Commit 8511c7ac authored by Claudio Valerio's avatar Claudio Valerio

some missing headers

parent 3988bc83
...@@ -3,24 +3,24 @@ ...@@ -3,24 +3,24 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
#include "UBCFFAdaptor.h" #include "UBCFFAdaptor.h"
#include <QtCore> #include <QtCore>
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -19,135 +19,135 @@ ...@@ -19,135 +19,135 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBCFFSUBSETADAPTOR_H #ifndef UBCFFSUBSETADAPTOR_H
#define UBCFFSUBSETADAPTOR_H #define UBCFFSUBSETADAPTOR_H
#include <QtXml> #include <QtXml>
#include <QString> #include <QString>
#include <QStack> #include <QStack>
#include <QDomDocument> #include <QDomDocument>
#include <QHash> #include <QHash>
class UBDocumentProxy; class UBDocumentProxy;
class UBGraphicsScene; class UBGraphicsScene;
class QSvgGenerator; class QSvgGenerator;
class UBGraphicsSvgItem; class UBGraphicsSvgItem;
class UBGraphicsPixmapItem; class UBGraphicsPixmapItem;
class UBGraphicsItemDelegate; class UBGraphicsItemDelegate;
class QTransform; class QTransform;
class QPainter; class QPainter;
class UBGraphicsItem; class UBGraphicsItem;
class QGraphicsItem; class QGraphicsItem;
class QTextBlockFormat; class QTextBlockFormat;
class QTextCharFormat; class QTextCharFormat;
class QTextCursor; class QTextCursor;
class UBGraphicsStrokesGroup; class UBGraphicsStrokesGroup;
class UBCFFSubsetAdaptor class UBCFFSubsetAdaptor
{ {
public: public:
UBCFFSubsetAdaptor(); UBCFFSubsetAdaptor();
static bool ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument); static bool ConvertCFFFileToUbz(QString &cffSourceFile, UBDocumentProxy* pDocument);
private: private:
class UBCFFSubsetReader class UBCFFSubsetReader
{ {
public: public:
UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content); UBCFFSubsetReader(UBDocumentProxy *proxy, QFile *content);
~UBCFFSubsetReader(); ~UBCFFSubsetReader();
UBDocumentProxy *mProxy; UBDocumentProxy *mProxy;
QString pwdContent; QString pwdContent;
bool parse(); bool parse();
private: private:
QString mTempFilePath; QString mTempFilePath;
UBGraphicsScene *mCurrentScene; UBGraphicsScene *mCurrentScene;
QRectF mCurrentSceneRect; QRectF mCurrentSceneRect;
QString mIndent; QString mIndent;
QRectF mViewBox; QRectF mViewBox;
QRectF mViewPort; QRectF mViewPort;
qreal mVBTransFactor; qreal mVBTransFactor;
QPointF mViewBoxCenter; QPointF mViewBoxCenter;
QSize mSize; QSize mSize;
QPointF mShiftVector; QPointF mShiftVector;
bool mSvgGSectionIsOpened; bool mSvgGSectionIsOpened;
UBGraphicsGroupContainerItem *mGSectionContainer; UBGraphicsGroupContainerItem *mGSectionContainer;
private: private:
QDomDocument mDOMdoc; QDomDocument mDOMdoc;
QDomNode mCurrentDOMElement; QDomNode mCurrentDOMElement;
QHash<QString, UBGraphicsItem*> persistedItems; QHash<QString, UBGraphicsItem*> persistedItems;
QMap<QString, QString> mRefToUuidMap; QMap<QString, QString> mRefToUuidMap;
QDir mTmpFlashDir; QDir mTmpFlashDir;
void addItemToGSection(QGraphicsItem *item); void addItemToGSection(QGraphicsItem *item);
bool hashElements(); bool hashElements();
void addExtentionsToHash(QDomElement *parent, QDomElement *topGroup); void addExtentionsToHash(QDomElement *parent, QDomElement *topGroup);
void hashSvg(QDomNode *parent, QString prefix = ""); void hashSvg(QDomNode *parent, QString prefix = "");
void hashSiblingIwbElements(QDomElement *parent, QDomElement *topGroup = 0); void hashSiblingIwbElements(QDomElement *parent, QDomElement *topGroup = 0);
inline void parseSvgSectionAttr(const QDomElement &); inline void parseSvgSectionAttr(const QDomElement &);
bool parseSvgPage(const QDomElement &parent); bool parseSvgPage(const QDomElement &parent);
bool parseSvgPageset(const QDomElement &parent); bool parseSvgPageset(const QDomElement &parent);
bool parseSvgElement(const QDomElement &parent); bool parseSvgElement(const QDomElement &parent);
bool parseIwbMeta(const QDomElement &element); bool parseIwbMeta(const QDomElement &element);
bool parseSvg(const QDomElement &svgSection); bool parseSvg(const QDomElement &svgSection);
inline bool parseGSection(const QDomElement &element); inline bool parseGSection(const QDomElement &element);
inline bool parseSvgSwitchSection(const QDomElement &element); inline bool parseSvgSwitchSection(const QDomElement &element);
inline bool parseSvgRect(const QDomElement &element); inline bool parseSvgRect(const QDomElement &element);
inline bool parseSvgEllipse(const QDomElement &element); inline bool parseSvgEllipse(const QDomElement &element);
inline bool parseSvgPolygon(const QDomElement &element); inline bool parseSvgPolygon(const QDomElement &element);
inline bool parseSvgPolyline(const QDomElement &element); inline bool parseSvgPolyline(const QDomElement &element);
inline bool parseSvgText(const QDomElement &element); inline bool parseSvgText(const QDomElement &element);
inline bool parseSvgTextarea(const QDomElement &element); inline bool parseSvgTextarea(const QDomElement &element);
inline bool parseSvgImage(const QDomElement &element); inline bool parseSvgImage(const QDomElement &element);
inline bool parseSvgFlash(const QDomElement &element); inline bool parseSvgFlash(const QDomElement &element);
inline bool parseSvgAudio(const QDomElement &element); inline bool parseSvgAudio(const QDomElement &element);
inline bool parseSvgVideo(const QDomElement &element); inline bool parseSvgVideo(const QDomElement &element);
inline UBGraphicsGroupContainerItem *parseIwbGroup(QDomElement &parent); inline UBGraphicsGroupContainerItem *parseIwbGroup(QDomElement &parent);
inline bool parseIwbElement(QDomElement &element); inline bool parseIwbElement(QDomElement &element);
inline void parseTSpan(const QDomElement &parent, QPainter &painter inline void parseTSpan(const QDomElement &parent, QPainter &painter
, qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect , qreal &curX, qreal &curY, qreal &width, qreal &height, qreal &linespacing, QRectF &lastDrawnTextBoundingRect
, qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic , qreal &fontSize, QColor &fontColor, QString &fontFamily, QString &fontStretch, bool &italic
, int &fontWeight, int &textAlign, QTransform &fontTransform); , int &fontWeight, int &textAlign, QTransform &fontTransform);
inline void parseTSpan(const QDomElement &element, QTextCursor &cursor inline void parseTSpan(const QDomElement &element, QTextCursor &cursor
, QTextBlockFormat &blockFormat, QTextCharFormat &charFormat); , QTextBlockFormat &blockFormat, QTextCharFormat &charFormat);
inline void hashSceneItem(const QDomElement &element, UBGraphicsItem *item); inline void hashSceneItem(const QDomElement &element, UBGraphicsItem *item);
// to kill // to kill
inline void parseTextAttributes(const QDomElement &element, qreal &fontSize, QColor &fontColor, inline void parseTextAttributes(const QDomElement &element, qreal &fontSize, QColor &fontColor,
QString &fontFamily, QString &fontStretch, bool &italic, QString &fontFamily, QString &fontStretch, bool &italic,
int &fontWeight, int &textAlign, QTransform &fontTransform); int &fontWeight, int &textAlign, QTransform &fontTransform);
inline void parseTextAttributes(const QDomElement &element, QFont &font, QColor); inline void parseTextAttributes(const QDomElement &element, QFont &font, QColor);
inline void readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format); inline void readTextBlockAttr(const QDomElement &element, QTextBlockFormat &format);
inline void readTextCharAttr(const QDomElement &element, QTextCharFormat &format); inline void readTextCharAttr(const QDomElement &element, QTextCharFormat &format);
//elements parsing methods //elements parsing methods
bool parseDoc(); bool parseDoc();
bool createNewScene(); bool createNewScene();
bool persistCurrentScene(); bool persistCurrentScene();
bool persistScenes(); bool persistScenes();
// helper methods // helper methods
void repositionSvgItem(QGraphicsItem *item, qreal width, qreal height, void repositionSvgItem(QGraphicsItem *item, qreal width, qreal height,
qreal x, qreal y, qreal x, qreal y,
QTransform &transform); QTransform &transform);
QColor colorFromString(const QString& clrString); QColor colorFromString(const QString& clrString);
QTransform transformFromString(const QString trString, QGraphicsItem *item = 0); QTransform transformFromString(const QString trString, QGraphicsItem *item = 0);
bool getViewBoxDimenstions(const QString& viewBox); bool getViewBoxDimenstions(const QString& viewBox);
QSvgGenerator* createSvgGenerator(qreal width, qreal height); QSvgGenerator* createSvgGenerator(qreal width, qreal height);
bool getTempFileName(); bool getTempFileName();
inline bool strToBool(QString); inline bool strToBool(QString);
bool createTempFlashPath(); bool createTempFlashPath();
}; };
}; };
#endif // UBCFFSUBSETADAPTOR_H #endif // UBCFFSUBSETADAPTOR_H
...@@ -19,270 +19,270 @@ ...@@ -19,270 +19,270 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QDir> #include <QDir>
#include <QList> #include <QList>
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBDocumentManager.h" #include "core/UBDocumentManager.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "domain/UBGraphicsPDFItem.h" #include "domain/UBGraphicsPDFItem.h"
#include "frameworks/UBFileSystemUtils.h" #include "frameworks/UBFileSystemUtils.h"
#include "pdf/PDFRenderer.h" #include "pdf/PDFRenderer.h"
#include "UBCFFSubsetAdaptor.h" #include "UBCFFSubsetAdaptor.h"
#include "UBImportCFF.h" #include "UBImportCFF.h"
#include "globals/UBGlobals.h" #include "globals/UBGlobals.h"
THIRD_PARTY_WARNINGS_DISABLE THIRD_PARTY_WARNINGS_DISABLE
#include "quazip.h" #include "quazip.h"
#include "quazipfile.h" #include "quazipfile.h"
#include "quazipfileinfo.h" #include "quazipfileinfo.h"
THIRD_PARTY_WARNINGS_ENABLE THIRD_PARTY_WARNINGS_ENABLE
#include "core/memcheck.h" #include "core/memcheck.h"
UBImportCFF::UBImportCFF(QObject *parent) UBImportCFF::UBImportCFF(QObject *parent)
: UBDocumentBasedImportAdaptor(parent) : UBDocumentBasedImportAdaptor(parent)
{ {
// NOOP // NOOP
} }
UBImportCFF::~UBImportCFF() UBImportCFF::~UBImportCFF()
{ {
// NOOP // NOOP
} }
QStringList UBImportCFF::supportedExtentions() QStringList UBImportCFF::supportedExtentions()
{ {
return QStringList("iwb"); return QStringList("iwb");
} }
QString UBImportCFF::importFileFilter() QString UBImportCFF::importFileFilter()
{ {
QString filter = tr("Common File Format ("); QString filter = tr("Common File Format (");
QStringList formats = supportedExtentions(); QStringList formats = supportedExtentions();
bool isFirst = true; bool isFirst = true;
foreach(QString format, formats) foreach(QString format, formats)
{ {
if(isFirst) if(isFirst)
isFirst = false; isFirst = false;
else else
filter.append(" "); filter.append(" ");
filter.append("*."+format); filter.append("*."+format);
} }
filter.append(")"); filter.append(")");
return filter; return filter;
} }
bool UBImportCFF::addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile) bool UBImportCFF::addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile)
{ {
QFileInfo fi(pFile); QFileInfo fi(pFile);
UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true); UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
// first unzip the file to the correct place // first unzip the file to the correct place
//TODO create temporary path for iwb file content //TODO create temporary path for iwb file content
QString path = QDir::tempPath(); QString path = QDir::tempPath();
QString documentRootFolder = expandFileToDir(pFile, path); QString documentRootFolder = expandFileToDir(pFile, path);
QString contentFile; QString contentFile;
if (documentRootFolder.isEmpty()) //if file has failed to unzip it is probably just xml file if (documentRootFolder.isEmpty()) //if file has failed to unzip it is probably just xml file
contentFile = pFile.fileName(); contentFile = pFile.fileName();
else //get path to content xml (according to iwbcff specification) else //get path to content xml (according to iwbcff specification)
contentFile = documentRootFolder.append("/content.xml"); contentFile = documentRootFolder.append("/content.xml");
if(!contentFile.length()){ if(!contentFile.length()){
UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName())); UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
return false; return false;
} }
else{ else{
//TODO convert expanded CFF file content to the destination document //TODO convert expanded CFF file content to the destination document
//create destination document proxy //create destination document proxy
//fill metadata and save //fill metadata and save
UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath()); UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
QDir dir; QDir dir;
dir.mkdir(destDocument->persistencePath()); dir.mkdir(destDocument->persistencePath());
//try to import cff to document //try to import cff to document
if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument)) if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
{ {
UBPersistenceManager::persistenceManager()->addDirectoryContentToDocument(destDocument->persistencePath(), pDocument); UBPersistenceManager::persistenceManager()->addDirectoryContentToDocument(destDocument->persistencePath(), pDocument);
UBFileSystemUtils::deleteDir(destDocument->persistencePath()); UBFileSystemUtils::deleteDir(destDocument->persistencePath());
delete destDocument; delete destDocument;
UBApplication::showMessage(tr("Import successful.")); UBApplication::showMessage(tr("Import successful."));
return true; return true;
} }
else else
{ {
UBFileSystemUtils::deleteDir(destDocument->persistencePath()); UBFileSystemUtils::deleteDir(destDocument->persistencePath());
delete destDocument; delete destDocument;
UBApplication::showMessage(tr("Import failed.")); UBApplication::showMessage(tr("Import failed."));
return false; return false;
} }
} }
} }
QString UBImportCFF::expandFileToDir(const QFile& pZipFile, const QString& pDir) QString UBImportCFF::expandFileToDir(const QFile& pZipFile, const QString& pDir)
{ {
QuaZip zip(pZipFile.fileName()); QuaZip zip(pZipFile.fileName());
if(!zip.open(QuaZip::mdUnzip)) { if(!zip.open(QuaZip::mdUnzip)) {
qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError(); qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError();
return ""; return "";
} }
zip.setFileNameCodec("UTF-8"); zip.setFileNameCodec("UTF-8");
QuaZipFileInfo info; QuaZipFileInfo info;
QuaZipFile file(&zip); QuaZipFile file(&zip);
//create unique cff document root fodler //create unique cff document root fodler
//use current date/time and temp number for folder name //use current date/time and temp number for folder name
QString documentRootFolder; QString documentRootFolder;
int tmpNumber = 0; int tmpNumber = 0;
QDir rootDir; QDir rootDir;
while (true) { while (true) {
QString tempPath = QString("%1/sank%2.%3") QString tempPath = QString("%1/sank%2.%3")
.arg(pDir) .arg(pDir)
.arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm")) .arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_HH-mm"))
.arg(tmpNumber); .arg(tmpNumber);
if (!rootDir.exists(tempPath)) { if (!rootDir.exists(tempPath)) {
documentRootFolder = tempPath; documentRootFolder = tempPath;
break; break;
} }
tmpNumber++; tmpNumber++;
if (tmpNumber == 100000) { if (tmpNumber == 100000) {
qWarning() << "Import failed. Failed to create temporary directory for iwb file"; qWarning() << "Import failed. Failed to create temporary directory for iwb file";
return ""; return "";
} }
} }
if (!rootDir.mkdir(documentRootFolder)) { if (!rootDir.mkdir(documentRootFolder)) {
qWarning() << "Import failed. Couse: failed to create temp folder for cff package"; qWarning() << "Import failed. Couse: failed to create temp folder for cff package";
} }
QFile out; QFile out;
char c; char c;
for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
if(!zip.getCurrentFileInfo(&info)) { if(!zip.getCurrentFileInfo(&info)) {
//TOD UB 4.3 O display error to user or use crash reporter //TOD UB 4.3 O display error to user or use crash reporter
qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError(); qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
return ""; return "";
} }
// if(!file.open(QIODevice::ReadOnly)) { // if(!file.open(QIODevice::ReadOnly)) {
// qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError(); // qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError();
// return ""; // return "";
// } // }
file.open(QIODevice::ReadOnly); file.open(QIODevice::ReadOnly);
if(file.getZipError()!= UNZ_OK) { if(file.getZipError()!= UNZ_OK) {
qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError(); qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError();
return ""; return "";
} }
QString newFileName = documentRootFolder + "/" + file.getActualFileName(); QString newFileName = documentRootFolder + "/" + file.getActualFileName();
QFileInfo newFileInfo(newFileName); QFileInfo newFileInfo(newFileName);
rootDir.mkpath(newFileInfo.absolutePath()); rootDir.mkpath(newFileInfo.absolutePath());
out.setFileName(newFileName); out.setFileName(newFileName);
out.open(QIODevice::WriteOnly); out.open(QIODevice::WriteOnly);
while(file.getChar(&c)) while(file.getChar(&c))
out.putChar(c); out.putChar(c);
out.close(); out.close();
if(file.getZipError()!=UNZ_OK) { if(file.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: " << zip.getZipError(); qWarning() << "Import failed. Cause: " << zip.getZipError();
return ""; return "";
} }
if(!file.atEnd()) { if(!file.atEnd()) {
qWarning() << "Import failed. Cause: read all but not EOF"; qWarning() << "Import failed. Cause: read all but not EOF";
return ""; return "";
} }
file.close(); file.close();
if(file.getZipError()!=UNZ_OK) { if(file.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: file.close(): " << file.getZipError(); qWarning() << "Import failed. Cause: file.close(): " << file.getZipError();
return ""; return "";
} }
} }
zip.close(); zip.close();
if(zip.getZipError()!=UNZ_OK) { if(zip.getZipError()!=UNZ_OK) {
qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError(); qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError();
return ""; return "";
} }
return documentRootFolder; return documentRootFolder;
} }
UBDocumentProxy* UBImportCFF::importFile(const QFile& pFile, const QString& pGroup) UBDocumentProxy* UBImportCFF::importFile(const QFile& pFile, const QString& pGroup)
{ {
Q_UNUSED(pGroup); // group is defined in the imported file Q_UNUSED(pGroup); // group is defined in the imported file
QFileInfo fi(pFile); QFileInfo fi(pFile);
UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true); UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);
// first unzip the file to the correct place // first unzip the file to the correct place
//TODO create temporary path for iwb file content //TODO create temporary path for iwb file content
QString path = QDir::tempPath(); QString path = QDir::tempPath();
QString documentRootFolder = expandFileToDir(pFile, path); QString documentRootFolder = expandFileToDir(pFile, path);
QString contentFile; QString contentFile;
if (documentRootFolder.isEmpty()) if (documentRootFolder.isEmpty())
//if file has failed to umzip it is probably just xml file //if file has failed to umzip it is probably just xml file
contentFile = pFile.fileName(); contentFile = pFile.fileName();
else else
//get path to content xml //get path to content xml
contentFile = QString("%1/content.xml").arg(documentRootFolder); contentFile = QString("%1/content.xml").arg(documentRootFolder);
if(!contentFile.length()){ if(!contentFile.length()){
UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName())); UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
return 0; return 0;
} }
else{ else{
//create destination document proxy //create destination document proxy
//fill metadata and save //fill metadata and save
UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath()); UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
QDir dir; QDir dir;
dir.mkdir(destDocument->persistencePath()); dir.mkdir(destDocument->persistencePath());
if (pGroup.length() > 0) if (pGroup.length() > 0)
destDocument->setMetaData(UBSettings::documentGroupName, pGroup); destDocument->setMetaData(UBSettings::documentGroupName, pGroup);
if (fi.baseName() > 0) if (fi.baseName() > 0)
destDocument->setMetaData(UBSettings::documentName, fi.baseName()); destDocument->setMetaData(UBSettings::documentName, fi.baseName());
destDocument->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion); destDocument->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion);
destDocument->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime())); destDocument->setMetaData(UBSettings::documentUpdatedAt, UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
UBDocumentProxy* newDocument = NULL; UBDocumentProxy* newDocument = NULL;
//try to import cff to document //try to import cff to document
if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument)) if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
{ {
newDocument = UBPersistenceManager::persistenceManager()->createDocumentFromDir(destDocument->persistencePath()); newDocument = UBPersistenceManager::persistenceManager()->createDocumentFromDir(destDocument->persistencePath());
UBApplication::showMessage(tr("Import successful.")); UBApplication::showMessage(tr("Import successful."));
} }
else else
{ {
UBFileSystemUtils::deleteDir(destDocument->persistencePath()); UBFileSystemUtils::deleteDir(destDocument->persistencePath());
UBApplication::showMessage(tr("Import failed.")); UBApplication::showMessage(tr("Import failed."));
} }
delete destDocument; delete destDocument;
if (documentRootFolder.length() != 0) if (documentRootFolder.length() != 0)
UBFileSystemUtils::deleteDir(documentRootFolder); UBFileSystemUtils::deleteDir(documentRootFolder);
return newDocument; return newDocument;
} }
} }
...@@ -19,32 +19,32 @@ ...@@ -19,32 +19,32 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBIMPORTCFF_H #ifndef UBIMPORTCFF_H
#define UBIMPORTCFF_H #define UBIMPORTCFF_H
#include <QtGui> #include <QtGui>
#include "UBImportAdaptor.h" #include "UBImportAdaptor.h"
class UBDocumentProxy; class UBDocumentProxy;
class UBImportCFF : public UBDocumentBasedImportAdaptor class UBImportCFF : public UBDocumentBasedImportAdaptor
{ {
Q_OBJECT; Q_OBJECT;
public: public:
UBImportCFF(QObject *parent = 0); UBImportCFF(QObject *parent = 0);
virtual ~UBImportCFF(); virtual ~UBImportCFF();
virtual QStringList supportedExtentions(); virtual QStringList supportedExtentions();
virtual QString importFileFilter(); virtual QString importFileFilter();
virtual bool addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile); virtual bool addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile);
virtual UBDocumentProxy* importFile(const QFile& pFile, const QString& pGroup); virtual UBDocumentProxy* importFile(const QFile& pFile, const QString& pGroup);
private: private:
QString expandFileToDir(const QFile& pZipFile, const QString& pDir); QString expandFileToDir(const QFile& pZipFile, const QString& pDir);
}; };
#endif // UBIMPORTCFF_H #endif // UBIMPORTCFF_H
...@@ -19,249 +19,249 @@ ...@@ -19,249 +19,249 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBSVGSUBSETADAPTOR_H_ #ifndef UBSVGSUBSETADAPTOR_H_
#define UBSVGSUBSETADAPTOR_H_ #define UBSVGSUBSETADAPTOR_H_
#include <QtGui> #include <QtGui>
#include <QtXml> #include <QtXml>
#include "frameworks/UBGeometryUtils.h" #include "frameworks/UBGeometryUtils.h"
class UBGraphicsSvgItem; class UBGraphicsSvgItem;
class UBGraphicsPolygonItem; class UBGraphicsPolygonItem;
class UBGraphicsPixmapItem; class UBGraphicsPixmapItem;
class UBGraphicsPDFItem; class UBGraphicsPDFItem;
class UBGraphicsWidgetItem; class UBGraphicsWidgetItem;
class UBGraphicsMediaItem; class UBGraphicsMediaItem;
class UBGraphicsAppleWidgetItem; class UBGraphicsAppleWidgetItem;
class UBGraphicsW3CWidgetItem; class UBGraphicsW3CWidgetItem;
class UBGraphicsTextItem; class UBGraphicsTextItem;
class UBGraphicsCurtainItem; class UBGraphicsCurtainItem;
class UBGraphicsRuler; class UBGraphicsRuler;
class UBGraphicsCompass; class UBGraphicsCompass;
class UBGraphicsProtractor; class UBGraphicsProtractor;
class UBGraphicsScene; class UBGraphicsScene;
class UBDocumentProxy; class UBDocumentProxy;
class UBGraphicsStroke; class UBGraphicsStroke;
class UBPersistenceManager; class UBPersistenceManager;
class UBGraphicsTriangle; class UBGraphicsTriangle;
class UBGraphicsCache; class UBGraphicsCache;
class IDataStorage; class IDataStorage;
class UBGraphicsGroupContainerItem; class UBGraphicsGroupContainerItem;
class UBGraphicsStrokesGroup; class UBGraphicsStrokesGroup;
class UBSvgSubsetAdaptor class UBSvgSubsetAdaptor
{ {
private: private:
UBSvgSubsetAdaptor() {;} UBSvgSubsetAdaptor() {;}
virtual ~UBSvgSubsetAdaptor() {;} virtual ~UBSvgSubsetAdaptor() {;}
public: public:
static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const int pageIndex); static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const int pageIndex);
static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex); static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
static void upgradeScene(UBDocumentProxy* proxy, const int pageIndex); static void upgradeScene(UBDocumentProxy* proxy, const int pageIndex);
static QUuid sceneUuid(UBDocumentProxy* proxy, const int pageIndex); static QUuid sceneUuid(UBDocumentProxy* proxy, const int pageIndex);
static void setSceneUuid(UBDocumentProxy* proxy, const int pageIndex, QUuid pUuid); static void setSceneUuid(UBDocumentProxy* proxy, const int pageIndex, QUuid pUuid);
static bool addElementToBeStored(QString domName,IDataStorage* dataStorageClass); static bool addElementToBeStored(QString domName,IDataStorage* dataStorageClass);
static void convertPDFObjectsToImages(UBDocumentProxy* proxy); static void convertPDFObjectsToImages(UBDocumentProxy* proxy);
static void convertSvgImagesToImages(UBDocumentProxy* proxy); static void convertSvgImagesToImages(UBDocumentProxy* proxy);
static QMap<QString,IDataStorage*> getAdditionalElementToStore() { return additionalElementToStore;} static QMap<QString,IDataStorage*> getAdditionalElementToStore() { return additionalElementToStore;}
static const QString nsSvg; static const QString nsSvg;
static const QString nsXLink; static const QString nsXLink;
static const QString nsXHtml; static const QString nsXHtml;
static const QString nsUb; static const QString nsUb;
static const QString xmlTrue; static const QString xmlTrue;
static const QString xmlFalse; static const QString xmlFalse;
static const QString sFontSizePrefix; static const QString sFontSizePrefix;
static const QString sPixelUnit; static const QString sPixelUnit;
static const QString sFontWeightPrefix; static const QString sFontWeightPrefix;
static const QString sFontStylePrefix; static const QString sFontStylePrefix;
static QString readTeacherGuideNode(int sceneIndex); static QString readTeacherGuideNode(int sceneIndex);
private: private:
static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const QByteArray& pArray); static UBGraphicsScene* loadScene(UBDocumentProxy* proxy, const QByteArray& pArray);
static QDomDocument loadSceneDocument(UBDocumentProxy* proxy, const int pPageIndex); static QDomDocument loadSceneDocument(UBDocumentProxy* proxy, const int pPageIndex);
static QString uniboardDocumentNamespaceUriFromVersion(int fileVersion); static QString uniboardDocumentNamespaceUriFromVersion(int fileVersion);
static const QString sFormerUniboardDocumentNamespaceUri; static const QString sFormerUniboardDocumentNamespaceUri;
static QString toSvgTransform(const QMatrix& matrix); static QString toSvgTransform(const QMatrix& matrix);
static QMatrix fromSvgTransform(const QString& transform); static QMatrix fromSvgTransform(const QString& transform);
static QMap<QString,IDataStorage*> additionalElementToStore; static QMap<QString,IDataStorage*> additionalElementToStore;
class UBSvgSubsetReader class UBSvgSubsetReader
{ {
public: public:
UBSvgSubsetReader(UBDocumentProxy* proxy, const QByteArray& pXmlData); UBSvgSubsetReader(UBDocumentProxy* proxy, const QByteArray& pXmlData);
virtual ~UBSvgSubsetReader(){} virtual ~UBSvgSubsetReader(){}
UBGraphicsScene* loadScene(); UBGraphicsScene* loadScene();
private: private:
UBGraphicsPolygonItem* polygonItemFromLineSvg(const QColor& pDefaultBrushColor); UBGraphicsPolygonItem* polygonItemFromLineSvg(const QColor& pDefaultBrushColor);
UBGraphicsPolygonItem* polygonItemFromPolygonSvg(const QColor& pDefaultBrushColor); UBGraphicsPolygonItem* polygonItemFromPolygonSvg(const QColor& pDefaultBrushColor);
QList<UBGraphicsPolygonItem*> polygonItemsFromPolylineSvg(const QColor& pDefaultColor); QList<UBGraphicsPolygonItem*> polygonItemsFromPolylineSvg(const QColor& pDefaultColor);
UBGraphicsPixmapItem* pixmapItemFromSvg(); UBGraphicsPixmapItem* pixmapItemFromSvg();
UBGraphicsSvgItem* svgItemFromSvg(); UBGraphicsSvgItem* svgItemFromSvg();
UBGraphicsPDFItem* pdfItemFromPDF(); UBGraphicsPDFItem* pdfItemFromPDF();
UBGraphicsMediaItem* videoItemFromSvg(); UBGraphicsMediaItem* videoItemFromSvg();
UBGraphicsMediaItem* audioItemFromSvg(); UBGraphicsMediaItem* audioItemFromSvg();
UBGraphicsAppleWidgetItem* graphicsAppleWidgetFromSvg(); UBGraphicsAppleWidgetItem* graphicsAppleWidgetFromSvg();
UBGraphicsW3CWidgetItem* graphicsW3CWidgetFromSvg(); UBGraphicsW3CWidgetItem* graphicsW3CWidgetFromSvg();
UBGraphicsTextItem* textItemFromSvg(); UBGraphicsTextItem* textItemFromSvg();
UBGraphicsCurtainItem* curtainItemFromSvg(); UBGraphicsCurtainItem* curtainItemFromSvg();
UBGraphicsRuler* rulerFromSvg(); UBGraphicsRuler* rulerFromSvg();
UBGraphicsCompass* compassFromSvg(); UBGraphicsCompass* compassFromSvg();
UBGraphicsProtractor* protractorFromSvg(); UBGraphicsProtractor* protractorFromSvg();
UBGraphicsTriangle* triangleFromSvg(); UBGraphicsTriangle* triangleFromSvg();
UBGraphicsCache* cacheFromSvg(); UBGraphicsCache* cacheFromSvg();
void readGroupRoot(); void readGroupRoot();
QGraphicsItem *readElementFromGroup(); QGraphicsItem *readElementFromGroup();
UBGraphicsGroupContainerItem* readGroup(); UBGraphicsGroupContainerItem* readGroup();
void graphicsItemFromSvg(QGraphicsItem* gItem); void graphicsItemFromSvg(QGraphicsItem* gItem);
qreal getZValueFromSvg(); qreal getZValueFromSvg();
QUuid getUuidFromSvg(); QUuid getUuidFromSvg();
QXmlStreamReader mXmlReader; QXmlStreamReader mXmlReader;
int mFileVersion; int mFileVersion;
UBDocumentProxy *mProxy; UBDocumentProxy *mProxy;
QString mDocumentPath; QString mDocumentPath;
QColor mGroupDarkBackgroundColor; QColor mGroupDarkBackgroundColor;
QColor mGroupLightBackgroundColor; QColor mGroupLightBackgroundColor;
qreal mGroupZIndex; qreal mGroupZIndex;
bool mGroupHasInfo; bool mGroupHasInfo;
QString mNamespaceUri; QString mNamespaceUri;
UBGraphicsScene *mScene; UBGraphicsScene *mScene;
QMap<QString,UBGraphicsStrokesGroup*> mStrokesList; QMap<QString,UBGraphicsStrokesGroup*> mStrokesList;
}; };
class UBSvgSubsetWriter class UBSvgSubsetWriter
{ {
public: public:
UBSvgSubsetWriter(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex); UBSvgSubsetWriter(UBDocumentProxy* proxy, UBGraphicsScene* pScene, const int pageIndex);
bool persistScene(int pageIndex); bool persistScene(int pageIndex);
virtual ~UBSvgSubsetWriter(){} virtual ~UBSvgSubsetWriter(){}
private: private:
void persistGroupToDom(QGraphicsItem *groupItem, QDomElement *curParent, QDomDocument *curDomDocument); void persistGroupToDom(QGraphicsItem *groupItem, QDomElement *curParent, QDomDocument *curDomDocument);
void persistStrokeToDom(QGraphicsItem *strokeItem, QDomElement *curParent, QDomDocument *curDomDocument); void persistStrokeToDom(QGraphicsItem *strokeItem, QDomElement *curParent, QDomDocument *curDomDocument);
void polygonItemToSvgPolygon(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo); void polygonItemToSvgPolygon(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
void polygonItemToSvgLine(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo); void polygonItemToSvgLine(UBGraphicsPolygonItem* polygonItem, bool groupHoldsInfo);
void strokeToSvgPolyline(UBGraphicsStroke* stroke, bool groupHoldsInfo); void strokeToSvgPolyline(UBGraphicsStroke* stroke, bool groupHoldsInfo);
void strokeToSvgPolygon(UBGraphicsStroke* stroke, bool groupHoldsInfo); void strokeToSvgPolygon(UBGraphicsStroke* stroke, bool groupHoldsInfo);
inline QString pointsToSvgPointsAttribute(QVector<QPointF> points) inline QString pointsToSvgPointsAttribute(QVector<QPointF> points)
{ {
UBGeometryUtils::crashPointList(points); UBGeometryUtils::crashPointList(points);
int pointsCount = points.size(); int pointsCount = points.size();
QString svgPoints; QString svgPoints;
int length = 0; int length = 0;
QString sBuf; QString sBuf;
for(int j = 0; j < pointsCount; j++) for(int j = 0; j < pointsCount; j++)
{ {
sBuf = "%1,%2 "; sBuf = "%1,%2 ";
const QPointF & point = points.at(j); const QPointF & point = points.at(j);
QString temp1 = "%1", temp2 = "%2"; QString temp1 = "%1", temp2 = "%2";
temp1 = temp1.arg(point.x()); temp1 = temp1.arg(point.x());
temp2 = temp2.arg(point.y()); temp2 = temp2.arg(point.y());
QLocale loc(QLocale::C); QLocale loc(QLocale::C);
sBuf = sBuf.arg(loc.toFloat(temp1)).arg(loc.toFloat(temp2)); sBuf = sBuf.arg(loc.toFloat(temp1)).arg(loc.toFloat(temp2));
svgPoints.insert(length, sBuf); svgPoints.insert(length, sBuf);
length += sBuf.length(); length += sBuf.length();
} }
return svgPoints; return svgPoints;
} }
inline qreal trickAlpha(qreal alpha) inline qreal trickAlpha(qreal alpha)
{ {
qreal trickAlpha = alpha; qreal trickAlpha = alpha;
if(trickAlpha >= 0.2 && trickAlpha < 0.6){ if(trickAlpha >= 0.2 && trickAlpha < 0.6){
trickAlpha /= 5; trickAlpha /= 5;
}else if (trickAlpha < 0.8) }else if (trickAlpha < 0.8)
trickAlpha /= 3; trickAlpha /= 3;
return trickAlpha; return trickAlpha;
} }
void pixmapItemToLinkedImage(UBGraphicsPixmapItem *pixmapItem); void pixmapItemToLinkedImage(UBGraphicsPixmapItem *pixmapItem);
void svgItemToLinkedSvg(UBGraphicsSvgItem *svgItem); void svgItemToLinkedSvg(UBGraphicsSvgItem *svgItem);
void pdfItemToLinkedPDF(UBGraphicsPDFItem *pdfItem); void pdfItemToLinkedPDF(UBGraphicsPDFItem *pdfItem);
void videoItemToLinkedVideo(UBGraphicsMediaItem *videoItem); void videoItemToLinkedVideo(UBGraphicsMediaItem *videoItem);
void audioItemToLinkedAudio(UBGraphicsMediaItem *audioItem); void audioItemToLinkedAudio(UBGraphicsMediaItem *audioItem);
void graphicsItemToSvg(QGraphicsItem *item); void graphicsItemToSvg(QGraphicsItem *item);
void graphicsAppleWidgetToSvg(UBGraphicsAppleWidgetItem *item); void graphicsAppleWidgetToSvg(UBGraphicsAppleWidgetItem *item);
void graphicsW3CWidgetToSvg(UBGraphicsW3CWidgetItem *item); void graphicsW3CWidgetToSvg(UBGraphicsW3CWidgetItem *item);
void graphicsWidgetToSvg(UBGraphicsWidgetItem *item); void graphicsWidgetToSvg(UBGraphicsWidgetItem *item);
void textItemToSvg(UBGraphicsTextItem *item); void textItemToSvg(UBGraphicsTextItem *item);
void curtainItemToSvg(UBGraphicsCurtainItem *item); void curtainItemToSvg(UBGraphicsCurtainItem *item);
void rulerToSvg(UBGraphicsRuler *item); void rulerToSvg(UBGraphicsRuler *item);
void compassToSvg(UBGraphicsCompass *item); void compassToSvg(UBGraphicsCompass *item);
void protractorToSvg(UBGraphicsProtractor *item); void protractorToSvg(UBGraphicsProtractor *item);
void cacheToSvg(UBGraphicsCache* item); void cacheToSvg(UBGraphicsCache* item);
void triangleToSvg(UBGraphicsTriangle *item); void triangleToSvg(UBGraphicsTriangle *item);
void writeSvgElement(); void writeSvgElement();
private: private:
UBGraphicsScene* mScene; UBGraphicsScene* mScene;
QXmlStreamWriter mXmlWriter; QXmlStreamWriter mXmlWriter;
QString mDocumentPath; QString mDocumentPath;
int mPageIndex; int mPageIndex;
}; };
}; };
#endif /* UBSVGSUBSETADAPTOR_H_ */ #endif /* UBSVGSUBSETADAPTOR_H_ */
...@@ -19,169 +19,169 @@ ...@@ -19,169 +19,169 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBThumbnailAdaptor.h" #include "UBThumbnailAdaptor.h"
#include <QtCore> #include <QtCore>
#include "frameworks/UBFileSystemUtils.h" #include "frameworks/UBFileSystemUtils.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "gui/UBDockTeacherGuideWidget.h" #include "gui/UBDockTeacherGuideWidget.h"
#include "gui/UBTeacherGuideWidget.h" #include "gui/UBTeacherGuideWidget.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "board/UBBoardPaletteManager.h" #include "board/UBBoardPaletteManager.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "UBSvgSubsetAdaptor.h" #include "UBSvgSubsetAdaptor.h"
#include "core/memcheck.h" #include "core/memcheck.h"
void UBThumbnailAdaptor::generateMissingThumbnails(UBDocumentProxy* proxy) void UBThumbnailAdaptor::generateMissingThumbnails(UBDocumentProxy* proxy)
{ {
int existingPageCount = proxy->pageCount(); int existingPageCount = proxy->pageCount();
for (int iPageNo = 0; iPageNo < existingPageCount; ++iPageNo) for (int iPageNo = 0; iPageNo < existingPageCount; ++iPageNo)
{ {
QString thumbFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", iPageNo); QString thumbFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", iPageNo);
QFile thumbFile(thumbFileName); QFile thumbFile(thumbFileName);
if (!thumbFile.exists()) if (!thumbFile.exists())
{ {
bool displayMessage = (existingPageCount > 5); bool displayMessage = (existingPageCount > 5);
int thumbCount = 0; int thumbCount = 0;
UBGraphicsScene* scene = UBSvgSubsetAdaptor::loadScene(proxy, iPageNo); UBGraphicsScene* scene = UBSvgSubsetAdaptor::loadScene(proxy, iPageNo);
if (scene) if (scene)
{ {
thumbCount++; thumbCount++;
if (displayMessage && thumbCount == 1) if (displayMessage && thumbCount == 1)
UBApplication::showMessage(tr("Generating preview thumbnails ...")); UBApplication::showMessage(tr("Generating preview thumbnails ..."));
persistScene(proxy, scene, iPageNo); persistScene(proxy, scene, iPageNo);
} }
if (displayMessage && thumbCount > 0) if (displayMessage && thumbCount > 0)
UBApplication::showMessage(tr("%1 thumbnails generated ...").arg(thumbCount)); UBApplication::showMessage(tr("%1 thumbnails generated ...").arg(thumbCount));
} }
} }
} }
const QPixmap* UBThumbnailAdaptor::get(UBDocumentProxy* proxy, int pageIndex) const QPixmap* UBThumbnailAdaptor::get(UBDocumentProxy* proxy, int pageIndex)
{ {
QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex); QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
QFile file(fileName); QFile file(fileName);
if (!file.exists()) if (!file.exists())
{ {
generateMissingThumbnails(proxy); generateMissingThumbnails(proxy);
} }
QPixmap* pix = new QPixmap(); QPixmap* pix = new QPixmap();
if (file.exists()) if (file.exists())
{ {
//Warning. Works only with modified Qt //Warning. Works only with modified Qt
#ifdef Q_WS_X11 #ifdef Q_WS_X11
pix->load(fileName, 0, Qt::AutoColor); pix->load(fileName, 0, Qt::AutoColor);
#else #else
pix->load(fileName, 0, Qt::AutoColor, false); pix->load(fileName, 0, Qt::AutoColor, false);
#endif #endif
} }
return pix; return pix;
} }
void UBThumbnailAdaptor::updateDocumentToHandleZeroPage(UBDocumentProxy* proxy) void UBThumbnailAdaptor::updateDocumentToHandleZeroPage(UBDocumentProxy* proxy)
{ {
if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()){ if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()){
QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", 0); QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", 0);
QFile file(fileName); QFile file(fileName);
if(!file.exists()){ if(!file.exists()){
UBPersistenceManager::persistenceManager()->persistDocumentScene(proxy,new UBGraphicsScene(proxy),0); UBPersistenceManager::persistenceManager()->persistDocumentScene(proxy,new UBGraphicsScene(proxy),0);
} }
} }
} }
void UBThumbnailAdaptor::load(UBDocumentProxy* proxy, QList<const QPixmap*>& list) void UBThumbnailAdaptor::load(UBDocumentProxy* proxy, QList<const QPixmap*>& list)
{ {
updateDocumentToHandleZeroPage(proxy); updateDocumentToHandleZeroPage(proxy);
generateMissingThumbnails(proxy); generateMissingThumbnails(proxy);
foreach(const QPixmap* pm, list) foreach(const QPixmap* pm, list)
delete pm; delete pm;
list.clear(); list.clear();
for(int i=0; i<proxy->pageCount(); i++) for(int i=0; i<proxy->pageCount(); i++)
list.append(get(proxy, i)); list.append(get(proxy, i));
} }
void UBThumbnailAdaptor::persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified) void UBThumbnailAdaptor::persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified)
{ {
QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex); QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
QFile thumbFile(fileName); QFile thumbFile(fileName);
if (pScene->isModified() || overrideModified || !thumbFile.exists() || UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()) if (pScene->isModified() || overrideModified || !thumbFile.exists() || UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())
{ {
qreal nominalWidth = pScene->nominalSize().width(); qreal nominalWidth = pScene->nominalSize().width();
qreal nominalHeight = pScene->nominalSize().height(); qreal nominalHeight = pScene->nominalSize().height();
qreal ratio = nominalWidth / nominalHeight; qreal ratio = nominalWidth / nominalHeight;
QRectF sceneRect = pScene->normalizedSceneRect(ratio); QRectF sceneRect = pScene->normalizedSceneRect(ratio);
qreal width = UBSettings::maxThumbnailWidth; qreal width = UBSettings::maxThumbnailWidth;
qreal height = width / ratio; qreal height = width / ratio;
QImage thumb(width, height, QImage::Format_ARGB32); QImage thumb(width, height, QImage::Format_ARGB32);
QRectF imageRect(0, 0, width, height); QRectF imageRect(0, 0, width, height);
QPainter painter(&thumb); QPainter painter(&thumb);
painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
if (pScene->isDarkBackground()) if (pScene->isDarkBackground())
{ {
painter.fillRect(imageRect, Qt::black); painter.fillRect(imageRect, Qt::black);
} }
else else
{ {
painter.fillRect(imageRect, Qt::white); painter.fillRect(imageRect, Qt::white);
} }
pScene->setRenderingContext(UBGraphicsScene::NonScreen); pScene->setRenderingContext(UBGraphicsScene::NonScreen);
pScene->setRenderingQuality(UBItem::RenderingQualityHigh); pScene->setRenderingQuality(UBItem::RenderingQualityHigh);
pScene->render(&painter, imageRect, sceneRect, Qt::KeepAspectRatio); pScene->render(&painter, imageRect, sceneRect, Qt::KeepAspectRatio);
if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()){ if(UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()){
QPixmap toque(":images/toque.svg"); QPixmap toque(":images/toque.svg");
painter.setOpacity(0.6); painter.setOpacity(0.6);
painter.drawPixmap(QPoint(width - toque.width(),0),toque); painter.drawPixmap(QPoint(width - toque.width(),0),toque);
} }
pScene->setRenderingContext(UBGraphicsScene::Screen); pScene->setRenderingContext(UBGraphicsScene::Screen);
pScene->setRenderingQuality(UBItem::RenderingQualityNormal); pScene->setRenderingQuality(UBItem::RenderingQualityNormal);
thumb.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(fileName, "JPG"); thumb.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(fileName, "JPG");
} }
} }
QUrl UBThumbnailAdaptor::thumbnailUrl(UBDocumentProxy* proxy, int pageIndex) QUrl UBThumbnailAdaptor::thumbnailUrl(UBDocumentProxy* proxy, int pageIndex)
{ {
QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex); QString fileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", pageIndex);
return QUrl::fromLocalFile(fileName); return QUrl::fromLocalFile(fileName);
} }
...@@ -19,34 +19,34 @@ ...@@ -19,34 +19,34 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBTHUMBNAILADAPTOR_H #ifndef UBTHUMBNAILADAPTOR_H
#define UBTHUMBNAILADAPTOR_H #define UBTHUMBNAILADAPTOR_H
#include <QtCore> #include <QtCore>
class UBDocument; class UBDocument;
class UBDocumentProxy; class UBDocumentProxy;
class UBGraphicsScene; class UBGraphicsScene;
class UBThumbnailAdaptor //static class class UBThumbnailAdaptor //static class
{ {
Q_DECLARE_TR_FUNCTIONS(UBThumbnailAdaptor) Q_DECLARE_TR_FUNCTIONS(UBThumbnailAdaptor)
public: public:
static QUrl thumbnailUrl(UBDocumentProxy* proxy, int pageIndex); static QUrl thumbnailUrl(UBDocumentProxy* proxy, int pageIndex);
static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified = false); static void persistScene(UBDocumentProxy* proxy, UBGraphicsScene* pScene, int pageIndex, bool overrideModified = false);
static const QPixmap* get(UBDocumentProxy* proxy, int index); static const QPixmap* get(UBDocumentProxy* proxy, int index);
static void load(UBDocumentProxy* proxy, QList<const QPixmap*>& list); static void load(UBDocumentProxy* proxy, QList<const QPixmap*>& list);
private: private:
static void generateMissingThumbnails(UBDocumentProxy* proxy); static void generateMissingThumbnails(UBDocumentProxy* proxy);
static void updateDocumentToHandleZeroPage(UBDocumentProxy* proxy); static void updateDocumentToHandleZeroPage(UBDocumentProxy* proxy);
UBThumbnailAdaptor() {} UBThumbnailAdaptor() {}
}; };
#endif // UBTHUMBNAILADAPTOR_H #endif // UBTHUMBNAILADAPTOR_H
...@@ -19,813 +19,813 @@ ...@@ -19,813 +19,813 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QFileInfo> #include <QFileInfo>
#include "UBDocumentPublisher.h" #include "UBDocumentPublisher.h"
#include "frameworks/UBPlatformUtils.h" #include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h" #include "frameworks/UBFileSystemUtils.h"
#include "frameworks/UBStringUtils.h" #include "frameworks/UBStringUtils.h"
#include "network/UBNetworkAccessManager.h" #include "network/UBNetworkAccessManager.h"
#include "network/UBServerXMLHttpRequest.h" #include "network/UBServerXMLHttpRequest.h"
#include "core/UBDocumentManager.h" #include "core/UBDocumentManager.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBApplicationController.h" #include "core/UBApplicationController.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "gui/UBMainWindow.h" #include "gui/UBMainWindow.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "document/UBDocumentContainer.h" #include "document/UBDocumentContainer.h"
#include "domain/UBGraphicsWidgetItem.h" #include "domain/UBGraphicsWidgetItem.h"
#include "globals/UBGlobals.h" #include "globals/UBGlobals.h"
THIRD_PARTY_WARNINGS_DISABLE THIRD_PARTY_WARNINGS_DISABLE
#include "quazip.h" #include "quazip.h"
#include "quazipfile.h" #include "quazipfile.h"
THIRD_PARTY_WARNINGS_ENABLE THIRD_PARTY_WARNINGS_ENABLE
#include "adaptors/UBExportFullPDF.h" #include "adaptors/UBExportFullPDF.h"
#include "adaptors/UBExportDocument.h" #include "adaptors/UBExportDocument.h"
#include "adaptors/UBSvgSubsetAdaptor.h" #include "adaptors/UBSvgSubsetAdaptor.h"
#include "UBSvgSubsetRasterizer.h" #include "UBSvgSubsetRasterizer.h"
#include "../../core/UBApplication.h" #include "../../core/UBApplication.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentPublisher::UBDocumentPublisher(UBDocumentProxy* pDocument, QObject *parent) UBDocumentPublisher::UBDocumentPublisher(UBDocumentProxy* pDocument, QObject *parent)
: QObject(parent) : QObject(parent)
, mSourceDocument(pDocument) , mSourceDocument(pDocument)
, mUsername("") , mUsername("")
, mPassword("") , mPassword("")
, bLoginCookieSet(false) , bLoginCookieSet(false)
{ {
init(); init();
} }
UBDocumentPublisher::~UBDocumentPublisher() UBDocumentPublisher::~UBDocumentPublisher()
{ {
} }
void UBDocumentPublisher::publish() void UBDocumentPublisher::publish()
{ {
//check that the username and password are stored on preferences //check that the username and password are stored on preferences
UBSettings* settings = UBSettings::settings(); UBSettings* settings = UBSettings::settings();
if(settings->communityUsername().isEmpty() || settings->communityPassword().isEmpty()){ if(settings->communityUsername().isEmpty() || settings->communityPassword().isEmpty()){
UBApplication::showMessage(tr("Credentials has to not been filled out yet.")); UBApplication::showMessage(tr("Credentials has to not been filled out yet."));
qDebug() << "trying to connect to community without the required credentials"; qDebug() << "trying to connect to community without the required credentials";
return; return;
} }
mUsername = settings->communityUsername(); mUsername = settings->communityUsername();
mPassword = settings->communityPassword(); mPassword = settings->communityPassword();
UBPublicationDlg dlg; UBPublicationDlg dlg;
if(QDialog::Accepted == dlg.exec()) if(QDialog::Accepted == dlg.exec())
{ {
mDocInfos.title = dlg.title(); mDocInfos.title = dlg.title();
mDocInfos.description = dlg.description(); mDocInfos.description = dlg.description();
buildUbwFile(); buildUbwFile();
UBApplication::showMessage(tr("Uploading Sankore File on Web.")); UBApplication::showMessage(tr("Uploading Sankore File on Web."));
sendUbw(mUsername, mPassword); sendUbw(mUsername, mPassword);
} }
} }
void UBDocumentPublisher::buildUbwFile() void UBDocumentPublisher::buildUbwFile()
{ {
QDir d; QDir d;
d.mkpath(UBFileSystemUtils::defaultTempDirPath()); d.mkpath(UBFileSystemUtils::defaultTempDirPath());
QString tmpDir = UBFileSystemUtils::createTempDir(); QString tmpDir = UBFileSystemUtils::createTempDir();
if (UBFileSystemUtils::copyDir(mSourceDocument->persistencePath(), tmpDir)) if (UBFileSystemUtils::copyDir(mSourceDocument->persistencePath(), tmpDir))
{ {
QString documentName = mSourceDocument->name(); QString documentName = mSourceDocument->name();
mPublishingPath = tmpDir; mPublishingPath = tmpDir;
mPublishingSize = mSourceDocument->pageCount(); mPublishingSize = mSourceDocument->pageCount();
rasterizeScenes(); rasterizeScenes();
upgradeDocumentForPublishing(); upgradeDocumentForPublishing();
UBExportFullPDF pdfExporter; UBExportFullPDF pdfExporter;
pdfExporter.setVerbode(false); pdfExporter.setVerbode(false);
pdfExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".pdf"); pdfExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".pdf");
UBExportDocument ubzExporter; UBExportDocument ubzExporter;
ubzExporter.setVerbode(false); ubzExporter.setVerbode(false);
ubzExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".ubz"); ubzExporter.persistsDocument(mSourceDocument, mPublishingPath + "/" + documentName + ".ubz");
// remove all useless files // remove all useless files
for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) { for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) {
QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.svg",pageIndex); QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.svg",pageIndex);
QFile::remove(filename); QFile::remove(filename);
} }
UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::imageDirectory); UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::imageDirectory);
UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::objectDirectory); UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::objectDirectory);
UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::videoDirectory); UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::videoDirectory);
UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::audioDirectory); UBFileSystemUtils::deleteDir(mPublishingPath + "/" + UBPersistenceManager::audioDirectory);
mTmpZipFile = UBFileSystemUtils::defaultTempDirPath() + "/" + UBStringUtils::toCanonicalUuid(QUuid::createUuid()) + ".ubw~"; mTmpZipFile = UBFileSystemUtils::defaultTempDirPath() + "/" + UBStringUtils::toCanonicalUuid(QUuid::createUuid()) + ".ubw~";
QuaZip zip(mTmpZipFile); QuaZip zip(mTmpZipFile);
zip.setFileNameCodec("UTF-8"); zip.setFileNameCodec("UTF-8");
if (!zip.open(QuaZip::mdCreate)) if (!zip.open(QuaZip::mdCreate))
{ {
qWarning() << "Export failed. Cause: zip.open(): " << zip.getZipError() << "," << mTmpZipFile; qWarning() << "Export failed. Cause: zip.open(): " << zip.getZipError() << "," << mTmpZipFile;
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
return; return;
} }
QuaZipFile outFile(&zip); QuaZipFile outFile(&zip);
if (!UBFileSystemUtils::compressDirInZip(mPublishingPath, "", &outFile, true)) if (!UBFileSystemUtils::compressDirInZip(mPublishingPath, "", &outFile, true))
{ {
qWarning("Export failed. compressDirInZip failed ..."); qWarning("Export failed. compressDirInZip failed ...");
zip.close(); zip.close();
UBApplication::showMessage(tr("Export failed.")); UBApplication::showMessage(tr("Export failed."));
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
return; return;
} }
if (zip.getZipError() != 0) if (zip.getZipError() != 0)
{ {
qWarning("Export failed. Cause: zip.close(): %d", zip.getZipError()); qWarning("Export failed. Cause: zip.close(): %d", zip.getZipError());
zip.close(); zip.close();
UBApplication::showMessage(tr("Export failed.")); UBApplication::showMessage(tr("Export failed."));
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
return; return;
} }
zip.close(); zip.close();
} }
else else
{ {
UBApplication::showMessage(tr("Export canceled ...")); UBApplication::showMessage(tr("Export canceled ..."));
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
} }
} }
void UBDocumentPublisher::rasterizeScenes() void UBDocumentPublisher::rasterizeScenes()
{ {
for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
{ {
UBApplication::showMessage(tr("Converting page %1/%2 ...").arg(UBDocumentContainer::pageFromSceneIndex(pageIndex)).arg(mPublishingSize), true); UBApplication::showMessage(tr("Converting page %1/%2 ...").arg(UBDocumentContainer::pageFromSceneIndex(pageIndex)).arg(mPublishingSize), true);
UBDocumentProxy publishingDocument(mPublishingPath); UBDocumentProxy publishingDocument(mPublishingPath);
UBSvgSubsetRasterizer rasterizer(&publishingDocument, pageIndex); UBSvgSubsetRasterizer rasterizer(&publishingDocument, pageIndex);
QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.jpg",pageIndex); QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.jpg",pageIndex);
rasterizer.rasterizeToFile(filename); rasterizer.rasterizeToFile(filename);
} }
} }
void UBDocumentPublisher::updateGoogleMapApiKey() void UBDocumentPublisher::updateGoogleMapApiKey()
{ {
QDir widgestDir(mPublishingPath + "/" + UBPersistenceManager::widgetDirectory); QDir widgestDir(mPublishingPath + "/" + UBPersistenceManager::widgetDirectory);
QString uniboardWebGoogleMapApiKey = UBSettings::settings()->uniboardWebGoogleMapApiKey->get().toString(); QString uniboardWebGoogleMapApiKey = UBSettings::settings()->uniboardWebGoogleMapApiKey->get().toString();
foreach(QFileInfo dirInfo, widgestDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) foreach(QFileInfo dirInfo, widgestDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
{ {
QString config = UBFileSystemUtils::readTextFile(dirInfo.absoluteFilePath() + "/config.xml").toLower(); QString config = UBFileSystemUtils::readTextFile(dirInfo.absoluteFilePath() + "/config.xml").toLower();
if (config.contains("google") && config.contains("map")) if (config.contains("google") && config.contains("map"))
{ {
QDir widgetDir(dirInfo.absoluteFilePath()); QDir widgetDir(dirInfo.absoluteFilePath());
foreach(QFileInfo fileInfo, widgetDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot)) foreach(QFileInfo fileInfo, widgetDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot))
{ {
QFile file(fileInfo.absoluteFilePath()); QFile file(fileInfo.absoluteFilePath());
if (file.open(QIODevice::ReadWrite)) if (file.open(QIODevice::ReadWrite))
{ {
QTextStream stream(&file); QTextStream stream(&file);
QString content = stream.readAll(); QString content = stream.readAll();
if (content.contains("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og")) if (content.contains("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og"))
{ {
content.replace("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og", content.replace("ABQIAAAA6vtVqAUu8kZ_eTz7c8kwSBT9UCAhw_xm0LNFHsWmQxTJAdp5lxSY_5r-lZriY_7sACaMnl80JcX6Og",
uniboardWebGoogleMapApiKey); uniboardWebGoogleMapApiKey);
file.resize(0); file.resize(0);
file.write(content.toUtf8()); file.write(content.toUtf8());
} }
file.close(); file.close();
} }
} }
} }
} }
} }
void UBDocumentPublisher::upgradeDocumentForPublishing() void UBDocumentPublisher::upgradeDocumentForPublishing()
{ {
for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++) for (int pageIndex = 0; pageIndex < mPublishingSize; pageIndex++)
{ {
UBDocumentProxy publishingDocument(mPublishingPath); UBDocumentProxy publishingDocument(mPublishingPath);
UBGraphicsScene *scene = UBSvgSubsetAdaptor::loadScene(&publishingDocument, pageIndex); UBGraphicsScene *scene = UBSvgSubsetAdaptor::loadScene(&publishingDocument, pageIndex);
QList<UBGraphicsW3CWidgetItem*> widgets; QList<UBGraphicsW3CWidgetItem*> widgets;
foreach(QGraphicsItem* item, scene->items()){ foreach(QGraphicsItem* item, scene->items()){
UBGraphicsW3CWidgetItem *widgetItem = dynamic_cast<UBGraphicsW3CWidgetItem*>(item); UBGraphicsW3CWidgetItem *widgetItem = dynamic_cast<UBGraphicsW3CWidgetItem*>(item);
if(widgetItem){ if(widgetItem){
generateWidgetPropertyScript(widgetItem, UBDocumentContainer::pageFromSceneIndex(pageIndex)); generateWidgetPropertyScript(widgetItem, UBDocumentContainer::pageFromSceneIndex(pageIndex));
widgets << widgetItem; widgets << widgetItem;
} }
} }
QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.json",pageIndex); QString filename = mPublishingPath + UBFileSystemUtils::digitFileFormat("/page%1.json",pageIndex);
QFile jsonFile(filename); QFile jsonFile(filename);
if (jsonFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) if (jsonFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
{ {
jsonFile.write("{\n"); jsonFile.write("{\n");
jsonFile.write(QString(" \"scene\": {\n").toUtf8()); jsonFile.write(QString(" \"scene\": {\n").toUtf8());
jsonFile.write(QString(" \"x\": %1,\n").arg(scene->normalizedSceneRect().x()).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(" \"y\": %1,\n").arg(scene->normalizedSceneRect().y()).toUtf8());
jsonFile.write(QString(" \"width\": %1,\n").arg(scene->normalizedSceneRect().width()).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(" \"height\": %1\n").arg(scene->normalizedSceneRect().height()).toUtf8());
jsonFile.write(QString(" },\n").toUtf8()); jsonFile.write(QString(" },\n").toUtf8());
jsonFile.write(QString(" \"widgets\": [\n").toUtf8()); jsonFile.write(QString(" \"widgets\": [\n").toUtf8());
bool first = true; bool first = true;
foreach(UBGraphicsW3CWidgetItem* widget, widgets) foreach(UBGraphicsW3CWidgetItem* widget, widgets)
{ {
if (!first) if (!first)
jsonFile.write(QString(" ,\n").toUtf8()); jsonFile.write(QString(" ,\n").toUtf8());
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(" \"uuid\": \"%1\",\n").arg(UBStringUtils::toCanonicalUuid(widget->uuid())).toUtf8());
jsonFile.write(QString(" \"id\": \"%1\",\n").arg(widget->metadatas().id).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(" \"name\": \"%1\",\n").arg(widget->metadatas().name).toUtf8());
jsonFile.write(QString(" \"description\": \"%1\",\n").arg(widget->metadatas().description).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(" \"author\": \"%1\",\n").arg(widget->metadatas().author).toUtf8());
jsonFile.write(QString(" \"authorEmail\": \"%1\",\n").arg(widget->metadatas().authorEmail).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(" \"authorHref\": \"%1\",\n").arg(widget->metadatas().authorHref).toUtf8());
jsonFile.write(QString(" \"version\": \"%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(" \"x\": %1,\n").arg(widget->sceneBoundingRect().x()).toUtf8());
jsonFile.write(QString(" \"y\": %1,\n").arg(widget->sceneBoundingRect().y()).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(" \"width\": %1,\n").arg(widget->sceneBoundingRect().width()).toUtf8());
jsonFile.write(QString(" \"height\": %1,\n").arg(widget->sceneBoundingRect().height()).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(" \"nominalWidth\": %1,\n").arg(widget->boundingRect().width()).toUtf8());
jsonFile.write(QString(" \"nominalHeight\": %1,\n").arg(widget->boundingRect().height()).toUtf8()); jsonFile.write(QString(" \"nominalHeight\": %1,\n").arg(widget->boundingRect().height()).toUtf8());
QString url = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString() + ".wgt"; QString url = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString() + ".wgt";
jsonFile.write(QString(" \"src\": \"%1\",\n").arg(url).toUtf8()); jsonFile.write(QString(" \"src\": \"%1\",\n").arg(url).toUtf8());
QString startFile = widget->mainHtmlFileName(); QString startFile = widget->mainHtmlFileName();
jsonFile.write(QString(" \"startFile\": \"%1\",\n").arg(startFile).toUtf8()); jsonFile.write(QString(" \"startFile\": \"%1\",\n").arg(startFile).toUtf8());
QMap<QString, QString> preferences = widget->UBGraphicsWidgetItem::preferences(); QMap<QString, QString> preferences = widget->UBGraphicsWidgetItem::preferences();
jsonFile.write(QString(" \"preferences\": {\n").toUtf8()); jsonFile.write(QString(" \"preferences\": {\n").toUtf8());
foreach(QString key, preferences.keys()) foreach(QString key, preferences.keys())
{ {
QString sep = ","; QString sep = ",";
if (key == preferences.keys().last()) if (key == preferences.keys().last())
sep = ""; sep = "";
jsonFile.write(QString(" \"%1\": \"%2\"%3\n") jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
.arg(key) .arg(key)
.arg(preferences.value(key)) .arg(preferences.value(key))
.arg(sep) .arg(sep)
.toUtf8()); .toUtf8());
} }
jsonFile.write(QString(" },\n").toUtf8()); jsonFile.write(QString(" },\n").toUtf8());
jsonFile.write(QString(" \"datastore\": {\n").toUtf8()); jsonFile.write(QString(" \"datastore\": {\n").toUtf8());
QMap<QString, QString> datastoreEntries = widget->datastoreEntries(); QMap<QString, QString> datastoreEntries = widget->datastoreEntries();
foreach(QString entry, datastoreEntries.keys()) foreach(QString entry, datastoreEntries.keys())
{ {
QString sep = ","; QString sep = ",";
if (entry == datastoreEntries.keys().last()) if (entry == datastoreEntries.keys().last())
sep = ""; sep = "";
jsonFile.write(QString(" \"%1\": \"%2\"%3\n") jsonFile.write(QString(" \"%1\": \"%2\"%3\n")
.arg(entry) .arg(entry)
.arg(datastoreEntries.value(entry)) .arg(datastoreEntries.value(entry))
.arg(sep) .arg(sep)
.toUtf8()); .toUtf8());
} }
jsonFile.write(QString(" }\n").toUtf8()); jsonFile.write(QString(" }\n").toUtf8());
jsonFile.write(QString(" }\n").toUtf8()); jsonFile.write(QString(" }\n").toUtf8());
first = false; first = false;
} }
jsonFile.write(" ]\n"); jsonFile.write(" ]\n");
jsonFile.write("}\n"); jsonFile.write("}\n");
} }
else else
{ {
qWarning() << "Cannot open file" << filename << "for saving page state"; qWarning() << "Cannot open file" << filename << "for saving page state";
} }
delete scene; delete scene;
} }
updateGoogleMapApiKey(); updateGoogleMapApiKey();
} }
void UBDocumentPublisher::generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber) void UBDocumentPublisher::generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber)
{ {
QMap<QString, QString> preferences = widgetItem->UBGraphicsWidgetItem::preferences(); QMap<QString, QString> preferences = widgetItem->UBGraphicsWidgetItem::preferences();
QMap<QString, QString> datastoreEntries = widgetItem->datastoreEntries(); QMap<QString, QString> datastoreEntries = widgetItem->datastoreEntries();
QString startFileName = widgetItem->mainHtmlFileName(); QString startFileName = widgetItem->mainHtmlFileName();
if (!startFileName.startsWith("http://")) if (!startFileName.startsWith("http://"))
{ {
QString startFilePath = mPublishingPath + "/" + UBPersistenceManager::widgetDirectory + "/" + widgetItem->uuid().toString() + ".wgt/" + startFileName; QString startFilePath = mPublishingPath + "/" + UBPersistenceManager::widgetDirectory + "/" + widgetItem->uuid().toString() + ".wgt/" + startFileName;
QFile startFile(startFilePath); QFile startFile(startFilePath);
if (startFile.exists()) if (startFile.exists())
{ {
if (startFile.open(QIODevice::ReadWrite)) if (startFile.open(QIODevice::ReadWrite))
{ {
QTextStream stream(&startFile); QTextStream stream(&startFile);
QStringList lines; QStringList lines;
bool addedJs = false; bool addedJs = false;
QString line; QString line;
do do
{ {
line = stream.readLine(); line = stream.readLine();
if (!line.isNull()) if (!line.isNull())
{ {
lines << line; lines << line;
if (!addedJs && line.contains("<head") && line.contains(">") ) // TODO UB 4.6, this is naive ... the HEAD tag may be on several lines if (!addedJs && line.contains("<head") && line.contains(">") ) // TODO UB 4.6, this is naive ... the HEAD tag may be on several lines
{ {
lines << ""; lines << "";
lines << " <script type=\"text/javascript\">"; lines << " <script type=\"text/javascript\">";
lines << " var widget = {};"; lines << " var widget = {};";
lines << " widget.id = '" + widgetItem->metadatas().id + "';"; lines << " widget.id = '" + widgetItem->metadatas().id + "';";
lines << " widget.name = '" + widgetItem->metadatas().name + "';"; lines << " widget.name = '" + widgetItem->metadatas().name + "';";
lines << " widget.description = '" + widgetItem->metadatas().description + "';"; lines << " widget.description = '" + widgetItem->metadatas().description + "';";
lines << " widget.author = '" + widgetItem->metadatas().author + "';"; lines << " widget.author = '" + widgetItem->metadatas().author + "';";
lines << " widget.authorEmail = '" + widgetItem->metadatas().authorEmail + "';"; lines << " widget.authorEmail = '" + widgetItem->metadatas().authorEmail + "';";
lines << " widget.authorHref = '" + widgetItem->metadatas().authorHref + "';"; lines << " widget.authorHref = '" + widgetItem->metadatas().authorHref + "';";
lines << " widget.version = '" + widgetItem->metadatas().version + "';"; lines << " widget.version = '" + widgetItem->metadatas().version + "';";
lines << " widget.uuid = '" + UBStringUtils::toCanonicalUuid(widgetItem->uuid()) + "';"; lines << " widget.uuid = '" + UBStringUtils::toCanonicalUuid(widgetItem->uuid()) + "';";
lines << " widget.width = " + QString("%1").arg(widgetItem->nominalSize().width()) + ";"; lines << " widget.width = " + QString("%1").arg(widgetItem->nominalSize().width()) + ";";
lines << " widget.height = " + QString("%1").arg(widgetItem->nominalSize().height()) + ";"; lines << " widget.height = " + QString("%1").arg(widgetItem->nominalSize().height()) + ";";
lines << " widget.openUrl = function(url) { window.open(url); }"; lines << " widget.openUrl = function(url) { window.open(url); }";
lines << " widget.preferences = new Array()"; lines << " widget.preferences = new Array()";
foreach(QString pref, preferences.keys()) foreach(QString pref, preferences.keys())
{ {
lines << " widget.preferences['" + pref + "'] = '" + preferences.value(pref) + "';"; lines << " widget.preferences['" + pref + "'] = '" + preferences.value(pref) + "';";
} }
lines << " widget.preferences.key = function(index) {"; lines << " widget.preferences.key = function(index) {";
lines << " var currentIndex = 0;"; lines << " var currentIndex = 0;";
lines << " for(key in widget.preferences){"; lines << " for(key in widget.preferences){";
lines << " if (currentIndex == index){ return key;}"; lines << " if (currentIndex == index){ return key;}";
lines << " currentIndex++;"; lines << " currentIndex++;";
lines << " }"; lines << " }";
lines << " return '';"; lines << " return '';";
lines << " }"; lines << " }";
lines << " widget.preferences.getItem = function(key) {"; lines << " widget.preferences.getItem = function(key) {";
lines << " return widget.preferences[key];"; lines << " return widget.preferences[key];";
lines << " }"; lines << " }";
lines << " widget.preferences.setItem = function(key, value) {}"; lines << " widget.preferences.setItem = function(key, value) {}";
lines << " widget.preferences.removeItem = function(key) {}"; lines << " widget.preferences.removeItem = function(key) {}";
lines << " widget.preferences.clear = function() {}"; lines << " widget.preferences.clear = function() {}";
lines << " var uniboard = {};"; lines << " var uniboard = {};";
lines << " uniboard.pageCount = " + QString("%1").arg(mPublishingSize) + ";"; lines << " uniboard.pageCount = " + QString("%1").arg(mPublishingSize) + ";";
lines << " uniboard.currentPageNumber = " + QString("%1").arg(pageNumber) + ";"; lines << " uniboard.currentPageNumber = " + QString("%1").arg(pageNumber) + ";";
lines << " uniboard.uuid = '" + UBStringUtils::toCanonicalUuid(widgetItem->uuid()) + "'"; lines << " uniboard.uuid = '" + UBStringUtils::toCanonicalUuid(widgetItem->uuid()) + "'";
lines << " uniboard.lang = navigator.language;"; lines << " uniboard.lang = navigator.language;";
lines << " uniboard.locale = function() {return navigator.language}"; lines << " uniboard.locale = function() {return navigator.language}";
lines << " uniboard.messages = {}"; lines << " uniboard.messages = {}";
lines << " uniboard.messages.subscribeToTopic = function(topicName){}"; lines << " uniboard.messages.subscribeToTopic = function(topicName){}";
lines << " uniboard.messages.unsubscribeFromTopic = function(topicName){}"; lines << " uniboard.messages.unsubscribeFromTopic = function(topicName){}";
lines << " uniboard.messages.sendMessage = function(topicName, message){}"; lines << " uniboard.messages.sendMessage = function(topicName, message){}";
lines << " uniboard.datastore = {};"; lines << " uniboard.datastore = {};";
lines << " uniboard.datastore.document = new Array();"; lines << " uniboard.datastore.document = new Array();";
foreach(QString entry, datastoreEntries.keys()) foreach(QString entry, datastoreEntries.keys())
{ {
lines << " uniboard.datastore.document['" + entry + "'] = '" + datastoreEntries.value(entry) + "';"; lines << " uniboard.datastore.document['" + entry + "'] = '" + datastoreEntries.value(entry) + "';";
} }
lines << " uniboard.datastore.document.key = function(index) {"; lines << " uniboard.datastore.document.key = function(index) {";
lines << " var currentIndex = 0;"; lines << " var currentIndex = 0;";
lines << " for(key in uniboard.datastore.document){"; lines << " for(key in uniboard.datastore.document){";
lines << " if (currentIndex == index){ return key;}"; lines << " if (currentIndex == index){ return key;}";
lines << " currentIndex++;"; lines << " currentIndex++;";
lines << " }"; lines << " }";
lines << " return '';"; lines << " return '';";
lines << " }"; lines << " }";
lines << " uniboard.datastore.document.getItem = function(key) {"; lines << " uniboard.datastore.document.getItem = function(key) {";
lines << " return uniboard.datastore.document[key];"; lines << " return uniboard.datastore.document[key];";
lines << " }"; lines << " }";
lines << " uniboard.datastore.document.setItem = function(key, value) {}"; lines << " uniboard.datastore.document.setItem = function(key, value) {}";
lines << " uniboard.datastore.document.removeItem = function(key) {}"; lines << " uniboard.datastore.document.removeItem = function(key) {}";
lines << " uniboard.datastore.document.clear = function() {}"; lines << " uniboard.datastore.document.clear = function() {}";
lines << " uniboard.setTool = function(tool){}"; lines << " uniboard.setTool = function(tool){}";
lines << " uniboard.setPenColor = function(color){}"; lines << " uniboard.setPenColor = function(color){}";
lines << " uniboard.setMarkerColor = function(color){}"; lines << " uniboard.setMarkerColor = function(color){}";
lines << " uniboard.pageThumbnail = function(pageNumber){"; lines << " uniboard.pageThumbnail = function(pageNumber){";
lines << " var nb;"; lines << " var nb;";
lines << " if (pageNumber < 10) return 'page00' + pageNumber + '.thumbnail.jpg';"; lines << " if (pageNumber < 10) return 'page00' + pageNumber + '.thumbnail.jpg';";
lines << " if (pageNumber < 100) return 'page0' + pageNumber + '.thumbnail.jpg';"; lines << " if (pageNumber < 100) return 'page0' + pageNumber + '.thumbnail.jpg';";
lines << " return 'page' + pageNumber + '.thumbnail.jpg;'"; lines << " return 'page' + pageNumber + '.thumbnail.jpg;'";
lines << " }"; lines << " }";
lines << " uniboard.zoom = function(factor, x, y){}"; lines << " uniboard.zoom = function(factor, x, y){}";
lines << " uniboard.move = function(x, y){}"; lines << " uniboard.move = function(x, y){}";
lines << " uniboard.move = function(x, y){}"; lines << " uniboard.move = function(x, y){}";
lines << " uniboard.moveTo = function(x, y){}"; lines << " uniboard.moveTo = function(x, y){}";
lines << " uniboard.drawLineTo = function(x, y, width){}"; lines << " uniboard.drawLineTo = function(x, y, width){}";
lines << " uniboard.eraseLineTo = function(x, y, width){}"; lines << " uniboard.eraseLineTo = function(x, y, width){}";
lines << " uniboard.clear = function(){}"; lines << " uniboard.clear = function(){}";
lines << " uniboard.setBackground = function(dark, crossed){}"; lines << " uniboard.setBackground = function(dark, crossed){}";
lines << " uniboard.addObject = function(url, width, height, x, y, background){}"; lines << " uniboard.addObject = function(url, width, height, x, y, background){}";
lines << " uniboard.resize = function(width, height){window.resizeTo(width, height);}"; lines << " uniboard.resize = function(width, height){window.resizeTo(width, height);}";
lines << " uniboard.showMessage = function(message){alert(message);}"; lines << " uniboard.showMessage = function(message){alert(message);}";
lines << " uniboard.centerOn = function(x, y){}"; lines << " uniboard.centerOn = function(x, y){}";
lines << " uniboard.addText = function(text, x, y){}"; lines << " uniboard.addText = function(text, x, y){}";
lines << " uniboard.setPreference = function(key, value){}"; lines << " uniboard.setPreference = function(key, value){}";
lines << " uniboard.preference = function(key, defValue){"; lines << " uniboard.preference = function(key, defValue){";
lines << " var pref = widget.preferences[key];"; lines << " var pref = widget.preferences[key];";
lines << " if (pref == undefined) "; lines << " if (pref == undefined) ";
lines << " return defValue;"; lines << " return defValue;";
lines << " else "; lines << " else ";
lines << " return pref;"; lines << " return pref;";
lines << " }"; lines << " }";
lines << " uniboard.preferenceKeys = function(){"; lines << " uniboard.preferenceKeys = function(){";
lines << " var keys = new Array();"; lines << " var keys = new Array();";
lines << " for(key in widget.preferences){"; lines << " for(key in widget.preferences){";
lines << " keys.push(key);"; lines << " keys.push(key);";
lines << " }"; lines << " }";
lines << " return keys;"; lines << " return keys;";
lines << " }"; lines << " }";
lines << " uniboard.datastore.document.key = function(index) {"; lines << " uniboard.datastore.document.key = function(index) {";
lines << " var currentIndex = 0;"; lines << " var currentIndex = 0;";
lines << " for(key in uniboard.datastore.document){"; lines << " for(key in uniboard.datastore.document){";
lines << " if (currentIndex == index){ return key;}"; lines << " if (currentIndex == index){ return key;}";
lines << " currentIndex++;"; lines << " currentIndex++;";
lines << " }"; lines << " }";
lines << " return '';"; lines << " return '';";
lines << " }"; lines << " }";
lines << " uniboard.datastore.document.getItem = function(key) {"; lines << " uniboard.datastore.document.getItem = function(key) {";
lines << " return uniboard.datastore.document[key];"; lines << " return uniboard.datastore.document[key];";
lines << " }"; lines << " }";
lines << " uniboard.datastore.document.setItem = function(key, value) {}"; lines << " uniboard.datastore.document.setItem = function(key, value) {}";
lines << " uniboard.datastore.document.removeItem = function(key) {}"; lines << " uniboard.datastore.document.removeItem = function(key) {}";
lines << " uniboard.datastore.document.clear = function() {}"; lines << " uniboard.datastore.document.clear = function() {}";
lines << " </script>"; lines << " </script>";
lines << ""; lines << "";
addedJs = true; addedJs = true;
} }
} }
} }
while (!line.isNull()); while (!line.isNull());
startFile.resize(0); startFile.resize(0);
startFile.write(lines.join("\n").toUtf8()); // TODO UB 4.x detect real html encoding startFile.write(lines.join("\n").toUtf8()); // TODO UB 4.x detect real html encoding
startFile.close(); startFile.close();
} }
} }
} }
else{ else{
qWarning() << "Remote Widget start file, cannot inject widget preferences and datastore entries"; qWarning() << "Remote Widget start file, cannot inject widget preferences and datastore entries";
} }
} }
void UBDocumentPublisher::init() void UBDocumentPublisher::init()
{ {
mCrlf=0x0d; mCrlf=0x0d;
mCrlf+=0x0a; mCrlf+=0x0a;
mDocInfos.title = ""; mDocInfos.title = "";
mDocInfos.description = ""; mDocInfos.description = "";
mpCookieJar = new QNetworkCookieJar(); mpCookieJar = new QNetworkCookieJar();
mpNetworkMgr = new QNetworkAccessManager(this); mpNetworkMgr = new QNetworkAccessManager(this);
connect(mpNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*))); connect(mpNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
} }
void UBDocumentPublisher::onFinished(QNetworkReply *reply) void UBDocumentPublisher::onFinished(QNetworkReply *reply)
{ {
QVariant cookieHeader = reply->rawHeader("Set-Cookie"); QVariant cookieHeader = reply->rawHeader("Set-Cookie");
// First we concatenate all the Set-Cookie values (the packet can contains many of them) // First we concatenate all the Set-Cookie values (the packet can contains many of them)
QStringList qslCookie = cookieHeader.toString().split("\n"); QStringList qslCookie = cookieHeader.toString().split("\n");
QString qsCookieValue = qslCookie.at(0); QString qsCookieValue = qslCookie.at(0);
for (int i = 1; i < qslCookie.size(); i++) { for (int i = 1; i < qslCookie.size(); i++) {
qsCookieValue += "; " +qslCookie.at(i); qsCookieValue += "; " +qslCookie.at(i);
} }
// Now we isolate every cookie value // Now we isolate every cookie value
QStringList qslCookieVals = qsCookieValue.split("; "); QStringList qslCookieVals = qsCookieValue.split("; ");
bool bTransferOk = false; bool bTransferOk = false;
for(int j = 0; j < qslCookieVals.size(); j++) for(int j = 0; j < qslCookieVals.size(); j++)
{ {
qDebug() << j; qDebug() << j;
if(qslCookieVals.at(j).startsWith("assetStatus")) if(qslCookieVals.at(j).startsWith("assetStatus"))
{ {
QStringList qslAsset = qslCookieVals.at(j).split("="); QStringList qslAsset = qslCookieVals.at(j).split("=");
if(qslAsset.at(1) == "UPLOADED") if(qslAsset.at(1) == "UPLOADED")
{ {
bTransferOk = true; bTransferOk = true;
break; break;
} }
} }
} }
if(bTransferOk) if(bTransferOk)
{ {
UBApplication::showMessage(tr("Document uploaded correctly on the web.")); UBApplication::showMessage(tr("Document uploaded correctly on the web."));
} }
else else
{ {
UBApplication::showMessage(tr("Failed to upload document on the web.")); UBApplication::showMessage(tr("Failed to upload document on the web."));
} }
reply->deleteLater(); reply->deleteLater();
} }
void UBDocumentPublisher::sendUbw(QString username, QString password) void UBDocumentPublisher::sendUbw(QString username, QString password)
{ {
if (QFile::exists(mTmpZipFile)) if (QFile::exists(mTmpZipFile))
{ {
QFile f(mTmpZipFile); QFile f(mTmpZipFile);
if (f.open(QIODevice::ReadOnly)) if (f.open(QIODevice::ReadOnly))
{ {
QFileInfo fi(f); QFileInfo fi(f);
QByteArray ba = f.readAll(); QByteArray ba = f.readAll();
QString boundary,data, multipartHeader; QString boundary,data, multipartHeader;
QByteArray datatoSend; QByteArray datatoSend;
boundary = "---WebKitFormBoundaryDKBTgA53MiyWrzLY"; boundary = "---WebKitFormBoundaryDKBTgA53MiyWrzLY";
multipartHeader = "multipart/form-data; boundary="+boundary; multipartHeader = "multipart/form-data; boundary="+boundary;
data="--"+boundary+mCrlf; data="--"+boundary+mCrlf;
data+="Content-Disposition: form-data; name=\"title\"" + mCrlf + mCrlf + mDocInfos.title + mCrlf; data+="Content-Disposition: form-data; name=\"title\"" + mCrlf + mCrlf + mDocInfos.title + mCrlf;
data+="--"+boundary+mCrlf; data+="--"+boundary+mCrlf;
data+="Content-Disposition: form-data; name=\"description\"" + mCrlf + mCrlf + mDocInfos.description.remove("\n") + mCrlf; data+="Content-Disposition: form-data; name=\"description\"" + mCrlf + mCrlf + mDocInfos.description.remove("\n") + mCrlf;
data+="--"+boundary+mCrlf; data+="--"+boundary+mCrlf;
data+="Content-Disposition: form-data; name=\"file\"; filename=\""+ fi.fileName() +"\""+mCrlf; data+="Content-Disposition: form-data; name=\"file\"; filename=\""+ fi.fileName() +"\""+mCrlf;
data+="Content-Type: application/octet-stream"+mCrlf+mCrlf; data+="Content-Type: application/octet-stream"+mCrlf+mCrlf;
datatoSend=data.toAscii(); // convert data string to byte array for request datatoSend=data.toAscii(); // convert data string to byte array for request
datatoSend += ba; datatoSend += ba;
datatoSend += mCrlf; datatoSend += mCrlf;
datatoSend += QString("--%0--%1").arg(boundary).arg(mCrlf); datatoSend += QString("--%0--%1").arg(boundary).arg(mCrlf);
QNetworkRequest request(QUrl(QString(DOCPUBLICATION_URL).toAscii().constData())); QNetworkRequest request(QUrl(QString(DOCPUBLICATION_URL).toAscii().constData()));
request.setHeader(QNetworkRequest::ContentTypeHeader, multipartHeader); request.setHeader(QNetworkRequest::ContentTypeHeader, multipartHeader);
request.setHeader(QNetworkRequest::ContentLengthHeader,datatoSend.size()); request.setHeader(QNetworkRequest::ContentLengthHeader,datatoSend.size());
QString b64Auth = getBase64Of(QString("%0:%1").arg(username).arg(password)); QString b64Auth = getBase64Of(QString("%0:%1").arg(username).arg(password));
request.setRawHeader("Authorization", QString("Basic %0").arg(b64Auth).toAscii().constData()); request.setRawHeader("Authorization", QString("Basic %0").arg(b64Auth).toAscii().constData());
request.setRawHeader("Host", "planete.sankore.org"); request.setRawHeader("Host", "planete.sankore.org");
request.setRawHeader("Accept", "*/*"); request.setRawHeader("Accept", "*/*");
request.setRawHeader("Accept-Language", "en-US,*"); request.setRawHeader("Accept-Language", "en-US,*");
mpCookieJar->setCookiesFromUrl(mCookies, QUrl(DOCPUBLICATION_URL)); mpCookieJar->setCookiesFromUrl(mCookies, QUrl(DOCPUBLICATION_URL));
mpNetworkMgr->setCookieJar(mpCookieJar); mpNetworkMgr->setCookieJar(mpCookieJar);
// Send the file // Send the file
mpNetworkMgr->post(request,datatoSend); mpNetworkMgr->post(request,datatoSend);
} }
} }
} }
QString UBDocumentPublisher::getBase64Of(QString stringToEncode) QString UBDocumentPublisher::getBase64Of(QString stringToEncode)
{ {
return stringToEncode.toAscii().toBase64(); return stringToEncode.toAscii().toBase64();
} }
// --------------------------------------------------------- // ---------------------------------------------------------
UBProxyLoginDlg::UBProxyLoginDlg(QWidget *parent, const char *name):QDialog(parent) UBProxyLoginDlg::UBProxyLoginDlg(QWidget *parent, const char *name):QDialog(parent)
, mpLayout(NULL) , mpLayout(NULL)
, mpUserLayout(NULL) , mpUserLayout(NULL)
, mpPasswordLayout(NULL) , mpPasswordLayout(NULL)
, mpButtons(NULL) , mpButtons(NULL)
, mpUserLabel(NULL) , mpUserLabel(NULL)
, mpPasswordLabel(NULL) , mpPasswordLabel(NULL)
, mpUsername(NULL) , mpUsername(NULL)
, mpPassword(NULL) , mpPassword(NULL)
{ {
setObjectName(name); setObjectName(name);
setFixedSize(400, 150); setFixedSize(400, 150);
setWindowTitle(tr("Proxy Login")); setWindowTitle(tr("Proxy Login"));
mpLayout = new QVBoxLayout(); mpLayout = new QVBoxLayout();
setLayout(mpLayout); setLayout(mpLayout);
mpUserLayout = new QHBoxLayout(); mpUserLayout = new QHBoxLayout();
mpLayout->addLayout(mpUserLayout); mpLayout->addLayout(mpUserLayout);
mpPasswordLayout = new QHBoxLayout(); mpPasswordLayout = new QHBoxLayout();
mpLayout->addLayout(mpPasswordLayout); mpLayout->addLayout(mpPasswordLayout);
mpUserLabel = new QLabel(tr("Username:"), this); mpUserLabel = new QLabel(tr("Username:"), this);
mpUsername = new QLineEdit(this); mpUsername = new QLineEdit(this);
mpUserLayout->addWidget(mpUserLabel, 0); mpUserLayout->addWidget(mpUserLabel, 0);
mpUserLayout->addWidget(mpUsername, 1); mpUserLayout->addWidget(mpUsername, 1);
mpPasswordLabel = new QLabel(tr("Password:"), this); mpPasswordLabel = new QLabel(tr("Password:"), this);
mpPassword = new QLineEdit(this); mpPassword = new QLineEdit(this);
mpPasswordLayout->addWidget(mpPasswordLabel, 0); mpPasswordLayout->addWidget(mpPasswordLabel, 0);
mpPasswordLayout->addWidget(mpPassword, 1); mpPasswordLayout->addWidget(mpPassword, 1);
mpButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); mpButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
mpLayout->addWidget(mpButtons); mpLayout->addWidget(mpButtons);
connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept())); connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject())); connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
} }
UBProxyLoginDlg::~UBProxyLoginDlg() UBProxyLoginDlg::~UBProxyLoginDlg()
{ {
if(NULL != mpLayout) if(NULL != mpLayout)
{ {
delete mpLayout; delete mpLayout;
mpLayout = NULL; mpLayout = NULL;
} }
if(NULL != mpButtons) if(NULL != mpButtons)
{ {
delete mpButtons; delete mpButtons;
mpButtons = NULL; mpButtons = NULL;
} }
if(NULL != mpUserLabel) if(NULL != mpUserLabel)
{ {
delete mpUserLabel; delete mpUserLabel;
mpUserLabel = NULL; mpUserLabel = NULL;
} }
if(NULL != mpPasswordLabel) if(NULL != mpPasswordLabel)
{ {
delete mpPasswordLabel; delete mpPasswordLabel;
mpPasswordLabel = NULL; mpPasswordLabel = NULL;
} }
if(NULL != mpUsername) if(NULL != mpUsername)
{ {
delete mpUsername; delete mpUsername;
mpUsername = NULL; mpUsername = NULL;
} }
if(NULL != mpPassword) if(NULL != mpPassword)
{ {
delete mpPassword; delete mpPassword;
mpPassword = NULL; mpPassword = NULL;
} }
} }
// --------------------------------------------------------- // ---------------------------------------------------------
UBPublicationDlg::UBPublicationDlg(QWidget *parent, const char *name):QDialog(parent) UBPublicationDlg::UBPublicationDlg(QWidget *parent, const char *name):QDialog(parent)
, mpLayout(NULL) , mpLayout(NULL)
, mpTitleLayout(NULL) , mpTitleLayout(NULL)
, mpTitleLabel(NULL) , mpTitleLabel(NULL)
, mpTitle(NULL) , mpTitle(NULL)
, mpDescLabel(NULL) , mpDescLabel(NULL)
, mpDescription(NULL) , mpDescription(NULL)
, mpButtons(NULL) , mpButtons(NULL)
{ {
setObjectName(name); setObjectName(name);
setWindowTitle(tr("Publish document on the web")); setWindowTitle(tr("Publish document on the web"));
resize(500, 300); resize(500, 300);
mpLayout = new QVBoxLayout(); mpLayout = new QVBoxLayout();
setLayout(mpLayout); setLayout(mpLayout);
mpTitleLabel = new QLabel(tr("Title:"), this); mpTitleLabel = new QLabel(tr("Title:"), this);
mpTitle = new QLineEdit(this); mpTitle = new QLineEdit(this);
mpTitleLayout = new QHBoxLayout(); mpTitleLayout = new QHBoxLayout();
mpTitleLayout->addWidget(mpTitleLabel, 0); mpTitleLayout->addWidget(mpTitleLabel, 0);
mpTitleLayout->addWidget(mpTitle, 1); mpTitleLayout->addWidget(mpTitle, 1);
mpLayout->addLayout(mpTitleLayout, 0); mpLayout->addLayout(mpTitleLayout, 0);
mpDescLabel = new QLabel(tr("Description:"), this); mpDescLabel = new QLabel(tr("Description:"), this);
mpLayout->addWidget(mpDescLabel, 0); mpLayout->addWidget(mpDescLabel, 0);
mpDescription = new QTextEdit(this); mpDescription = new QTextEdit(this);
mpLayout->addWidget(mpDescription, 1); mpLayout->addWidget(mpDescription, 1);
mpButtons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); mpButtons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this);
mpButtons->button(QDialogButtonBox::Ok)->setText(tr("Publish")); mpButtons->button(QDialogButtonBox::Ok)->setText(tr("Publish"));
mpLayout->addWidget(mpButtons); mpLayout->addWidget(mpButtons);
mpButtons->button(QDialogButtonBox::Ok)->setEnabled(false); mpButtons->button(QDialogButtonBox::Ok)->setEnabled(false);
connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept())); connect(mpButtons, SIGNAL(accepted()), this, SLOT(accept()));
connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject())); connect(mpButtons, SIGNAL(rejected()), this, SLOT(reject()));
connect(mpTitle, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged())); connect(mpTitle, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged()));
connect(mpDescription, SIGNAL(textChanged()), this, SLOT(onTextChanged())); connect(mpDescription, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
} }
UBPublicationDlg::~UBPublicationDlg() UBPublicationDlg::~UBPublicationDlg()
{ {
if(NULL != mpTitleLabel) if(NULL != mpTitleLabel)
{ {
delete mpTitleLabel; delete mpTitleLabel;
mpTitleLabel = NULL; mpTitleLabel = NULL;
} }
if(NULL != mpTitle) if(NULL != mpTitle)
{ {
delete mpTitle; delete mpTitle;
mpTitle = NULL; mpTitle = NULL;
} }
if(NULL != mpDescLabel) if(NULL != mpDescLabel)
{ {
delete mpDescLabel; delete mpDescLabel;
mpDescLabel = NULL; mpDescLabel = NULL;
} }
if(NULL != mpDescription) if(NULL != mpDescription)
{ {
delete mpDescription; delete mpDescription;
mpDescription = NULL; mpDescription = NULL;
} }
if(NULL != mpButtons) if(NULL != mpButtons)
{ {
delete mpButtons; delete mpButtons;
mpButtons = NULL; mpButtons = NULL;
} }
if(NULL != mpTitleLayout) if(NULL != mpTitleLayout)
{ {
delete mpTitleLayout; delete mpTitleLayout;
mpTitleLayout = NULL; mpTitleLayout = NULL;
} }
if(NULL != mpLayout) if(NULL != mpLayout)
{ {
delete mpLayout; delete mpLayout;
mpLayout = NULL; mpLayout = NULL;
} }
} }
void UBPublicationDlg::onTextChanged() void UBPublicationDlg::onTextChanged()
{ {
bool bPublishButtonState = false; bool bPublishButtonState = false;
if(mpTitle->text() != "" && mpDescription->document()->toPlainText() != "") if(mpTitle->text() != "" && mpDescription->document()->toPlainText() != "")
{ {
bPublishButtonState = true; bPublishButtonState = true;
} }
else else
{ {
bPublishButtonState = false; bPublishButtonState = false;
} }
mpButtons->button(QDialogButtonBox::Ok)->setEnabled(bPublishButtonState); mpButtons->button(QDialogButtonBox::Ok)->setEnabled(bPublishButtonState);
} }
...@@ -19,124 +19,124 @@ ...@@ -19,124 +19,124 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBDOCUMENTPUBLISHER_H #ifndef UBDOCUMENTPUBLISHER_H
#define UBDOCUMENTPUBLISHER_H #define UBDOCUMENTPUBLISHER_H
#include <QtGui> #include <QtGui>
#include <QtNetwork> #include <QtNetwork>
#include "ui_webPublishing.h" #include "ui_webPublishing.h"
#define DOCPUBLICATION_URL "http://planete.sankore.org/xwiki/bin/view/CreateResources/UniboardUpload?xpage=plain&outputSyntax=plain" #define DOCPUBLICATION_URL "http://planete.sankore.org/xwiki/bin/view/CreateResources/UniboardUpload?xpage=plain&outputSyntax=plain"
typedef struct typedef struct
{ {
QString title; QString title;
QString description; QString description;
} sDocumentInfos; } sDocumentInfos;
class UBDocumentProxy; class UBDocumentProxy;
class UBServerXMLHttpRequest; class UBServerXMLHttpRequest;
class UBGraphicsW3CWidgetItem; class UBGraphicsW3CWidgetItem;
class QWebView; class QWebView;
class UBProxyLoginDlg : public QDialog class UBProxyLoginDlg : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
UBProxyLoginDlg(QWidget* parent=0, const char* name="ProxyLoginDlg"); UBProxyLoginDlg(QWidget* parent=0, const char* name="ProxyLoginDlg");
~UBProxyLoginDlg(); ~UBProxyLoginDlg();
QString username(){return mpUsername->text();} QString username(){return mpUsername->text();}
QString password(){return mpPassword->text();} QString password(){return mpPassword->text();}
private: private:
QVBoxLayout* mpLayout; QVBoxLayout* mpLayout;
QHBoxLayout* mpUserLayout; QHBoxLayout* mpUserLayout;
QHBoxLayout* mpPasswordLayout; QHBoxLayout* mpPasswordLayout;
QDialogButtonBox* mpButtons; QDialogButtonBox* mpButtons;
QLabel* mpUserLabel; QLabel* mpUserLabel;
QLabel* mpPasswordLabel; QLabel* mpPasswordLabel;
QLineEdit* mpUsername; QLineEdit* mpUsername;
QLineEdit* mpPassword; QLineEdit* mpPassword;
}; };
class UBPublicationDlg : public QDialog class UBPublicationDlg : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
UBPublicationDlg(QWidget* parent=0, const char* name="UBPublicationDlg"); UBPublicationDlg(QWidget* parent=0, const char* name="UBPublicationDlg");
~UBPublicationDlg(); ~UBPublicationDlg();
QString title(){return mpTitle->text();} QString title(){return mpTitle->text();}
QString description(){return mpDescription->document()->toPlainText();} QString description(){return mpDescription->document()->toPlainText();}
private slots: private slots:
void onTextChanged(); void onTextChanged();
private: private:
QVBoxLayout* mpLayout; QVBoxLayout* mpLayout;
QHBoxLayout* mpTitleLayout; QHBoxLayout* mpTitleLayout;
QLabel* mpTitleLabel; QLabel* mpTitleLabel;
QLineEdit* mpTitle; QLineEdit* mpTitle;
QLabel* mpDescLabel; QLabel* mpDescLabel;
QTextEdit* mpDescription; QTextEdit* mpDescription;
QDialogButtonBox* mpButtons; QDialogButtonBox* mpButtons;
}; };
class UBDocumentPublisher : public QObject class UBDocumentPublisher : public QObject
{ {
Q_OBJECT; Q_OBJECT;
public: public:
explicit UBDocumentPublisher(UBDocumentProxy* sourceDocument, QObject *parent = 0); explicit UBDocumentPublisher(UBDocumentProxy* sourceDocument, QObject *parent = 0);
virtual ~UBDocumentPublisher(); virtual ~UBDocumentPublisher();
void publish(); void publish();
signals: signals:
void loginDone(); void loginDone();
protected: protected:
virtual void updateGoogleMapApiKey(); virtual void updateGoogleMapApiKey();
virtual void rasterizeScenes(); virtual void rasterizeScenes();
virtual void upgradeDocumentForPublishing(); virtual void upgradeDocumentForPublishing();
virtual void generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber); virtual void generateWidgetPropertyScript(UBGraphicsW3CWidgetItem *widgetItem, int pageNumber);
private slots: private slots:
void onFinished(QNetworkReply* reply); void onFinished(QNetworkReply* reply);
private: private:
UBDocumentProxy *mSourceDocument; UBDocumentProxy *mSourceDocument;
//UBDocumentProxy *mPublishingDocument; //UBDocumentProxy *mPublishingDocument;
QString mPublishingPath; QString mPublishingPath;
int mPublishingSize; int mPublishingSize;
void init(); void init();
void sendUbw(QString username, QString password); void sendUbw(QString username, QString password);
QString getBase64Of(QString stringToEncode); QString getBase64Of(QString stringToEncode);
QHBoxLayout* mpLayout; QHBoxLayout* mpLayout;
QNetworkAccessManager* mpNetworkMgr; QNetworkAccessManager* mpNetworkMgr;
QNetworkCookieJar* mpCookieJar; QNetworkCookieJar* mpCookieJar;
QString mUsername; QString mUsername;
QString mPassword; QString mPassword;
QString mCrlf; QString mCrlf;
bool bLoginCookieSet; bool bLoginCookieSet;
void buildUbwFile(); void buildUbwFile();
QString mTmpZipFile; QString mTmpZipFile;
QList<QNetworkCookie> mCookies; QList<QNetworkCookie> mCookies;
sDocumentInfos mDocInfos; sDocumentInfos mDocInfos;
}; };
#endif // UBDOCUMENTPUBLISHER_H #endif // UBDOCUMENTPUBLISHER_H
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -19,295 +19,295 @@ ...@@ -19,295 +19,295 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBBOARDCONTROLLER_H_ #ifndef UBBOARDCONTROLLER_H_
#define UBBOARDCONTROLLER_H_ #define UBBOARDCONTROLLER_H_
#include <QtGui> #include <QtGui>
#include <QObject> #include <QObject>
#include "document/UBDocumentContainer.h" #include "document/UBDocumentContainer.h"
class UBMainWindow; class UBMainWindow;
class UBApplication; class UBApplication;
class UBBoardView; class UBBoardView;
class UBDocumentController; class UBDocumentController;
class UBMessageWindow; class UBMessageWindow;
class UBGraphicsScene; class UBGraphicsScene;
class UBDocumentProxy; class UBDocumentProxy;
class UBBlackoutWidget; class UBBlackoutWidget;
class UBToolWidget; class UBToolWidget;
class UBVersion; class UBVersion;
class UBSoftwareUpdate; class UBSoftwareUpdate;
class UBSoftwareUpdateDialog; class UBSoftwareUpdateDialog;
class UBGraphicsMediaItem; class UBGraphicsMediaItem;
class UBGraphicsVideoItem; class UBGraphicsVideoItem;
class UBGraphicsAudioItem; class UBGraphicsAudioItem;
class UBGraphicsWidgetItem; class UBGraphicsWidgetItem;
class UBBoardPaletteManager; class UBBoardPaletteManager;
class UBItem; class UBItem;
class UBGraphicsItem; class UBGraphicsItem;
class UBBoardController : public UBDocumentContainer class UBBoardController : public UBDocumentContainer
{ {
Q_OBJECT Q_OBJECT
public: public:
UBBoardController(UBMainWindow *mainWindow); UBBoardController(UBMainWindow *mainWindow);
virtual ~UBBoardController(); virtual ~UBBoardController();
void init(); void init();
void setupLayout(); void setupLayout();
UBGraphicsScene* activeScene() const; UBGraphicsScene* activeScene() const;
int activeSceneIndex() const; int activeSceneIndex() const;
QSize displayViewport(); QSize displayViewport();
QSize controlViewport(); QSize controlViewport();
QRectF controlGeometry(); QRectF controlGeometry();
void closing(); void closing();
int currentPage(); int currentPage();
QWidget* controlContainer() QWidget* controlContainer()
{ {
return mControlContainer; return mControlContainer;
} }
UBBoardView* controlView() UBBoardView* controlView()
{ {
return mControlView; return mControlView;
} }
UBBoardView* displayView() UBBoardView* displayView()
{ {
return mDisplayView; return mDisplayView;
} }
UBGraphicsScene* activeScene() UBGraphicsScene* activeScene()
{ {
return mActiveScene; return mActiveScene;
} }
void setPenColorOnDarkBackground(const QColor& pColor) void setPenColorOnDarkBackground(const QColor& pColor)
{ {
if (mPenColorOnDarkBackground == pColor) if (mPenColorOnDarkBackground == pColor)
return; return;
mPenColorOnDarkBackground = pColor; mPenColorOnDarkBackground = pColor;
emit penColorChanged(); emit penColorChanged();
} }
void setPenColorOnLightBackground(const QColor& pColor) void setPenColorOnLightBackground(const QColor& pColor)
{ {
if (mPenColorOnLightBackground == pColor) if (mPenColorOnLightBackground == pColor)
return; return;
mPenColorOnLightBackground = pColor; mPenColorOnLightBackground = pColor;
emit penColorChanged(); emit penColorChanged();
} }
void setMarkerColorOnDarkBackground(const QColor& pColor) void setMarkerColorOnDarkBackground(const QColor& pColor)
{ {
mMarkerColorOnDarkBackground = pColor; mMarkerColorOnDarkBackground = pColor;
} }
void setMarkerColorOnLightBackground(const QColor& pColor) void setMarkerColorOnLightBackground(const QColor& pColor)
{ {
mMarkerColorOnLightBackground = pColor; mMarkerColorOnLightBackground = pColor;
} }
QColor penColorOnDarkBackground() QColor penColorOnDarkBackground()
{ {
return mPenColorOnDarkBackground; return mPenColorOnDarkBackground;
} }
QColor penColorOnLightBackground() QColor penColorOnLightBackground()
{ {
return mPenColorOnLightBackground; return mPenColorOnLightBackground;
} }
QColor markerColorOnDarkBackground() QColor markerColorOnDarkBackground()
{ {
return mMarkerColorOnDarkBackground; return mMarkerColorOnDarkBackground;
} }
QColor markerColorOnLightBackground() QColor markerColorOnLightBackground()
{ {
return mMarkerColorOnLightBackground; return mMarkerColorOnLightBackground;
} }
qreal systemScaleFactor() qreal systemScaleFactor()
{ {
return mSystemScaleFactor; return mSystemScaleFactor;
} }
qreal currentZoom(); qreal currentZoom();
void persistCurrentScene(); void persistCurrentScene();
void showNewVersionAvailable(bool automatic, const UBVersion &installedVersion, const UBSoftwareUpdate &softwareUpdate); void showNewVersionAvailable(bool automatic, const UBVersion &installedVersion, const UBSoftwareUpdate &softwareUpdate);
void setBoxing(QRect displayRect); void setBoxing(QRect displayRect);
void setToolbarTexts(); void setToolbarTexts();
static QUrl expandWidgetToTempDir(const QByteArray& pZipedData, const QString& pExtension = QString("wgt")); static QUrl expandWidgetToTempDir(const QByteArray& pZipedData, const QString& pExtension = QString("wgt"));
// static QRect freeRectInGlobalPos() const {return ;} // static QRect freeRectInGlobalPos() const {return ;}
void setPageSize(QSize newSize); void setPageSize(QSize newSize);
UBBoardPaletteManager *paletteManager() UBBoardPaletteManager *paletteManager()
{ {
return mPaletteManager; return mPaletteManager;
} }
void notifyCache(bool visible); void notifyCache(bool visible);
void notifyPageChanged(); void notifyPageChanged();
void displayMetaData(QMap<QString, QString> metadatas); void displayMetaData(QMap<QString, QString> metadatas);
void ClearUndoStack(); void ClearUndoStack();
void setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, int pSceneIndex = 0, bool forceReload = false); void setActiveDocumentScene(UBDocumentProxy* pDocumentProxy, int pSceneIndex = 0, bool forceReload = false);
void setActiveDocumentScene(int pSceneIndex); void setActiveDocumentScene(int pSceneIndex);
void moveSceneToIndex(int source, int target); void moveSceneToIndex(int source, int target);
void duplicateScene(int index); void duplicateScene(int index);
UBGraphicsItem *duplicateItem(UBItem *item, bool bAsync = true); UBGraphicsItem *duplicateItem(UBItem *item, bool bAsync = true);
void deleteScene(int index); void deleteScene(int index);
bool cacheIsVisible() {return mCacheWidgetIsEnabled;} bool cacheIsVisible() {return mCacheWidgetIsEnabled;}
QString actionGroupText(){ return mActionGroupText;} QString actionGroupText(){ return mActionGroupText;}
QString actionUngroupText(){ return mActionUngroupText;} QString actionUngroupText(){ return mActionUngroupText;}
public slots: public slots:
void showDocumentsDialog(); void showDocumentsDialog();
void showKeyboard(bool show); void showKeyboard(bool show);
void togglePodcast(bool checked); void togglePodcast(bool checked);
void blackout(); void blackout();
void addScene(); void addScene();
void addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty = false); void addScene(UBDocumentProxy* proxy, int sceneIndex, bool replaceActiveIfEmpty = false);
void addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty = false); void addScene(UBGraphicsScene* scene, bool replaceActiveIfEmpty = false);
void duplicateScene(); void duplicateScene();
void importPage(); void importPage();
void clearScene(); void clearScene();
void clearSceneItems(); void clearSceneItems();
void clearSceneAnnotation(); void clearSceneAnnotation();
void clearSceneBackground(); void clearSceneBackground();
void zoomIn(QPointF scenePoint = QPointF(0,0)); void zoomIn(QPointF scenePoint = QPointF(0,0));
void zoomOut(QPointF scenePoint = QPointF(0,0)); void zoomOut(QPointF scenePoint = QPointF(0,0));
void zoomRestore(); void zoomRestore();
void centerRestore(); void centerRestore();
void centerOn(QPointF scenePoint = QPointF(0,0)); void centerOn(QPointF scenePoint = QPointF(0,0));
void zoom(const qreal ratio, QPointF scenePoint); void zoom(const qreal ratio, QPointF scenePoint);
void handScroll(qreal dx, qreal dy); void handScroll(qreal dx, qreal dy);
void previousScene(); void previousScene();
void nextScene(); void nextScene();
void firstScene(); void firstScene();
void lastScene(); void lastScene();
void groupButtonClicked(); 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); 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, UBItem *downloadFinished(bool pSuccess, QUrl sourceUrl, QUrl contentUrl, QString pHeader,
QByteArray pData, QPointF pPos, QSize pSize, QByteArray pData, QPointF pPos, QSize pSize,
bool isBackground = false, bool internalData = false); bool isBackground = false, bool internalData = false);
void changeBackground(bool isDark, bool isCrossed); void changeBackground(bool isDark, bool isCrossed);
void setToolCursor(int tool); void setToolCursor(int tool);
void showMessage(const QString& message, bool showSpinningWheel = false); void showMessage(const QString& message, bool showSpinningWheel = false);
void hideMessage(); void hideMessage();
void setDisabled(bool disable); void setDisabled(bool disable);
void setColorIndex(int pColorIndex); void setColorIndex(int pColorIndex);
void removeTool(UBToolWidget* toolWidget); void removeTool(UBToolWidget* toolWidget);
void hide(); void hide();
void show(); void show();
void setWidePageSize(bool checked); void setWidePageSize(bool checked);
void setRegularPageSize(bool checked); void setRegularPageSize(bool checked);
void stylusToolChanged(int tool); void stylusToolChanged(int tool);
void grabScene(const QRectF& pSceneRect); void grabScene(const QRectF& pSceneRect);
UBGraphicsMediaItem* addVideo(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false); 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); UBGraphicsMediaItem* addAudio(const QUrl& pUrl, bool startPlay, const QPointF& pos, bool bUseSource = false);
UBGraphicsWidgetItem *addW3cWidget(const QUrl& pUrl, const QPointF& pos); UBGraphicsWidgetItem *addW3cWidget(const QUrl& pUrl, const QPointF& pos);
void cut(); void cut();
void copy(); void copy();
void paste(); void paste();
void processMimeData(const QMimeData* pMimeData, const QPointF& pPos); void processMimeData(const QMimeData* pMimeData, const QPointF& pPos);
void moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicWidget); void moveGraphicsWidgetToControlView(UBGraphicsWidgetItem* graphicWidget);
void moveToolWidgetToScene(UBToolWidget* toolWidget); void moveToolWidgetToScene(UBToolWidget* toolWidget);
void addItem(); void addItem();
void freezeW3CWidgets(bool freeze); void freezeW3CWidgets(bool freeze);
void freezeW3CWidget(QGraphicsItem* item, bool freeze); void freezeW3CWidget(QGraphicsItem* item, bool freeze);
void startScript(); void startScript();
void stopScript(); void stopScript();
signals: signals:
void newPageAdded(); void newPageAdded();
void activeSceneChanged(); void activeSceneChanged();
void zoomChanged(qreal pZoomFactor); void zoomChanged(qreal pZoomFactor);
void systemScaleFactorChanged(qreal pSystemScaleFactor); void systemScaleFactorChanged(qreal pSystemScaleFactor);
void penColorChanged(); void penColorChanged();
void controlViewportChanged(); void controlViewportChanged();
void backgroundChanged(); void backgroundChanged();
void cacheEnabled(); void cacheEnabled();
void cacheDisabled(); void cacheDisabled();
void pageChanged(); void pageChanged();
void documentReorganized(int index); void documentReorganized(int index);
void displayMetadata(QMap<QString, QString> metadata); void displayMetadata(QMap<QString, QString> metadata);
void pageSelectionChanged(int index); void pageSelectionChanged(int index);
void npapiWidgetCreated(const QString &Url); void npapiWidgetCreated(const QString &Url);
protected: protected:
void setupViews(); void setupViews();
void setupToolbar(); void setupToolbar();
void connectToolbar(); void connectToolbar();
void initToolbarTexts(); void initToolbarTexts();
void updateActionStates(); void updateActionStates();
void updateSystemScaleFactor(); void updateSystemScaleFactor();
QString truncate(QString text, int maxWidth); QString truncate(QString text, int maxWidth);
protected slots: protected slots:
void selectionChanged(); void selectionChanged();
void undoRedoStateChange(bool canUndo); void undoRedoStateChange(bool canUndo);
void documentSceneChanged(UBDocumentProxy* proxy, int pIndex); void documentSceneChanged(UBDocumentProxy* proxy, int pIndex);
private: private:
void updatePageSizeState(); void updatePageSizeState();
void saveViewState(); void saveViewState();
void adjustDisplayViews(); void adjustDisplayViews();
UBMainWindow *mMainWindow; UBMainWindow *mMainWindow;
UBGraphicsScene* mActiveScene; UBGraphicsScene* mActiveScene;
int mActiveSceneIndex; int mActiveSceneIndex;
UBBoardPaletteManager *mPaletteManager; UBBoardPaletteManager *mPaletteManager;
UBSoftwareUpdateDialog *mSoftwareUpdateDialog; UBSoftwareUpdateDialog *mSoftwareUpdateDialog;
UBMessageWindow *mMessageWindow; UBMessageWindow *mMessageWindow;
UBBoardView *mControlView; UBBoardView *mControlView;
UBBoardView *mDisplayView; UBBoardView *mDisplayView;
QWidget *mControlContainer; QWidget *mControlContainer;
QHBoxLayout *mControlLayout; QHBoxLayout *mControlLayout;
qreal mZoomFactor; qreal mZoomFactor;
bool mIsClosing; bool mIsClosing;
QColor mPenColorOnDarkBackground; QColor mPenColorOnDarkBackground;
QColor mPenColorOnLightBackground; QColor mPenColorOnLightBackground;
QColor mMarkerColorOnDarkBackground; QColor mMarkerColorOnDarkBackground;
QColor mMarkerColorOnLightBackground; QColor mMarkerColorOnLightBackground;
qreal mSystemScaleFactor; qreal mSystemScaleFactor;
bool mCleanupDone; bool mCleanupDone;
QMap<QAction*, QPair<QString, QString> > mActionTexts; QMap<QAction*, QPair<QString, QString> > mActionTexts;
bool mCacheWidgetIsEnabled; bool mCacheWidgetIsEnabled;
QGraphicsItem* mLastCreatedItem; QGraphicsItem* mLastCreatedItem;
int mDeletingSceneIndex; int mDeletingSceneIndex;
int mMovingSceneIndex; int mMovingSceneIndex;
QString mActionGroupText; QString mActionGroupText;
QString mActionUngroupText; QString mActionUngroupText;
private slots: private slots:
void stylusToolDoubleClicked(int tool); void stylusToolDoubleClicked(int tool);
void boardViewResized(QResizeEvent* event); void boardViewResized(QResizeEvent* event);
void documentWillBeDeleted(UBDocumentProxy* pProxy); void documentWillBeDeleted(UBDocumentProxy* pProxy);
void updateBackgroundActionsState(bool isDark, bool isCrossed); void updateBackgroundActionsState(bool isDark, bool isCrossed);
void updateBackgroundState(); void updateBackgroundState();
void colorPaletteChanged(); void colorPaletteChanged();
void libraryDialogClosed(int ret); void libraryDialogClosed(int ret);
void lastWindowClosed(); void lastWindowClosed();
void onDownloadModalFinished(); void onDownloadModalFinished();
}; };
#endif /* UBBOARDCONTROLLER_H_ */ #endif /* UBBOARDCONTROLLER_H_ */
...@@ -19,984 +19,984 @@ ...@@ -19,984 +19,984 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBBoardPaletteManager.h" #include "UBBoardPaletteManager.h"
#include "frameworks/UBPlatformUtils.h" #include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h" #include "frameworks/UBFileSystemUtils.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBApplicationController.h" #include "core/UBApplicationController.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "core/UBSetting.h" #include "core/UBSetting.h"
#include "core/UBDisplayManager.h" #include "core/UBDisplayManager.h"
#include "gui/UBMainWindow.h" #include "gui/UBMainWindow.h"
#include "gui/UBStylusPalette.h" #include "gui/UBStylusPalette.h"
#include "gui/UBKeyboardPalette.h" #include "gui/UBKeyboardPalette.h"
#include "gui/UBToolWidget.h" #include "gui/UBToolWidget.h"
#include "gui/UBZoomPalette.h" #include "gui/UBZoomPalette.h"
#include "gui/UBWebToolsPalette.h" #include "gui/UBWebToolsPalette.h"
#include "gui/UBActionPalette.h" #include "gui/UBActionPalette.h"
#include "gui/UBFavoriteToolPalette.h" #include "gui/UBFavoriteToolPalette.h"
#include "gui/UBDockTeacherGuideWidget.h" #include "gui/UBDockTeacherGuideWidget.h"
#include "web/UBWebPage.h" #include "web/UBWebPage.h"
#include "web/UBWebController.h" #include "web/UBWebController.h"
#include "web/browser/WBBrowserWindow.h" #include "web/browser/WBBrowserWindow.h"
#include "web/browser/WBTabWidget.h" #include "web/browser/WBTabWidget.h"
#include "web/browser/WBWebView.h" #include "web/browser/WBWebView.h"
#include "desktop/UBDesktopAnnotationController.h" #include "desktop/UBDesktopAnnotationController.h"
#include "network/UBNetworkAccessManager.h" #include "network/UBNetworkAccessManager.h"
#include "network/UBServerXMLHttpRequest.h" #include "network/UBServerXMLHttpRequest.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "domain/UBGraphicsPixmapItem.h" #include "domain/UBGraphicsPixmapItem.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "podcast/UBPodcastController.h" #include "podcast/UBPodcastController.h"
#include "board/UBDrawingController.h" #include "board/UBDrawingController.h"
#include "tools/UBToolsManager.h" #include "tools/UBToolsManager.h"
#include "UBBoardController.h" #include "UBBoardController.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBBoardPaletteManager::UBBoardPaletteManager(QWidget* container, UBBoardController* pBoardController) UBBoardPaletteManager::UBBoardPaletteManager(QWidget* container, UBBoardController* pBoardController)
: QObject(container) : QObject(container)
, mKeyboardPalette(0) , mKeyboardPalette(0)
, mWebToolsCurrentPalette(0) , mWebToolsCurrentPalette(0)
, mContainer(container) , mContainer(container)
, mBoardControler(pBoardController) , mBoardControler(pBoardController)
, mStylusPalette(0) , mStylusPalette(0)
, mZoomPalette(0) , mZoomPalette(0)
, mLeftPalette(NULL) , mLeftPalette(NULL)
, mRightPalette(NULL) , mRightPalette(NULL)
, mBackgroundsPalette(0) , mBackgroundsPalette(0)
, mToolsPalette(0) , mToolsPalette(0)
, mAddItemPalette(0) , mAddItemPalette(0)
, mErasePalette(NULL) , mErasePalette(NULL)
, mPagePalette(NULL) , mPagePalette(NULL)
, mPendingPageButtonPressed(false) , mPendingPageButtonPressed(false)
, mPendingZoomButtonPressed(false) , mPendingZoomButtonPressed(false)
, mPendingPanButtonPressed(false) , mPendingPanButtonPressed(false)
, mPendingEraseButtonPressed(false) , mPendingEraseButtonPressed(false)
, mpPageNavigWidget(NULL) , mpPageNavigWidget(NULL)
, mpCachePropWidget(NULL) , mpCachePropWidget(NULL)
, mpDownloadWidget(NULL) , mpDownloadWidget(NULL)
, mpTeacherGuideWidget(NULL) , mpTeacherGuideWidget(NULL)
, mDownloadInProgress(false) , mDownloadInProgress(false)
{ {
setupPalettes(); setupPalettes();
connectPalettes(); connectPalettes();
} }
UBBoardPaletteManager::~UBBoardPaletteManager() UBBoardPaletteManager::~UBBoardPaletteManager()
{ {
// mAddedItemPalette is delete automatically because of is parent // mAddedItemPalette is delete automatically because of is parent
// that changes depending on the mode // that changes depending on the mode
// mMainWindow->centralWidget is the parent of mStylusPalette // mMainWindow->centralWidget is the parent of mStylusPalette
// do not delete this here. // do not delete this here.
} }
void UBBoardPaletteManager::initPalettesPosAtStartup() void UBBoardPaletteManager::initPalettesPosAtStartup()
{ {
mStylusPalette->initPosition(); mStylusPalette->initPosition();
} }
void UBBoardPaletteManager::setupLayout() void UBBoardPaletteManager::setupLayout()
{ {
} }
/** /**
* \brief Set up the dock palette widgets * \brief Set up the dock palette widgets
*/ */
void UBBoardPaletteManager::setupDockPaletteWidgets() void UBBoardPaletteManager::setupDockPaletteWidgets()
{ {
//------------------------------------------------// //------------------------------------------------//
// Create the widgets for the dock palettes // Create the widgets for the dock palettes
mpPageNavigWidget = new UBPageNavigationWidget(); mpPageNavigWidget = new UBPageNavigationWidget();
mpCachePropWidget = new UBCachePropertiesWidget(); mpCachePropWidget = new UBCachePropertiesWidget();
mpDownloadWidget = new UBDockDownloadWidget(); mpDownloadWidget = new UBDockDownloadWidget();
// Add the dock palettes // Add the dock palettes
mLeftPalette = new UBLeftPalette(mContainer); mLeftPalette = new UBLeftPalette(mContainer);
// LEFT palette widgets // LEFT palette widgets
mpPageNavigWidget = new UBPageNavigationWidget(); mpPageNavigWidget = new UBPageNavigationWidget();
mLeftPalette->registerWidget(mpPageNavigWidget); mLeftPalette->registerWidget(mpPageNavigWidget);
mLeftPalette->addTab(mpPageNavigWidget); mLeftPalette->addTab(mpPageNavigWidget);
if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool() || UBSettings::settings()->teacherGuideLessonPagesActivated->get().toBool()){ if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool() || UBSettings::settings()->teacherGuideLessonPagesActivated->get().toBool()){
mpTeacherGuideWidget = new UBDockTeacherGuideWidget(); mpTeacherGuideWidget = new UBDockTeacherGuideWidget();
mLeftPalette->registerWidget(mpTeacherGuideWidget); mLeftPalette->registerWidget(mpTeacherGuideWidget);
mLeftPalette->addTab(mpTeacherGuideWidget); mLeftPalette->addTab(mpTeacherGuideWidget);
} }
mLeftPalette->connectSignals(); mLeftPalette->connectSignals();
mLeftPalette->showTabWidget(0); mLeftPalette->showTabWidget(0);
mRightPalette = new UBRightPalette(mContainer); mRightPalette = new UBRightPalette(mContainer);
// RIGHT palette widgets // RIGHT palette widgets
mpFeaturesWidget = new UBFeaturesWidget(); mpFeaturesWidget = new UBFeaturesWidget();
mRightPalette->registerWidget(mpFeaturesWidget); mRightPalette->registerWidget(mpFeaturesWidget);
mRightPalette->addTab(mpFeaturesWidget); mRightPalette->addTab(mpFeaturesWidget);
// The cache widget will be visible only if a cache is put on the page // The cache widget will be visible only if a cache is put on the page
mRightPalette->registerWidget(mpCachePropWidget); mRightPalette->registerWidget(mpCachePropWidget);
// The download widget will be part of the right palette but // The download widget will be part of the right palette but
// will become visible only when the first download starts // will become visible only when the first download starts
mRightPalette->registerWidget(mpDownloadWidget); mRightPalette->registerWidget(mpDownloadWidget);
mRightPalette->connectSignals(); mRightPalette->connectSignals();
changeMode(eUBDockPaletteWidget_BOARD, true); changeMode(eUBDockPaletteWidget_BOARD, true);
// Hide the tabs that must be hidden // Hide the tabs that must be hidden
mRightPalette->removeTab(mpDownloadWidget); mRightPalette->removeTab(mpDownloadWidget);
mRightPalette->removeTab(mpCachePropWidget); mRightPalette->removeTab(mpCachePropWidget);
} }
void UBBoardPaletteManager::slot_changeMainMode(UBApplicationController::MainMode mainMode) void UBBoardPaletteManager::slot_changeMainMode(UBApplicationController::MainMode mainMode)
{ {
// Board = 0, Internet, Document, Tutorial, ParaschoolEditor, WebDocument // Board = 0, Internet, Document, Tutorial, ParaschoolEditor, WebDocument
switch( mainMode ) switch( mainMode )
{ {
case UBApplicationController::Board: case UBApplicationController::Board:
{ {
// call changeMode only when switch NOT from desktop mode // call changeMode only when switch NOT from desktop mode
if(!UBApplication::applicationController->isShowingDesktop()) if(!UBApplication::applicationController->isShowingDesktop())
changeMode(eUBDockPaletteWidget_BOARD); changeMode(eUBDockPaletteWidget_BOARD);
} }
break; break;
case UBApplicationController::Tutorial: case UBApplicationController::Tutorial:
{ {
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
mKeyboardPalette->hide(); mKeyboardPalette->hide();
} }
break; break;
case UBApplicationController::Internet: case UBApplicationController::Internet:
changeMode(eUBDockPaletteWidget_WEB); changeMode(eUBDockPaletteWidget_WEB);
break; break;
case UBApplicationController::Document: case UBApplicationController::Document:
changeMode(eUBDockPaletteWidget_DOCUMENT); changeMode(eUBDockPaletteWidget_DOCUMENT);
break; break;
default: default:
{ {
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
mKeyboardPalette->hide(); mKeyboardPalette->hide();
} }
break; break;
} }
} }
void UBBoardPaletteManager::slot_changeDesktopMode(bool isDesktop) void UBBoardPaletteManager::slot_changeDesktopMode(bool isDesktop)
{ {
UBApplicationController::MainMode currMode = UBApplication::applicationController->displayMode(); UBApplicationController::MainMode currMode = UBApplication::applicationController->displayMode();
if(!isDesktop) if(!isDesktop)
{ {
switch( currMode ) switch( currMode )
{ {
case UBApplicationController::Board: case UBApplicationController::Board:
changeMode(eUBDockPaletteWidget_BOARD); changeMode(eUBDockPaletteWidget_BOARD);
break; break;
default: default:
break; break;
} }
} }
else else
changeMode(eUBDockPaletteWidget_DESKTOP); changeMode(eUBDockPaletteWidget_DESKTOP);
} }
void UBBoardPaletteManager::setupPalettes() void UBBoardPaletteManager::setupPalettes()
{ {
if (UBPlatformUtils::hasVirtualKeyboard()) if (UBPlatformUtils::hasVirtualKeyboard())
{ {
mKeyboardPalette = new UBKeyboardPalette(0); mKeyboardPalette = new UBKeyboardPalette(0);
#ifndef Q_WS_WIN #ifndef Q_WS_WIN
connect(mKeyboardPalette, SIGNAL(closed()), mKeyboardPalette, SLOT(onDeactivated())); connect(mKeyboardPalette, SIGNAL(closed()), mKeyboardPalette, SLOT(onDeactivated()));
#endif #endif
} }
setupDockPaletteWidgets(); setupDockPaletteWidgets();
// Add the other palettes // Add the other palettes
mStylusPalette = new UBStylusPalette(mContainer, UBSettings::settings()->appToolBarOrientationVertical->get().toBool() ? Qt::Vertical : Qt::Horizontal); mStylusPalette = new UBStylusPalette(mContainer, UBSettings::settings()->appToolBarOrientationVertical->get().toBool() ? Qt::Vertical : Qt::Horizontal);
connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int))); connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
mStylusPalette->show(); // always show stylus palette at startup mStylusPalette->show(); // always show stylus palette at startup
mZoomPalette = new UBZoomPalette(mContainer); mZoomPalette = new UBZoomPalette(mContainer);
mStylusPalette->stackUnder(mZoomPalette); mStylusPalette->stackUnder(mZoomPalette);
QList<QAction*> backgroundsActions; QList<QAction*> backgroundsActions;
backgroundsActions << UBApplication::mainWindow->actionPlainLightBackground; backgroundsActions << UBApplication::mainWindow->actionPlainLightBackground;
backgroundsActions << UBApplication::mainWindow->actionCrossedLightBackground; backgroundsActions << UBApplication::mainWindow->actionCrossedLightBackground;
backgroundsActions << UBApplication::mainWindow->actionPlainDarkBackground; backgroundsActions << UBApplication::mainWindow->actionPlainDarkBackground;
backgroundsActions << UBApplication::mainWindow->actionCrossedDarkBackground; backgroundsActions << UBApplication::mainWindow->actionCrossedDarkBackground;
mBackgroundsPalette = new UBActionPalette(backgroundsActions, Qt::Horizontal , mContainer); mBackgroundsPalette = new UBActionPalette(backgroundsActions, Qt::Horizontal , mContainer);
mBackgroundsPalette->setButtonIconSize(QSize(128, 128)); mBackgroundsPalette->setButtonIconSize(QSize(128, 128));
mBackgroundsPalette->groupActions(); mBackgroundsPalette->groupActions();
mBackgroundsPalette->setClosable(true); mBackgroundsPalette->setClosable(true);
mBackgroundsPalette->setAutoClose(true); mBackgroundsPalette->setAutoClose(true);
mBackgroundsPalette->adjustSizeAndPosition(); mBackgroundsPalette->adjustSizeAndPosition();
mBackgroundsPalette->hide(); mBackgroundsPalette->hide();
QList<QAction*> addItemActions; QList<QAction*> addItemActions;
addItemActions << UBApplication::mainWindow->actionAddItemToCurrentPage; addItemActions << UBApplication::mainWindow->actionAddItemToCurrentPage;
addItemActions << UBApplication::mainWindow->actionAddItemToNewPage; addItemActions << UBApplication::mainWindow->actionAddItemToNewPage;
addItemActions << UBApplication::mainWindow->actionAddItemToLibrary; addItemActions << UBApplication::mainWindow->actionAddItemToLibrary;
mAddItemPalette = new UBActionPalette(addItemActions, Qt::Horizontal, mContainer); mAddItemPalette = new UBActionPalette(addItemActions, Qt::Horizontal, mContainer);
mAddItemPalette->setButtonIconSize(QSize(128, 128)); mAddItemPalette->setButtonIconSize(QSize(128, 128));
mAddItemPalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); mAddItemPalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
mAddItemPalette->groupActions(); mAddItemPalette->groupActions();
mAddItemPalette->setClosable(true); mAddItemPalette->setClosable(true);
mAddItemPalette->adjustSizeAndPosition(); mAddItemPalette->adjustSizeAndPosition();
mAddItemPalette->hide(); mAddItemPalette->hide();
QList<QAction*> eraseActions; QList<QAction*> eraseActions;
eraseActions << UBApplication::mainWindow->actionEraseAnnotations; eraseActions << UBApplication::mainWindow->actionEraseAnnotations;
eraseActions << UBApplication::mainWindow->actionEraseItems; eraseActions << UBApplication::mainWindow->actionEraseItems;
eraseActions << UBApplication::mainWindow->actionClearPage; eraseActions << UBApplication::mainWindow->actionClearPage;
eraseActions << UBApplication::mainWindow->actionEraseBackground; eraseActions << UBApplication::mainWindow->actionEraseBackground;
mErasePalette = new UBActionPalette(eraseActions, Qt::Horizontal , mContainer); mErasePalette = new UBActionPalette(eraseActions, Qt::Horizontal , mContainer);
mErasePalette->setButtonIconSize(QSize(128, 128)); mErasePalette->setButtonIconSize(QSize(128, 128));
mErasePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); mErasePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
mErasePalette->groupActions(); mErasePalette->groupActions();
mErasePalette->setClosable(true); mErasePalette->setClosable(true);
mErasePalette->adjustSizeAndPosition(); mErasePalette->adjustSizeAndPosition();
mErasePalette->hide(); mErasePalette->hide();
QList<QAction*> pageActions; QList<QAction*> pageActions;
pageActions << UBApplication::mainWindow->actionNewPage; pageActions << UBApplication::mainWindow->actionNewPage;
pageActions << UBApplication::mainWindow->actionDuplicatePage; pageActions << UBApplication::mainWindow->actionDuplicatePage;
pageActions << UBApplication::mainWindow->actionImportPage; pageActions << UBApplication::mainWindow->actionImportPage;
mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer); mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
mPagePalette->setButtonIconSize(QSize(128, 128)); mPagePalette->setButtonIconSize(QSize(128, 128));
mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
mPagePalette->groupActions(); mPagePalette->groupActions();
mPagePalette->setClosable(true); mPagePalette->setClosable(true);
mPagePalette->adjustSizeAndPosition(); mPagePalette->adjustSizeAndPosition();
mPagePalette->hide(); mPagePalette->hide();
connect(UBSettings::settings()->appToolBarOrientationVertical, SIGNAL(changed(QVariant)), this, SLOT(changeStylusPaletteOrientation(QVariant))); connect(UBSettings::settings()->appToolBarOrientationVertical, SIGNAL(changed(QVariant)), this, SLOT(changeStylusPaletteOrientation(QVariant)));
} }
void UBBoardPaletteManager::pagePaletteButtonPressed() void UBBoardPaletteManager::pagePaletteButtonPressed()
{ {
mPageButtonPressedTime = QTime::currentTime(); mPageButtonPressedTime = QTime::currentTime();
mPendingPageButtonPressed = true; mPendingPageButtonPressed = true;
QTimer::singleShot(1000, this, SLOT(pagePaletteButtonReleased())); QTimer::singleShot(1000, this, SLOT(pagePaletteButtonReleased()));
} }
void UBBoardPaletteManager::pagePaletteButtonReleased() void UBBoardPaletteManager::pagePaletteButtonReleased()
{ {
if (mPendingPageButtonPressed) if (mPendingPageButtonPressed)
{ {
if( mPageButtonPressedTime.msecsTo(QTime::currentTime()) > 900) if( mPageButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
{ {
// The palette is reinstanciated because the duplication depends on the current scene // The palette is reinstanciated because the duplication depends on the current scene
delete(mPagePalette); delete(mPagePalette);
mPagePalette = 0; mPagePalette = 0;
QList<QAction*>pageActions; QList<QAction*>pageActions;
pageActions << UBApplication::mainWindow->actionNewPage; pageActions << UBApplication::mainWindow->actionNewPage;
UBBoardController* boardController = UBApplication::boardController; UBBoardController* boardController = UBApplication::boardController;
if(UBApplication::documentController->pageCanBeDuplicated(UBDocumentContainer::pageFromSceneIndex(boardController->activeSceneIndex()))){ if(UBApplication::documentController->pageCanBeDuplicated(UBDocumentContainer::pageFromSceneIndex(boardController->activeSceneIndex()))){
pageActions << UBApplication::mainWindow->actionDuplicatePage; pageActions << UBApplication::mainWindow->actionDuplicatePage;
} }
pageActions << UBApplication::mainWindow->actionImportPage; pageActions << UBApplication::mainWindow->actionImportPage;
mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer); mPagePalette = new UBActionPalette(pageActions, Qt::Horizontal , mContainer);
mPagePalette->setButtonIconSize(QSize(128, 128)); mPagePalette->setButtonIconSize(QSize(128, 128));
mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); mPagePalette->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
mPagePalette->groupActions(); mPagePalette->groupActions();
mPagePalette->setClosable(true); mPagePalette->setClosable(true);
// As we recreate the pagePalette every time, we must reconnect the slots // As we recreate the pagePalette every time, we must reconnect the slots
connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed())); connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
togglePagePalette(true); togglePagePalette(true);
} }
else else
{ {
UBApplication::mainWindow->actionNewPage->trigger(); UBApplication::mainWindow->actionNewPage->trigger();
} }
mPendingPageButtonPressed = false; mPendingPageButtonPressed = false;
} }
} }
void UBBoardPaletteManager::erasePaletteButtonPressed() void UBBoardPaletteManager::erasePaletteButtonPressed()
{ {
mEraseButtonPressedTime = QTime::currentTime(); mEraseButtonPressedTime = QTime::currentTime();
mPendingEraseButtonPressed = true; mPendingEraseButtonPressed = true;
QTimer::singleShot(1000, this, SLOT(erasePaletteButtonReleased())); QTimer::singleShot(1000, this, SLOT(erasePaletteButtonReleased()));
} }
void UBBoardPaletteManager::erasePaletteButtonReleased() void UBBoardPaletteManager::erasePaletteButtonReleased()
{ {
if (mPendingEraseButtonPressed) if (mPendingEraseButtonPressed)
{ {
if( mEraseButtonPressedTime.msecsTo(QTime::currentTime()) > 900) if( mEraseButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
{ {
toggleErasePalette(true); toggleErasePalette(true);
} }
else else
{ {
UBApplication::mainWindow->actionClearPage->trigger(); UBApplication::mainWindow->actionClearPage->trigger();
} }
mPendingEraseButtonPressed = false; mPendingEraseButtonPressed = false;
} }
} }
void UBBoardPaletteManager::linkClicked(const QUrl& url) void UBBoardPaletteManager::linkClicked(const QUrl& url)
{ {
UBApplication::applicationController->showInternet(); UBApplication::applicationController->showInternet();
UBApplication::webController->loadUrl(url); UBApplication::webController->loadUrl(url);
} }
void UBBoardPaletteManager::purchaseLinkActivated(const QString& link) void UBBoardPaletteManager::purchaseLinkActivated(const QString& link)
{ {
UBApplication::applicationController->showInternet(); UBApplication::applicationController->showInternet();
UBApplication::webController->loadUrl(QUrl(link)); UBApplication::webController->loadUrl(QUrl(link));
} }
void UBBoardPaletteManager::connectPalettes() void UBBoardPaletteManager::connectPalettes()
{ {
connect(UBApplication::mainWindow->actionStylus, SIGNAL(toggled(bool)), this, SLOT(toggleStylusPalette(bool))); connect(UBApplication::mainWindow->actionStylus, SIGNAL(toggled(bool)), this, SLOT(toggleStylusPalette(bool)));
foreach(QWidget *widget, UBApplication::mainWindow->actionZoomIn->associatedWidgets()) foreach(QWidget *widget, UBApplication::mainWindow->actionZoomIn->associatedWidgets())
{ {
QAbstractButton *button = qobject_cast<QAbstractButton*>(widget); QAbstractButton *button = qobject_cast<QAbstractButton*>(widget);
if (button) if (button)
{ {
connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed())); connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased())); connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
} }
} }
foreach(QWidget *widget, UBApplication::mainWindow->actionZoomOut->associatedWidgets()) foreach(QWidget *widget, UBApplication::mainWindow->actionZoomOut->associatedWidgets())
{ {
QAbstractButton *button = qobject_cast<QAbstractButton*>(widget); QAbstractButton *button = qobject_cast<QAbstractButton*>(widget);
if (button) if (button)
{ {
connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed())); connect(button, SIGNAL(pressed()), this, SLOT(zoomButtonPressed()));
connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased())); connect(button, SIGNAL(released()), this, SLOT(zoomButtonReleased()));
} }
} }
foreach(QWidget *widget, UBApplication::mainWindow->actionHand->associatedWidgets()) foreach(QWidget *widget, UBApplication::mainWindow->actionHand->associatedWidgets())
{ {
QAbstractButton *button = qobject_cast<QAbstractButton*>(widget); QAbstractButton *button = qobject_cast<QAbstractButton*>(widget);
if (button) if (button)
{ {
connect(button, SIGNAL(pressed()), this, SLOT(panButtonPressed())); connect(button, SIGNAL(pressed()), this, SLOT(panButtonPressed()));
connect(button, SIGNAL(released()), this, SLOT(panButtonReleased())); connect(button, SIGNAL(released()), this, SLOT(panButtonReleased()));
} }
} }
connect(UBApplication::mainWindow->actionBackgrounds, SIGNAL(toggled(bool)), this, SLOT(toggleBackgroundPalette(bool))); connect(UBApplication::mainWindow->actionBackgrounds, SIGNAL(toggled(bool)), this, SLOT(toggleBackgroundPalette(bool)));
connect(mBackgroundsPalette, SIGNAL(closed()), this, SLOT(backgroundPaletteClosed())); connect(mBackgroundsPalette, SIGNAL(closed()), this, SLOT(backgroundPaletteClosed()));
connect(UBApplication::mainWindow->actionPlainLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground())); connect(UBApplication::mainWindow->actionPlainLightBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
connect(UBApplication::mainWindow->actionCrossedLightBackground, 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->actionPlainDarkBackground, SIGNAL(triggered()), this, SLOT(changeBackground()));
connect(UBApplication::mainWindow->actionCrossedDarkBackground, 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->actionPodcast, SIGNAL(triggered(bool)), this, SLOT(tooglePodcastPalette(bool)));
connect(UBApplication::mainWindow->actionAddItemToCurrentPage, SIGNAL(triggered()), this, SLOT(addItemToCurrentPage())); connect(UBApplication::mainWindow->actionAddItemToCurrentPage, SIGNAL(triggered()), this, SLOT(addItemToCurrentPage()));
connect(UBApplication::mainWindow->actionAddItemToNewPage, SIGNAL(triggered()), this, SLOT(addItemToNewPage())); connect(UBApplication::mainWindow->actionAddItemToNewPage, SIGNAL(triggered()), this, SLOT(addItemToNewPage()));
connect(UBApplication::mainWindow->actionAddItemToLibrary, SIGNAL(triggered()), this, SLOT(addItemToLibrary())); connect(UBApplication::mainWindow->actionAddItemToLibrary, SIGNAL(triggered()), this, SLOT(addItemToLibrary()));
connect(UBApplication::mainWindow->actionEraseItems, SIGNAL(triggered()), mErasePalette, SLOT(close())); connect(UBApplication::mainWindow->actionEraseItems, SIGNAL(triggered()), mErasePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionEraseAnnotations, 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->actionClearPage, SIGNAL(triggered()), mErasePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionEraseBackground,SIGNAL(triggered()),mErasePalette,SLOT(close())); connect(UBApplication::mainWindow->actionEraseBackground,SIGNAL(triggered()),mErasePalette,SLOT(close()));
connect(mErasePalette, SIGNAL(closed()), this, SLOT(erasePaletteClosed())); connect(mErasePalette, SIGNAL(closed()), this, SLOT(erasePaletteClosed()));
foreach(QWidget *widget, UBApplication::mainWindow->actionErase->associatedWidgets()) foreach(QWidget *widget, UBApplication::mainWindow->actionErase->associatedWidgets())
{ {
QAbstractButton *button = qobject_cast<QAbstractButton*>(widget); QAbstractButton *button = qobject_cast<QAbstractButton*>(widget);
if (button) if (button)
{ {
connect(button, SIGNAL(pressed()), this, SLOT(erasePaletteButtonPressed())); connect(button, SIGNAL(pressed()), this, SLOT(erasePaletteButtonPressed()));
connect(button, SIGNAL(released()), this, SLOT(erasePaletteButtonReleased())); connect(button, SIGNAL(released()), this, SLOT(erasePaletteButtonReleased()));
} }
} }
connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionNewPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionDuplicatePage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close())); connect(UBApplication::mainWindow->actionImportPage, SIGNAL(triggered()), mPagePalette, SLOT(close()));
connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed())); connect(mPagePalette, SIGNAL(closed()), this, SLOT(pagePaletteClosed()));
foreach(QWidget *widget, UBApplication::mainWindow->actionPages->associatedWidgets()) foreach(QWidget *widget, UBApplication::mainWindow->actionPages->associatedWidgets())
{ {
QAbstractButton *button = qobject_cast<QAbstractButton*>(widget); QAbstractButton *button = qobject_cast<QAbstractButton*>(widget);
if (button) if (button)
{ {
connect(button, SIGNAL(pressed()), this, SLOT(pagePaletteButtonPressed())); connect(button, SIGNAL(pressed()), this, SLOT(pagePaletteButtonPressed()));
connect(button, SIGNAL(released()), this, SLOT(pagePaletteButtonReleased())); connect(button, SIGNAL(released()), this, SLOT(pagePaletteButtonReleased()));
} }
} }
} }
bool isFirstResized = true; bool isFirstResized = true;
void UBBoardPaletteManager::containerResized() void UBBoardPaletteManager::containerResized()
{ {
int innerMargin = UBSettings::boardMargin; int innerMargin = UBSettings::boardMargin;
int userLeft = innerMargin; int userLeft = innerMargin;
int userWidth = mContainer->width() - (2 * innerMargin); int userWidth = mContainer->width() - (2 * innerMargin);
int userTop = innerMargin; int userTop = innerMargin;
int userHeight = mContainer->height() - (2 * innerMargin); int userHeight = mContainer->height() - (2 * innerMargin);
if(mStylusPalette) if(mStylusPalette)
{ {
mStylusPalette->move(userLeft, userTop); mStylusPalette->move(userLeft, userTop);
mStylusPalette->adjustSizeAndPosition(); mStylusPalette->adjustSizeAndPosition();
mStylusPalette->initPosition(); mStylusPalette->initPosition();
} }
if(mZoomPalette) if(mZoomPalette)
{ {
mZoomPalette->move(userLeft + userWidth - mZoomPalette->width() mZoomPalette->move(userLeft + userWidth - mZoomPalette->width()
, userTop + userHeight /*- mPageNumberPalette->height()*/ - innerMargin - mZoomPalette->height()); , userTop + userHeight /*- mPageNumberPalette->height()*/ - innerMargin - mZoomPalette->height());
mZoomPalette->adjustSizeAndPosition(); mZoomPalette->adjustSizeAndPosition();
} }
if (isFirstResized && mKeyboardPalette && mKeyboardPalette->parent() == UBApplication::boardController->controlContainer()) if (isFirstResized && mKeyboardPalette && mKeyboardPalette->parent() == UBApplication::boardController->controlContainer())
{ {
isFirstResized = false; isFirstResized = false;
mKeyboardPalette->move(userLeft + (userWidth - mKeyboardPalette->width())/2, mKeyboardPalette->move(userLeft + (userWidth - mKeyboardPalette->width())/2,
userTop + (userHeight - mKeyboardPalette->height())/2); userTop + (userHeight - mKeyboardPalette->height())/2);
mKeyboardPalette->adjustSizeAndPosition(); mKeyboardPalette->adjustSizeAndPosition();
} }
if(mLeftPalette) if(mLeftPalette)
{ {
mLeftPalette->resize(mLeftPalette->width()-1, mContainer->height()); mLeftPalette->resize(mLeftPalette->width()-1, mContainer->height());
mLeftPalette->resize(mLeftPalette->width(), mContainer->height()); mLeftPalette->resize(mLeftPalette->width(), mContainer->height());
} }
if(mRightPalette) if(mRightPalette)
{ {
mRightPalette->resize(mRightPalette->width()-1, mContainer->height()); mRightPalette->resize(mRightPalette->width()-1, mContainer->height());
mRightPalette->resize(mRightPalette->width(), mContainer->height()); mRightPalette->resize(mRightPalette->width(), mContainer->height());
} }
} }
void UBBoardPaletteManager::changeBackground() void UBBoardPaletteManager::changeBackground()
{ {
if (UBApplication::mainWindow->actionCrossedLightBackground->isChecked()) if (UBApplication::mainWindow->actionCrossedLightBackground->isChecked())
UBApplication::boardController->changeBackground(false, true); UBApplication::boardController->changeBackground(false, true);
else if (UBApplication::mainWindow->actionPlainDarkBackground->isChecked()) else if (UBApplication::mainWindow->actionPlainDarkBackground->isChecked())
UBApplication::boardController->changeBackground(true, false); UBApplication::boardController->changeBackground(true, false);
else if (UBApplication::mainWindow->actionCrossedDarkBackground->isChecked()) else if (UBApplication::mainWindow->actionCrossedDarkBackground->isChecked())
UBApplication::boardController->changeBackground(true, true); UBApplication::boardController->changeBackground(true, true);
else else
UBApplication::boardController->changeBackground(false, false); UBApplication::boardController->changeBackground(false, false);
UBApplication::mainWindow->actionBackgrounds->setChecked(false); UBApplication::mainWindow->actionBackgrounds->setChecked(false);
} }
void UBBoardPaletteManager::activeSceneChanged() void UBBoardPaletteManager::activeSceneChanged()
{ {
UBGraphicsScene *activeScene = UBApplication::boardController->activeScene(); UBGraphicsScene *activeScene = UBApplication::boardController->activeScene();
int pageIndex = UBApplication::boardController->activeSceneIndex(); int pageIndex = UBApplication::boardController->activeSceneIndex();
if (mStylusPalette) if (mStylusPalette)
connect(mStylusPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser())); connect(mStylusPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
if (mpPageNavigWidget) if (mpPageNavigWidget)
{ {
mpPageNavigWidget->setPageNumber(UBDocumentContainer::pageFromSceneIndex(pageIndex), activeScene->document()->pageCount()); mpPageNavigWidget->setPageNumber(UBDocumentContainer::pageFromSceneIndex(pageIndex), activeScene->document()->pageCount());
} }
if (mZoomPalette) if (mZoomPalette)
connect(mZoomPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser())); connect(mZoomPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
if (mBackgroundsPalette) if (mBackgroundsPalette)
connect(mBackgroundsPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser())); connect(mBackgroundsPalette, SIGNAL(mouseEntered()), activeScene, SLOT(hideEraser()));
} }
void UBBoardPaletteManager::toggleBackgroundPalette(bool checked) void UBBoardPaletteManager::toggleBackgroundPalette(bool checked)
{ {
mBackgroundsPalette->setVisible(checked); mBackgroundsPalette->setVisible(checked);
if (checked) if (checked)
{ {
UBApplication::mainWindow->actionErase->setChecked(false); UBApplication::mainWindow->actionErase->setChecked(false);
UBApplication::mainWindow->actionNewPage->setChecked(false); UBApplication::mainWindow->actionNewPage->setChecked(false);
mBackgroundsPalette->adjustSizeAndPosition(); mBackgroundsPalette->adjustSizeAndPosition();
mBackgroundsPalette->move((mContainer->width() - mBackgroundsPalette->width()) / 2, mBackgroundsPalette->move((mContainer->width() - mBackgroundsPalette->width()) / 2,
(mContainer->height() - mBackgroundsPalette->height()) / 5); (mContainer->height() - mBackgroundsPalette->height()) / 5);
} }
} }
void UBBoardPaletteManager::backgroundPaletteClosed() void UBBoardPaletteManager::backgroundPaletteClosed()
{ {
UBApplication::mainWindow->actionBackgrounds->setChecked(false); UBApplication::mainWindow->actionBackgrounds->setChecked(false);
} }
void UBBoardPaletteManager::toggleStylusPalette(bool checked) void UBBoardPaletteManager::toggleStylusPalette(bool checked)
{ {
mStylusPalette->setVisible(checked); mStylusPalette->setVisible(checked);
} }
void UBBoardPaletteManager::toggleErasePalette(bool checked) void UBBoardPaletteManager::toggleErasePalette(bool checked)
{ {
mErasePalette->setVisible(checked); mErasePalette->setVisible(checked);
if (checked) if (checked)
{ {
UBApplication::mainWindow->actionBackgrounds->setChecked(false); UBApplication::mainWindow->actionBackgrounds->setChecked(false);
UBApplication::mainWindow->actionNewPage->setChecked(false); UBApplication::mainWindow->actionNewPage->setChecked(false);
mErasePalette->adjustSizeAndPosition(); mErasePalette->adjustSizeAndPosition();
mErasePalette->move((mContainer->width() - mErasePalette->width()) / 2, mErasePalette->move((mContainer->width() - mErasePalette->width()) / 2,
(mContainer->height() - mErasePalette->height()) / 5); (mContainer->height() - mErasePalette->height()) / 5);
} }
} }
void UBBoardPaletteManager::erasePaletteClosed() void UBBoardPaletteManager::erasePaletteClosed()
{ {
UBApplication::mainWindow->actionErase->setChecked(false); UBApplication::mainWindow->actionErase->setChecked(false);
} }
void UBBoardPaletteManager::togglePagePalette(bool checked) void UBBoardPaletteManager::togglePagePalette(bool checked)
{ {
mPagePalette->setVisible(checked); mPagePalette->setVisible(checked);
if (checked) if (checked)
{ {
UBApplication::mainWindow->actionBackgrounds->setChecked(false); UBApplication::mainWindow->actionBackgrounds->setChecked(false);
UBApplication::mainWindow->actionErase->setChecked(false); UBApplication::mainWindow->actionErase->setChecked(false);
mPagePalette->adjustSizeAndPosition(); mPagePalette->adjustSizeAndPosition();
mPagePalette->move((mContainer->width() - mPagePalette->width()) / 2, mPagePalette->move((mContainer->width() - mPagePalette->width()) / 2,
(mContainer->height() - mPagePalette->height()) / 5); (mContainer->height() - mPagePalette->height()) / 5);
} }
} }
void UBBoardPaletteManager::pagePaletteClosed() void UBBoardPaletteManager::pagePaletteClosed()
{ {
UBApplication::mainWindow->actionPages->setChecked(false); UBApplication::mainWindow->actionPages->setChecked(false);
} }
void UBBoardPaletteManager::tooglePodcastPalette(bool checked) void UBBoardPaletteManager::tooglePodcastPalette(bool checked)
{ {
UBPodcastController::instance()->toggleRecordingPalette(checked); UBPodcastController::instance()->toggleRecordingPalette(checked);
} }
void UBBoardPaletteManager::addItem(const QUrl& pUrl) void UBBoardPaletteManager::addItem(const QUrl& pUrl)
{ {
mItemUrl = pUrl; mItemUrl = pUrl;
mPixmap = QPixmap(); mPixmap = QPixmap();
mPos = QPointF(0, 0); mPos = QPointF(0, 0);
mScaleFactor = 1.; mScaleFactor = 1.;
mAddItemPalette->show(); mAddItemPalette->show();
mAddItemPalette->adjustSizeAndPosition(); mAddItemPalette->adjustSizeAndPosition();
mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2, mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
(mContainer->height() - mAddItemPalette->height()) / 5); (mContainer->height() - mAddItemPalette->height()) / 5);
} }
void UBBoardPaletteManager::changeMode(eUBDockPaletteWidgetMode newMode, bool isInit) void UBBoardPaletteManager::changeMode(eUBDockPaletteWidgetMode newMode, bool isInit)
{ {
bool rightPaletteVisible = mRightPalette->switchMode(newMode); bool rightPaletteVisible = mRightPalette->switchMode(newMode);
bool leftPaletteVisible = mLeftPalette->switchMode(newMode); bool leftPaletteVisible = mLeftPalette->switchMode(newMode);
switch( newMode ) switch( newMode )
{ {
case eUBDockPaletteWidget_BOARD: case eUBDockPaletteWidget_BOARD:
{ {
// On Application start up the mAddItemPalette isn't initialized yet // On Application start up the mAddItemPalette isn't initialized yet
if(mAddItemPalette){ if(mAddItemPalette){
mAddItemPalette->setParent(UBApplication::boardController->controlContainer()); mAddItemPalette->setParent(UBApplication::boardController->controlContainer());
} }
mLeftPalette->assignParent(mContainer); mLeftPalette->assignParent(mContainer);
mRightPalette->assignParent(mContainer); mRightPalette->assignParent(mContainer);
mRightPalette->stackUnder(mStylusPalette); mRightPalette->stackUnder(mStylusPalette);
mLeftPalette->stackUnder(mStylusPalette); mLeftPalette->stackUnder(mStylusPalette);
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
{ {
if(mKeyboardPalette->m_isVisible) if(mKeyboardPalette->m_isVisible)
{ {
mKeyboardPalette->hide(); mKeyboardPalette->hide();
mKeyboardPalette->setParent(UBApplication::boardController->controlContainer()); mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
mKeyboardPalette->show(); mKeyboardPalette->show();
} }
else else
mKeyboardPalette->setParent(UBApplication::boardController->controlContainer()); mKeyboardPalette->setParent(UBApplication::boardController->controlContainer());
} }
mLeftPalette->setVisible(leftPaletteVisible); mLeftPalette->setVisible(leftPaletteVisible);
mRightPalette->setVisible(rightPaletteVisible); mRightPalette->setVisible(rightPaletteVisible);
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if (rightPaletteVisible) if (rightPaletteVisible)
mRightPalette->setAdditionalVOffset(0); mRightPalette->setAdditionalVOffset(0);
#endif #endif
if( !isInit ) if( !isInit )
containerResized(); containerResized();
if (mWebToolsCurrentPalette) if (mWebToolsCurrentPalette)
mWebToolsCurrentPalette->hide(); mWebToolsCurrentPalette->hide();
} }
break; break;
case eUBDockPaletteWidget_DESKTOP: case eUBDockPaletteWidget_DESKTOP:
{ {
mAddItemPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView()); mAddItemPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
mLeftPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView()); mLeftPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
mRightPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView()); mRightPalette->assignParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
mStylusPalette->raise(); mStylusPalette->raise();
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
{ {
if(mKeyboardPalette->m_isVisible) if(mKeyboardPalette->m_isVisible)
{ {
mKeyboardPalette->hide(); mKeyboardPalette->hide();
#ifndef Q_WS_X11 #ifndef Q_WS_X11
mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView()); mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
#else #else
mKeyboardPalette->setParent(0); mKeyboardPalette->setParent(0);
#endif #endif
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint); mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
#endif #endif
mKeyboardPalette->show(); mKeyboardPalette->show();
} }
else else
// In linux keyboard in desktop mode have to allways be with null parent // In linux keyboard in desktop mode have to allways be with null parent
#ifdef Q_WS_X11 #ifdef Q_WS_X11
mKeyboardPalette->setParent(0); mKeyboardPalette->setParent(0);
#else #else
mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView()); mKeyboardPalette->setParent((QWidget*)UBApplication::applicationController->uninotesController()->drawingView());
#endif //Q_WS_X11 #endif //Q_WS_X11
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint); mKeyboardPalette->setWindowFlags(Qt::Dialog | Qt::Popup | Qt::FramelessWindowHint);
#endif #endif
} }
mLeftPalette->setVisible(leftPaletteVisible); mLeftPalette->setVisible(leftPaletteVisible);
mRightPalette->setVisible(rightPaletteVisible); mRightPalette->setVisible(rightPaletteVisible);
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if (rightPaletteVisible && UBSettings::settings()->appToolBarPositionedAtTop->get().toBool()) if (rightPaletteVisible && UBSettings::settings()->appToolBarPositionedAtTop->get().toBool())
mRightPalette->setAdditionalVOffset(30); mRightPalette->setAdditionalVOffset(30);
#endif #endif
if(!isInit) if(!isInit)
UBApplication::applicationController->uninotesController()->TransparentWidgetResized(); UBApplication::applicationController->uninotesController()->TransparentWidgetResized();
if (mWebToolsCurrentPalette) if (mWebToolsCurrentPalette)
mWebToolsCurrentPalette->hide(); mWebToolsCurrentPalette->hide();
} }
break; break;
case eUBDockPaletteWidget_WEB: case eUBDockPaletteWidget_WEB:
{ {
mAddItemPalette->setParent(UBApplication::mainWindow); mAddItemPalette->setParent(UBApplication::mainWindow);
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
{ {
// tmp variable? // tmp variable?
// WBBrowserWindow* brWnd = UBApplication::webController->GetCurrentWebBrowser(); // WBBrowserWindow* brWnd = UBApplication::webController->GetCurrentWebBrowser();
if(mKeyboardPalette->m_isVisible) if(mKeyboardPalette->m_isVisible)
{ {
mKeyboardPalette->hide(); mKeyboardPalette->hide();
mKeyboardPalette->setParent(UBApplication::mainWindow); mKeyboardPalette->setParent(UBApplication::mainWindow);
mKeyboardPalette->show(); mKeyboardPalette->show();
} }
else else
mKeyboardPalette->setParent(UBApplication::mainWindow); mKeyboardPalette->setParent(UBApplication::mainWindow);
} }
} }
break; break;
case eUBDockPaletteWidget_DOCUMENT: case eUBDockPaletteWidget_DOCUMENT:
{ {
mLeftPalette->setVisible(leftPaletteVisible); mLeftPalette->setVisible(leftPaletteVisible);
mRightPalette->setVisible(rightPaletteVisible); mRightPalette->setVisible(rightPaletteVisible);
mLeftPalette->assignParent(UBApplication::documentController->controlView()); mLeftPalette->assignParent(UBApplication::documentController->controlView());
mRightPalette->assignParent(UBApplication::documentController->controlView()); mRightPalette->assignParent(UBApplication::documentController->controlView());
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
{ {
if(mKeyboardPalette->m_isVisible) if(mKeyboardPalette->m_isVisible)
{ {
mKeyboardPalette->hide(); mKeyboardPalette->hide();
mKeyboardPalette->setParent(UBApplication::documentController->controlView()); mKeyboardPalette->setParent(UBApplication::documentController->controlView());
mKeyboardPalette->show(); mKeyboardPalette->show();
} }
else else
mKeyboardPalette->setParent(UBApplication::documentController->controlView()); mKeyboardPalette->setParent(UBApplication::documentController->controlView());
} }
if (mWebToolsCurrentPalette) if (mWebToolsCurrentPalette)
mWebToolsCurrentPalette->hide(); mWebToolsCurrentPalette->hide();
} }
break; break;
default: default:
{ {
mLeftPalette->setVisible(leftPaletteVisible); mLeftPalette->setVisible(leftPaletteVisible);
mRightPalette->setVisible(rightPaletteVisible); mRightPalette->setVisible(rightPaletteVisible);
mLeftPalette->assignParent(0); mLeftPalette->assignParent(0);
mRightPalette->assignParent(0); mRightPalette->assignParent(0);
if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL) if (UBPlatformUtils::hasVirtualKeyboard() && mKeyboardPalette != NULL)
{ {
if(mKeyboardPalette->m_isVisible) if(mKeyboardPalette->m_isVisible)
{ {
mKeyboardPalette->hide(); mKeyboardPalette->hide();
mKeyboardPalette->setParent(0); mKeyboardPalette->setParent(0);
mKeyboardPalette->show(); mKeyboardPalette->show();
} }
else else
mKeyboardPalette->setParent(0); mKeyboardPalette->setParent(0);
} }
} }
break; break;
} }
if( !isInit ) if( !isInit )
UBApplication::boardController->notifyPageChanged(); UBApplication::boardController->notifyPageChanged();
emit signal_changeMode(newMode); emit signal_changeMode(newMode);
} }
void UBBoardPaletteManager::addItem(const QPixmap& pPixmap, const QPointF& pos, qreal scaleFactor, const QUrl& sourceUrl) void UBBoardPaletteManager::addItem(const QPixmap& pPixmap, const QPointF& pos, qreal scaleFactor, const QUrl& sourceUrl)
{ {
mItemUrl = sourceUrl; mItemUrl = sourceUrl;
mPixmap = pPixmap; mPixmap = pPixmap;
mPos = pos; mPos = pos;
mScaleFactor = scaleFactor; mScaleFactor = scaleFactor;
mAddItemPalette->show(); mAddItemPalette->show();
mAddItemPalette->adjustSizeAndPosition(); mAddItemPalette->adjustSizeAndPosition();
mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2, mAddItemPalette->move((mContainer->width() - mAddItemPalette->width()) / 2,
(mContainer->height() - mAddItemPalette->height()) / 5); (mContainer->height() - mAddItemPalette->height()) / 5);
} }
void UBBoardPaletteManager::addItemToCurrentPage() void UBBoardPaletteManager::addItemToCurrentPage()
{ {
UBApplication::applicationController->showBoard(); UBApplication::applicationController->showBoard();
mAddItemPalette->hide(); mAddItemPalette->hide();
if(mPixmap.isNull()) if(mPixmap.isNull())
UBApplication::boardController->downloadURL(mItemUrl); UBApplication::boardController->downloadURL(mItemUrl);
else else
{ {
UBGraphicsPixmapItem* item = UBApplication::boardController->activeScene()->addPixmap(mPixmap, NULL, mPos, mScaleFactor); UBGraphicsPixmapItem* item = UBApplication::boardController->activeScene()->addPixmap(mPixmap, NULL, mPos, mScaleFactor);
item->setSourceUrl(mItemUrl); item->setSourceUrl(mItemUrl);
item->setSelected(true); item->setSelected(true);
UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector); UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
} }
} }
void UBBoardPaletteManager::addItemToNewPage() void UBBoardPaletteManager::addItemToNewPage()
{ {
UBApplication::boardController->addScene(); UBApplication::boardController->addScene();
addItemToCurrentPage(); addItemToCurrentPage();
} }
void UBBoardPaletteManager::addItemToLibrary() void UBBoardPaletteManager::addItemToLibrary()
{ {
if(mPixmap.isNull()) if(mPixmap.isNull())
{ {
mPixmap = QPixmap(mItemUrl.toLocalFile()); mPixmap = QPixmap(mItemUrl.toLocalFile());
} }
if(!mPixmap.isNull()) if(!mPixmap.isNull())
{ {
if(mScaleFactor != 1.) if(mScaleFactor != 1.)
{ {
mPixmap = mPixmap.scaled(mScaleFactor * mPixmap.width(), mScaleFactor* mPixmap.height() mPixmap = mPixmap.scaled(mScaleFactor * mPixmap.width(), mScaleFactor* mPixmap.height()
, Qt::KeepAspectRatio, Qt::SmoothTransformation); , Qt::KeepAspectRatio, Qt::SmoothTransformation);
} }
QImage image = mPixmap.toImage(); QImage image = mPixmap.toImage();
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
QString capturedName = tr("CapturedImage") + "-" + now.toString("dd-MM-yyyy hh-mm-ss") + ".png"; QString capturedName = tr("CapturedImage") + "-" + now.toString("dd-MM-yyyy hh-mm-ss") + ".png";
mpFeaturesWidget->importImage(image, capturedName); mpFeaturesWidget->importImage(image, capturedName);
} }
else else
{ {
UBApplication::showMessage(tr("Error Adding Image to Library")); UBApplication::showMessage(tr("Error Adding Image to Library"));
} }
mAddItemPalette->hide(); mAddItemPalette->hide();
} }
void UBBoardPaletteManager::zoomButtonPressed() void UBBoardPaletteManager::zoomButtonPressed()
{ {
mZoomButtonPressedTime = QTime::currentTime(); mZoomButtonPressedTime = QTime::currentTime();
mPendingZoomButtonPressed = true; mPendingZoomButtonPressed = true;
QTimer::singleShot(1000, this, SLOT(zoomButtonReleased())); QTimer::singleShot(1000, this, SLOT(zoomButtonReleased()));
} }
void UBBoardPaletteManager::zoomButtonReleased() void UBBoardPaletteManager::zoomButtonReleased()
{ {
if (mPendingZoomButtonPressed) if (mPendingZoomButtonPressed)
{ {
if(mZoomButtonPressedTime.msecsTo(QTime::currentTime()) > 900) if(mZoomButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
{ {
mBoardControler->zoomRestore(); mBoardControler->zoomRestore();
} }
mPendingZoomButtonPressed = false; mPendingZoomButtonPressed = false;
} }
} }
void UBBoardPaletteManager::panButtonPressed() void UBBoardPaletteManager::panButtonPressed()
{ {
mPanButtonPressedTime = QTime::currentTime(); mPanButtonPressedTime = QTime::currentTime();
mPendingPanButtonPressed = true; mPendingPanButtonPressed = true;
QTimer::singleShot(1000, this, SLOT(panButtonReleased())); QTimer::singleShot(1000, this, SLOT(panButtonReleased()));
} }
void UBBoardPaletteManager::panButtonReleased() void UBBoardPaletteManager::panButtonReleased()
{ {
if (mPendingPanButtonPressed) if (mPendingPanButtonPressed)
{ {
if(mPanButtonPressedTime.msecsTo(QTime::currentTime()) > 900) if(mPanButtonPressedTime.msecsTo(QTime::currentTime()) > 900)
{ {
mBoardControler->centerRestore(); mBoardControler->centerRestore();
} }
mPendingPanButtonPressed = false; mPendingPanButtonPressed = false;
} }
} }
void UBBoardPaletteManager::showVirtualKeyboard(bool show) void UBBoardPaletteManager::showVirtualKeyboard(bool show)
{ {
if (mKeyboardPalette) if (mKeyboardPalette)
mKeyboardPalette->setVisible(show); mKeyboardPalette->setVisible(show);
} }
void UBBoardPaletteManager::changeStylusPaletteOrientation(QVariant var) void UBBoardPaletteManager::changeStylusPaletteOrientation(QVariant var)
{ {
bool bVertical = var.toBool(); bool bVertical = var.toBool();
bool bVisible = mStylusPalette->isVisible(); bool bVisible = mStylusPalette->isVisible();
// Clean the old palette // Clean the old palette
if(NULL != mStylusPalette) if(NULL != mStylusPalette)
{ {
delete mStylusPalette; delete mStylusPalette;
mStylusPalette = NULL; mStylusPalette = NULL;
} }
// Create the new palette // Create the new palette
if(bVertical) if(bVertical)
{ {
mStylusPalette = new UBStylusPalette(mContainer, Qt::Vertical); mStylusPalette = new UBStylusPalette(mContainer, Qt::Vertical);
} }
else else
{ {
mStylusPalette = new UBStylusPalette(mContainer, Qt::Horizontal); mStylusPalette = new UBStylusPalette(mContainer, Qt::Horizontal);
} }
connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int))); connect(mStylusPalette, SIGNAL(stylusToolDoubleClicked(int)), UBApplication::boardController, SLOT(stylusToolDoubleClicked(int)));
mStylusPalette->setVisible(bVisible); // always show stylus palette at startup mStylusPalette->setVisible(bVisible); // always show stylus palette at startup
} }
void UBBoardPaletteManager::connectToDocumentController() void UBBoardPaletteManager::connectToDocumentController()
{ {
emit connectToDocController(); emit connectToDocController();
} }
void UBBoardPaletteManager::refreshPalettes() void UBBoardPaletteManager::refreshPalettes()
{ {
mRightPalette->update(); mRightPalette->update();
mLeftPalette->update(); mLeftPalette->update();
} }
void UBBoardPaletteManager::startDownloads() void UBBoardPaletteManager::startDownloads()
{ {
if(!mDownloadInProgress) if(!mDownloadInProgress)
{ {
mDownloadInProgress = true; mDownloadInProgress = true;
mpDownloadWidget->setVisibleState(true); mpDownloadWidget->setVisibleState(true);
mRightPalette->addTab(mpDownloadWidget); mRightPalette->addTab(mpDownloadWidget);
} }
} }
void UBBoardPaletteManager::stopDownloads() void UBBoardPaletteManager::stopDownloads()
{ {
if(mDownloadInProgress) if(mDownloadInProgress)
{ {
mDownloadInProgress = false; mDownloadInProgress = false;
mpDownloadWidget->setVisibleState(false); mpDownloadWidget->setVisibleState(false);
mRightPalette->removeTab(mpDownloadWidget); mRightPalette->removeTab(mpDownloadWidget);
} }
} }
...@@ -19,173 +19,173 @@ ...@@ -19,173 +19,173 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBBOARDPALETTEMANAGER_H_ #ifndef UBBOARDPALETTEMANAGER_H_
#define UBBOARDPALETTEMANAGER_H_ #define UBBOARDPALETTEMANAGER_H_
#include <QtGui> #include <QtGui>
#include <QtWebKit> #include <QtWebKit>
#include "gui/UBLeftPalette.h" #include "gui/UBLeftPalette.h"
#include "gui/UBRightPalette.h" #include "gui/UBRightPalette.h"
#include "gui/UBPageNavigationWidget.h" #include "gui/UBPageNavigationWidget.h"
#include "gui/UBCachePropertiesWidget.h" #include "gui/UBCachePropertiesWidget.h"
#include "gui/UBDockDownloadWidget.h" #include "gui/UBDockDownloadWidget.h"
#include "core/UBApplicationController.h" #include "core/UBApplicationController.h"
#include "gui/UBFeaturesWidget.h" #include "gui/UBFeaturesWidget.h"
class UBWebToolsPalette; class UBWebToolsPalette;
class UBStylusPalette; class UBStylusPalette;
class UBClockPalette; class UBClockPalette;
class UBPageNumberPalette; class UBPageNumberPalette;
class UBZoomPalette; class UBZoomPalette;
class UBActionPalette; class UBActionPalette;
class UBBoardController; class UBBoardController;
class UBServerXMLHttpRequest; class UBServerXMLHttpRequest;
class UBKeyboardPalette; class UBKeyboardPalette;
class UBMainWindow; class UBMainWindow;
class UBApplicationController; class UBApplicationController;
class UBDockTeacherGuideWidget; class UBDockTeacherGuideWidget;
class UBBoardPaletteManager : public QObject class UBBoardPaletteManager : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
UBBoardPaletteManager(QWidget* container, UBBoardController* controller); UBBoardPaletteManager(QWidget* container, UBBoardController* controller);
virtual ~UBBoardPaletteManager(); virtual ~UBBoardPaletteManager();
void setupLayout(); void setupLayout();
UBLeftPalette* leftPalette(){return mLeftPalette;} UBLeftPalette* leftPalette(){return mLeftPalette;}
UBRightPalette* rightPalette(){return mRightPalette;} UBRightPalette* rightPalette(){return mRightPalette;}
UBStylusPalette* stylusPalette(){return mStylusPalette;} UBStylusPalette* stylusPalette(){return mStylusPalette;}
UBActionPalette *addItemPalette() {return mAddItemPalette;} UBActionPalette *addItemPalette() {return mAddItemPalette;}
void showVirtualKeyboard(bool show = true); void showVirtualKeyboard(bool show = true);
void initPalettesPosAtStartup(); void initPalettesPosAtStartup();
void connectToDocumentController(); void connectToDocumentController();
void refreshPalettes(); void refreshPalettes();
UBKeyboardPalette *mKeyboardPalette; UBKeyboardPalette *mKeyboardPalette;
void setCurrentWebToolsPalette(UBWebToolsPalette *palette) {mWebToolsCurrentPalette = palette;} void setCurrentWebToolsPalette(UBWebToolsPalette *palette) {mWebToolsCurrentPalette = palette;}
UBWebToolsPalette* mWebToolsCurrentPalette; UBWebToolsPalette* mWebToolsCurrentPalette;
UBDockTeacherGuideWidget* teacherGuideDockWidget() { return mpTeacherGuideWidget;} UBDockTeacherGuideWidget* teacherGuideDockWidget() { return mpTeacherGuideWidget;}
void processPalettersWidget(UBDockPalette *paletter, eUBDockPaletteWidgetMode mode); void processPalettersWidget(UBDockPalette *paletter, eUBDockPaletteWidgetMode mode);
void changeMode(eUBDockPaletteWidgetMode newMode, bool isInit = false); void changeMode(eUBDockPaletteWidgetMode newMode, bool isInit = false);
void startDownloads(); void startDownloads();
void stopDownloads(); void stopDownloads();
signals: signals:
void connectToDocController(); void connectToDocController();
void signal_changeMode(eUBDockPaletteWidgetMode newMode); void signal_changeMode(eUBDockPaletteWidgetMode newMode);
public slots: public slots:
void activeSceneChanged(); void activeSceneChanged();
void containerResized(); void containerResized();
void addItem(const QUrl& pUrl); 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 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_changeMainMode(UBApplicationController::MainMode);
void slot_changeDesktopMode(bool); void slot_changeDesktopMode(bool);
void toggleErasePalette(bool ckecked); void toggleErasePalette(bool ckecked);
private: private:
void setupPalettes(); void setupPalettes();
void connectPalettes(); void connectPalettes();
void positionFreeDisplayPalette(); void positionFreeDisplayPalette();
void setupDockPaletteWidgets(); void setupDockPaletteWidgets();
QWidget* mContainer; QWidget* mContainer;
UBBoardController *mBoardControler; UBBoardController *mBoardControler;
UBStylusPalette *mStylusPalette; UBStylusPalette *mStylusPalette;
UBZoomPalette *mZoomPalette; UBZoomPalette *mZoomPalette;
/** The left dock palette */ /** The left dock palette */
UBLeftPalette* mLeftPalette; UBLeftPalette* mLeftPalette;
/** The right dock palette */ /** The right dock palette */
UBRightPalette* mRightPalette; UBRightPalette* mRightPalette;
UBActionPalette *mBackgroundsPalette; UBActionPalette *mBackgroundsPalette;
UBActionPalette *mToolsPalette; UBActionPalette *mToolsPalette;
UBActionPalette* mAddItemPalette; UBActionPalette* mAddItemPalette;
UBActionPalette* mErasePalette; UBActionPalette* mErasePalette;
UBActionPalette* mPagePalette; UBActionPalette* mPagePalette;
QUrl mItemUrl; QUrl mItemUrl;
QPixmap mPixmap; QPixmap mPixmap;
QPointF mPos; QPointF mPos;
qreal mScaleFactor; qreal mScaleFactor;
QTime mPageButtonPressedTime; QTime mPageButtonPressedTime;
bool mPendingPageButtonPressed; bool mPendingPageButtonPressed;
QTime mZoomButtonPressedTime; QTime mZoomButtonPressedTime;
bool mPendingZoomButtonPressed; bool mPendingZoomButtonPressed;
QTime mPanButtonPressedTime; QTime mPanButtonPressedTime;
bool mPendingPanButtonPressed; bool mPendingPanButtonPressed;
QTime mEraseButtonPressedTime; QTime mEraseButtonPressedTime;
bool mPendingEraseButtonPressed; bool mPendingEraseButtonPressed;
/** The page navigator widget */ /** The page navigator widget */
UBPageNavigationWidget* mpPageNavigWidget; UBPageNavigationWidget* mpPageNavigWidget;
/** The cache properties widget */ /** The cache properties widget */
UBCachePropertiesWidget* mpCachePropWidget; UBCachePropertiesWidget* mpCachePropWidget;
UBFeaturesWidget *mpFeaturesWidget; UBFeaturesWidget *mpFeaturesWidget;
/** The download widget */ /** The download widget */
UBDockDownloadWidget* mpDownloadWidget; UBDockDownloadWidget* mpDownloadWidget;
UBDockTeacherGuideWidget* mpTeacherGuideWidget; UBDockTeacherGuideWidget* mpTeacherGuideWidget;
bool mDownloadInProgress; bool mDownloadInProgress;
private slots: private slots:
void changeBackground(); void changeBackground();
void toggleBackgroundPalette(bool checked); void toggleBackgroundPalette(bool checked);
void backgroundPaletteClosed(); void backgroundPaletteClosed();
void toggleStylusPalette(bool checked); void toggleStylusPalette(bool checked);
void tooglePodcastPalette(bool checked); void tooglePodcastPalette(bool checked);
void erasePaletteButtonPressed(); void erasePaletteButtonPressed();
void erasePaletteButtonReleased(); void erasePaletteButtonReleased();
void erasePaletteClosed(); void erasePaletteClosed();
void togglePagePalette(bool ckecked); void togglePagePalette(bool ckecked);
void pagePaletteClosed(); void pagePaletteClosed();
void pagePaletteButtonPressed(); void pagePaletteButtonPressed();
void pagePaletteButtonReleased(); void pagePaletteButtonReleased();
void addItemToCurrentPage(); void addItemToCurrentPage();
void addItemToNewPage(); void addItemToNewPage();
void addItemToLibrary(); void addItemToLibrary();
void purchaseLinkActivated(const QString&); void purchaseLinkActivated(const QString&);
void linkClicked(const QUrl& url); void linkClicked(const QUrl& url);
void zoomButtonPressed(); void zoomButtonPressed();
void zoomButtonReleased(); void zoomButtonReleased();
void panButtonPressed(); void panButtonPressed();
void panButtonReleased(); void panButtonReleased();
void changeStylusPaletteOrientation(QVariant var); void changeStylusPaletteOrientation(QVariant var);
}; };
#endif /* UBBOARDPALETTEMANAGER_H_ */ #endif /* UBBOARDPALETTEMANAGER_H_ */
...@@ -19,164 +19,164 @@ ...@@ -19,164 +19,164 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBBOARDVIEW_H_ #ifndef UBBOARDVIEW_H_
#define UBBOARDVIEW_H_ #define UBBOARDVIEW_H_
#include <QtGui> #include <QtGui>
#include "core/UB.h" #include "core/UB.h"
#include "domain/UBGraphicsDelegateFrame.h" #include "domain/UBGraphicsDelegateFrame.h"
class UBBoardController; class UBBoardController;
class UBGraphicsScene; class UBGraphicsScene;
class UBGraphicsWidgetItem; class UBGraphicsWidgetItem;
class UBRubberBand; class UBRubberBand;
class UBBoardView : public QGraphicsView class UBBoardView : public QGraphicsView
{ {
Q_OBJECT Q_OBJECT
public: public:
UBBoardView(UBBoardController* pController, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false); 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); UBBoardView(UBBoardController* pController, int pStartLayer, int pEndLayer, QWidget* pParent = 0, bool isControl = false, bool isDesktop = false);
virtual ~UBBoardView(); virtual ~UBBoardView();
UBGraphicsScene* scene(); UBGraphicsScene* scene();
void forcedTabletRelease(); void forcedTabletRelease();
void setToolCursor(int tool); void setToolCursor(int tool);
void rubberItems(); void rubberItems();
void moveRubberedItems(QPointF movingVector); void moveRubberedItems(QPointF movingVector);
void setMultiselection(bool enable); void setMultiselection(bool enable);
bool isMultipleSelectionEnabled() { return mMultipleSelectionIsEnabled; } bool isMultipleSelectionEnabled() { return mMultipleSelectionIsEnabled; }
signals: signals:
void resized(QResizeEvent* event); void resized(QResizeEvent* event);
void hidden(); void hidden();
void shown(); void shown();
void clickOnBoard(); void clickOnBoard();
protected: protected:
bool itemIsLocked(QGraphicsItem *item); 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 isUBItem(QGraphicsItem *item); // we should to determine items who is not UB and use general scene behavior for them.
bool isCppTool(QGraphicsItem *item); bool isCppTool(QGraphicsItem *item);
void handleItemsSelection(QGraphicsItem *item); void handleItemsSelection(QGraphicsItem *item);
bool itemShouldReceiveMousePressEvent(QGraphicsItem *item); bool itemShouldReceiveMousePressEvent(QGraphicsItem *item);
bool itemShouldReceiveSuspendedMousePressEvent(QGraphicsItem *item); bool itemShouldReceiveSuspendedMousePressEvent(QGraphicsItem *item);
bool itemHaveParentWithType(QGraphicsItem *item, int type); bool itemHaveParentWithType(QGraphicsItem *item, int type);
bool itemShouldBeMoved(QGraphicsItem *item); bool itemShouldBeMoved(QGraphicsItem *item);
QGraphicsItem* determineItemToPress(QGraphicsItem *item); QGraphicsItem* determineItemToPress(QGraphicsItem *item);
QGraphicsItem* determineItemToMove(QGraphicsItem *item); QGraphicsItem* determineItemToMove(QGraphicsItem *item);
void handleItemMousePress(QMouseEvent *event); void handleItemMousePress(QMouseEvent *event);
void handleItemMouseMove(QMouseEvent *event); void handleItemMouseMove(QMouseEvent *event);
virtual bool event (QEvent * e); virtual bool event (QEvent * e);
virtual void keyPressEvent(QKeyEvent *event); virtual void keyPressEvent(QKeyEvent *event);
virtual void keyReleaseEvent(QKeyEvent *event); virtual void keyReleaseEvent(QKeyEvent *event);
virtual void tabletEvent(QTabletEvent * event); virtual void tabletEvent(QTabletEvent * event);
virtual void mouseDoubleClickEvent(QMouseEvent *event); virtual void mouseDoubleClickEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event); virtual void wheelEvent(QWheelEvent *event);
virtual void leaveEvent ( QEvent * event); virtual void leaveEvent ( QEvent * event);
virtual void focusOutEvent ( QFocusEvent * event ); virtual void focusOutEvent ( QFocusEvent * event );
virtual void drawItems(QPainter *painter, int numItems, virtual void drawItems(QPainter *painter, int numItems,
QGraphicsItem *items[], QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[]); const QStyleOptionGraphicsItem options[]);
// virtual void dragEnterEvent(QDragEnterEvent * event); // virtual void dragEnterEvent(QDragEnterEvent * event);
virtual void dropEvent(QDropEvent *event); virtual void dropEvent(QDropEvent *event);
virtual void dragMoveEvent(QDragMoveEvent *event); virtual void dragMoveEvent(QDragMoveEvent *event);
virtual void resizeEvent(QResizeEvent * event); virtual void resizeEvent(QResizeEvent * event);
virtual void drawBackground(QPainter *painter, const QRectF &rect); virtual void drawBackground(QPainter *painter, const QRectF &rect);
virtual void showEvent(QShowEvent * event); virtual void showEvent(QShowEvent * event);
virtual void hideEvent(QHideEvent * event); virtual void hideEvent(QHideEvent * event);
private: private:
void init(); void init();
inline bool shouldDisplayItem(QGraphicsItem *item) inline bool shouldDisplayItem(QGraphicsItem *item)
{ {
bool ok; bool ok;
int itemLayerType = item->data(UBGraphicsItemData::ItemLayerType).toInt(&ok); int itemLayerType = item->data(UBGraphicsItemData::ItemLayerType).toInt(&ok);
return (ok && (itemLayerType >= mStartLayer && itemLayerType <= mEndLayer)); return (ok && (itemLayerType >= mStartLayer && itemLayerType <= mEndLayer));
} }
QList<QUrl> processMimeData(const QMimeData* pMimeData); QList<QUrl> processMimeData(const QMimeData* pMimeData);
UBBoardController* mController; UBBoardController* mController;
int mStartLayer, mEndLayer; int mStartLayer, mEndLayer;
bool mFilterZIndex; bool mFilterZIndex;
bool mTabletStylusIsPressed; bool mTabletStylusIsPressed;
bool mUsingTabletEraser; bool mUsingTabletEraser;
bool mPendingStylusReleaseEvent; bool mPendingStylusReleaseEvent;
bool mMouseButtonIsPressed; bool mMouseButtonIsPressed;
QPointF mPreviousPoint; QPointF mPreviousPoint;
QPoint mMouseDownPos; QPoint mMouseDownPos;
bool mPenPressureSensitive; bool mPenPressureSensitive;
bool mMarkerPressureSensitive; bool mMarkerPressureSensitive;
bool mUseHighResTabletEvent; bool mUseHighResTabletEvent;
QRubberBand *mRubberBand; QRubberBand *mRubberBand;
bool mIsCreatingTextZone; bool mIsCreatingTextZone;
bool mIsCreatingSceneGrabZone; bool mIsCreatingSceneGrabZone;
bool isAbsurdPoint(QPoint point); bool isAbsurdPoint(QPoint point);
bool mVirtualKeyboardActive; bool mVirtualKeyboardActive;
bool mOkOnWidget; bool mOkOnWidget;
bool mWidgetMoved; bool mWidgetMoved;
QPointF mLastPressedMousePos; QPointF mLastPressedMousePos;
QGraphicsItem *movingItem; QGraphicsItem *movingItem;
QMouseEvent *suspendedMousePressEvent; QMouseEvent *suspendedMousePressEvent;
bool moveRubberBand; bool moveRubberBand;
UBRubberBand *mUBRubberBand; UBRubberBand *mUBRubberBand;
QList<QGraphicsItem *> mRubberedItems; QList<QGraphicsItem *> mRubberedItems;
QSet<QGraphicsItem*> mJustSelectedItems; QSet<QGraphicsItem*> mJustSelectedItems;
int mLongPressInterval; int mLongPressInterval;
QTimer mLongPressTimer; QTimer mLongPressTimer;
bool mIsDragInProgress; bool mIsDragInProgress;
bool mMultipleSelectionIsEnabled; bool mMultipleSelectionIsEnabled;
bool bIsControl; bool bIsControl;
bool bIsDesktop; bool bIsDesktop;
bool mRubberBandInPlayMode; bool mRubberBandInPlayMode;
static bool hasSelectedParents(QGraphicsItem * item); static bool hasSelectedParents(QGraphicsItem * item);
private slots: private slots:
void settingChanged(QVariant newValue); void settingChanged(QVariant newValue);
public slots: public slots:
void virtualKeyboardActivated(bool b); void virtualKeyboardActivated(bool b);
void longPressEvent(); void longPressEvent();
}; };
#endif /* UBBOARDVIEW_H_ */ #endif /* UBBOARDVIEW_H_ */
...@@ -19,155 +19,155 @@ ...@@ -19,155 +19,155 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBAPPLICATION_H_ #ifndef UBAPPLICATION_H_
#define UBAPPLICATION_H_ #define UBAPPLICATION_H_
#include <QtGui> #include <QtGui>
#include "qtsingleapplication.h" #include "qtsingleapplication.h"
#include "transition/UniboardSankoreTransition.h" #include "transition/UniboardSankoreTransition.h"
namespace Ui namespace Ui
{ {
class MainWindow; class MainWindow;
} }
class UBBoardController; class UBBoardController;
class UBWebController; class UBWebController;
class UBControlView; class UBControlView;
class UBPreferencesController; class UBPreferencesController;
class UBResources; class UBResources;
class UBSettings; class UBSettings;
class UBPersistenceManager; class UBPersistenceManager;
class UBApplicationController; class UBApplicationController;
class UBDocumentController; class UBDocumentController;
class UBMainWindow; class UBMainWindow;
class UBApplication : public QtSingleApplication class UBApplication : public QtSingleApplication
{ {
Q_OBJECT; Q_OBJECT;
public: public:
UBApplication(const QString &id, int &argc, char **argv); UBApplication(const QString &id, int &argc, char **argv);
virtual ~UBApplication(); virtual ~UBApplication();
int exec(const QString& pFileToImport); int exec(const QString& pFileToImport);
void cleanup(); void cleanup();
static QPointer<QUndoStack> undoStack; static QPointer<QUndoStack> undoStack;
static UBApplicationController *applicationController; static UBApplicationController *applicationController;
static UBBoardController* boardController; static UBBoardController* boardController;
static UBWebController* webController; static UBWebController* webController;
static UBDocumentController* documentController; static UBDocumentController* documentController;
static UniboardSankoreTransition* mUniboardSankoreTransition; static UniboardSankoreTransition* mUniboardSankoreTransition;
static UBMainWindow* mainWindow; static UBMainWindow* mainWindow;
static UBApplication* app() static UBApplication* app()
{ {
return static_cast<UBApplication*>qApp; return static_cast<UBApplication*>qApp;
} }
static const QString mimeTypeUniboardDocument; static const QString mimeTypeUniboardDocument;
static const QString mimeTypeUniboardPage; static const QString mimeTypeUniboardPage;
static const QString mimeTypeUniboardPageItem; static const QString mimeTypeUniboardPageItem;
static const QString mimeTypeUniboardPageThumbnail; static const QString mimeTypeUniboardPageThumbnail;
static void showMessage(const QString& message, bool showSpinningWheel = false); static void showMessage(const QString& message, bool showSpinningWheel = false);
static void setDisabled(bool disable); static void setDisabled(bool disable);
static QObject* staticMemoryCleaner; static QObject* staticMemoryCleaner;
void decorateActionMenu(QAction* action); void decorateActionMenu(QAction* action);
void insertSpaceToToolbarBeforeAction(QToolBar* toolbar, QAction* action, int width = -1); void insertSpaceToToolbarBeforeAction(QToolBar* toolbar, QAction* action, int width = -1);
int toolBarHeight(); int toolBarHeight();
bool eventFilter(QObject *obj, QEvent *event); bool eventFilter(QObject *obj, QEvent *event);
bool isVerbose() { return mIsVerbose;} bool isVerbose() { return mIsVerbose;}
void setVerbose(bool verbose){mIsVerbose = verbose;} void setVerbose(bool verbose){mIsVerbose = verbose;}
static QString urlFromHtml(QString html); static QString urlFromHtml(QString html);
static bool isFromWeb(QString url); static bool isFromWeb(QString url);
signals: signals:
public slots: public slots:
void showBoard(); void showBoard();
void showInternet(); void showInternet();
void showDocument(); void showDocument();
void startScript(); void startScript();
void stopScript(); void stopScript();
void toolBarPositionChanged(QVariant topOrBottom); void toolBarPositionChanged(QVariant topOrBottom);
void toolBarDisplayTextChanged(QVariant display); void toolBarDisplayTextChanged(QVariant display);
void closeEvent(QCloseEvent *event); void closeEvent(QCloseEvent *event);
/** /**
* Used on Windows platform to open file in running application. On MacOS X opening file is done through the * 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. * FileOpen event that is handle in eventFilter method.
*/ */
bool handleOpenMessage(const QString& pMessage); bool handleOpenMessage(const QString& pMessage);
private slots: private slots:
void closing(); void closing();
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
void showMinimized(); void showMinimized();
#endif #endif
void importUniboardFiles(); void importUniboardFiles();
void onScreenCountChanged(int newCount); void onScreenCountChanged(int newCount);
private: private:
void updateProtoActionsState(); void updateProtoActionsState();
void setupTranslators(QStringList args); void setupTranslators(QStringList args);
QList<QMenu*> mProtoMenus; QList<QMenu*> mProtoMenus;
bool mIsVerbose; bool mIsVerbose;
QString checkLanguageAvailabilityForSankore(QString& language); QString checkLanguageAvailabilityForSankore(QString& language);
protected: protected:
#if defined(Q_WS_MACX) && !defined(QT_MAC_USE_COCOA) #if defined(Q_WS_MACX) && !defined(QT_MAC_USE_COCOA)
bool macEventFilter(EventHandlerCallRef caller, EventRef event); bool macEventFilter(EventHandlerCallRef caller, EventRef event);
#endif #endif
UBPreferencesController* mPreferencesController; UBPreferencesController* mPreferencesController;
QTranslator* mApplicationTranslator; QTranslator* mApplicationTranslator;
QTranslator* mQtGuiTranslator; QTranslator* mQtGuiTranslator;
}; };
class UBStyle : public QPlastiqueStyle class UBStyle : public QPlastiqueStyle
{ {
public: public:
UBStyle() UBStyle()
: QPlastiqueStyle() : QPlastiqueStyle()
{ {
// NOOP // NOOP
} }
virtual ~UBStyle() virtual ~UBStyle()
{ {
// NOOP // NOOP
} }
/* /*
* redefined to be more cocoa like on texts * redefined to be more cocoa like on texts
*/ */
virtual void drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal, virtual void drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
bool enabled, const QString& text, QPalette::ColorRole textRole) const; bool enabled, const QString& text, QPalette::ColorRole textRole) const;
}; };
#endif /* UBAPPLICATION_H_ */ #endif /* UBAPPLICATION_H_ */
...@@ -19,820 +19,820 @@ ...@@ -19,820 +19,820 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBApplicationController.h" #include "UBApplicationController.h"
#include "frameworks/UBPlatformUtils.h" #include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBVersion.h" #include "frameworks/UBVersion.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "core/UBSetting.h" #include "core/UBSetting.h"
#include "core/UBDocumentManager.h" #include "core/UBDocumentManager.h"
#include "core/UBDisplayManager.h" #include "core/UBDisplayManager.h"
#include "board/UBBoardView.h" #include "board/UBBoardView.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "board/UBBoardPaletteManager.h" #include "board/UBBoardPaletteManager.h"
#include "board/UBDrawingController.h" #include "board/UBDrawingController.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "domain/UBGraphicsWidgetItem.h" #include "domain/UBGraphicsWidgetItem.h"
#include "desktop/UBDesktopPalette.h" #include "desktop/UBDesktopPalette.h"
#include "desktop/UBDesktopAnnotationController.h" #include "desktop/UBDesktopAnnotationController.h"
#include "web/UBWebController.h" #include "web/UBWebController.h"
#include "gui/UBScreenMirror.h" #include "gui/UBScreenMirror.h"
#include "gui/UBMainWindow.h" #include "gui/UBMainWindow.h"
#include "gui/UBDockTeacherGuideWidget.h" #include "gui/UBDockTeacherGuideWidget.h"
#include "gui/UBTeacherGuideWidget.h" #include "gui/UBTeacherGuideWidget.h"
#include "domain/UBGraphicsPixmapItem.h" #include "domain/UBGraphicsPixmapItem.h"
#include "podcast/UBPodcastController.h" #include "podcast/UBPodcastController.h"
#include "network/UBNetworkAccessManager.h" #include "network/UBNetworkAccessManager.h"
#include "ui_mainWindow.h" #include "ui_mainWindow.h"
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
#include <Carbon/Carbon.h> #include <Carbon/Carbon.h>
#endif #endif
#include "core/memcheck.h" #include "core/memcheck.h"
UBApplicationController::UBApplicationController(UBBoardView *pControlView, UBApplicationController::UBApplicationController(UBBoardView *pControlView,
UBBoardView *pDisplayView, UBBoardView *pDisplayView,
UBMainWindow* pMainWindow, UBMainWindow* pMainWindow,
QObject* parent, QObject* parent,
UBRightPalette* rightPalette) UBRightPalette* rightPalette)
: QObject(parent) : QObject(parent)
, mMainWindow(pMainWindow) , mMainWindow(pMainWindow)
, mControlView(pControlView) , mControlView(pControlView)
, mDisplayView(pDisplayView) , mDisplayView(pDisplayView)
, mMirror(0) , mMirror(0)
, mMainMode(Board) , mMainMode(Board)
, mDisplayManager(0) , mDisplayManager(0)
, mAutomaticCheckForUpdates(false) , mAutomaticCheckForUpdates(false)
, mCheckingForUpdates(false) , mCheckingForUpdates(false)
, mIsShowingDesktop(false) , mIsShowingDesktop(false)
, mHttp(0) , mHttp(0)
{ {
mDisplayManager = new UBDisplayManager(this); mDisplayManager = new UBDisplayManager(this);
mUninoteController = new UBDesktopAnnotationController(this, rightPalette); mUninoteController = new UBDesktopAnnotationController(this, rightPalette);
connect(mDisplayManager, SIGNAL(screenLayoutChanged()), this, SLOT(screenLayoutChanged())); connect(mDisplayManager, SIGNAL(screenLayoutChanged()), this, SLOT(screenLayoutChanged()));
connect(mDisplayManager, SIGNAL(screenLayoutChanged()), mUninoteController, SLOT(screenLayoutChanged())); connect(mDisplayManager, SIGNAL(screenLayoutChanged()), mUninoteController, SLOT(screenLayoutChanged()));
connect(mDisplayManager, SIGNAL(screenLayoutChanged()), UBApplication::webController, 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(imageCaptured(const QPixmap &, bool)), this, SLOT(addCapturedPixmap(const QPixmap &, bool)));
connect(mUninoteController, SIGNAL(restoreUniboard()), this, SLOT(hideDesktop())); connect(mUninoteController, SIGNAL(restoreUniboard()), this, SLOT(hideDesktop()));
for(int i = 0; i < mDisplayManager->numPreviousViews(); i++) for(int i = 0; i < mDisplayManager->numPreviousViews(); i++)
{ {
UBBoardView *previousView = new UBBoardView(UBApplication::boardController, UBItemLayerType::FixedBackground, UBItemLayerType::Tool, 0); UBBoardView *previousView = new UBBoardView(UBApplication::boardController, UBItemLayerType::FixedBackground, UBItemLayerType::Tool, 0);
previousView->setInteractive(false); previousView->setInteractive(false);
mPreviousViews.append(previousView); mPreviousViews.append(previousView);
} }
mBlackScene = new UBGraphicsScene(0); // deleted by UBApplicationController::destructor mBlackScene = new UBGraphicsScene(0); // deleted by UBApplicationController::destructor
mBlackScene->setBackground(true, false); mBlackScene->setBackground(true, false);
if (mDisplayManager->numScreens() >= 2) if (mDisplayManager->numScreens() >= 2)
{ {
mMirror = new UBScreenMirror(); mMirror = new UBScreenMirror();
} }
connect(UBApplication::webController, SIGNAL(imageCaptured(const QPixmap &, bool, const QUrl&)) connect(UBApplication::webController, SIGNAL(imageCaptured(const QPixmap &, bool, const QUrl&))
, this, SLOT(addCapturedPixmap(const QPixmap &, bool, const QUrl&))); , this, SLOT(addCapturedPixmap(const QPixmap &, bool, const QUrl&)));
networkAccessManager = new QNetworkAccessManager (this); networkAccessManager = new QNetworkAccessManager (this);
QTimer::singleShot (1000, this, SLOT (checkUpdateAtLaunch())); QTimer::singleShot (1000, this, SLOT (checkUpdateAtLaunch()));
#ifdef Q_WS_X11 #ifdef Q_WS_X11
mMainWindow->setStyleSheet("QToolButton { font-size: 11px}"); mMainWindow->setStyleSheet("QToolButton { font-size: 11px}");
#endif #endif
} }
UBApplicationController::~UBApplicationController() UBApplicationController::~UBApplicationController()
{ {
foreach(UBBoardView* view, mPreviousViews) foreach(UBBoardView* view, mPreviousViews)
{ {
delete view; delete view;
} }
delete mBlackScene; delete mBlackScene;
delete mMirror; delete mMirror;
if (mHttp) delete mHttp; if (mHttp) delete mHttp;
} }
void UBApplicationController::initViewState(int horizontalPosition, int verticalPostition) void UBApplicationController::initViewState(int horizontalPosition, int verticalPostition)
{ {
mInitialHScroll = horizontalPosition; mInitialHScroll = horizontalPosition;
mInitialVScroll = verticalPostition; mInitialVScroll = verticalPostition;
} }
void UBApplicationController::initScreenLayout(bool useMultiscreen) void UBApplicationController::initScreenLayout(bool useMultiscreen)
{ {
mDisplayManager->setControlWidget(mMainWindow); mDisplayManager->setControlWidget(mMainWindow);
mDisplayManager->setDisplayWidget(mDisplayView); mDisplayManager->setDisplayWidget(mDisplayView);
mDisplayManager->setPreviousDisplaysWidgets(mPreviousViews); mDisplayManager->setPreviousDisplaysWidgets(mPreviousViews);
mDisplayManager->setDesktopWidget(mUninoteController->drawingView()); mDisplayManager->setDesktopWidget(mUninoteController->drawingView());
mDisplayManager->setUseMultiScreen(useMultiscreen); mDisplayManager->setUseMultiScreen(useMultiscreen);
mDisplayManager->adjustScreens(-1); mDisplayManager->adjustScreens(-1);
} }
void UBApplicationController::screenLayoutChanged() void UBApplicationController::screenLayoutChanged()
{ {
initViewState(mControlView->horizontalScrollBar()->value(), initViewState(mControlView->horizontalScrollBar()->value(),
mControlView->verticalScrollBar()->value()); mControlView->verticalScrollBar()->value());
adaptToolBar(); adaptToolBar();
adjustDisplayView(); adjustDisplayView();
if (mDisplayManager->hasDisplay()) if (mDisplayManager->hasDisplay())
{ {
UBApplication::boardController->setBoxing(mDisplayView->geometry()); UBApplication::boardController->setBoxing(mDisplayView->geometry());
} }
else else
{ {
UBApplication::boardController->setBoxing(QRect()); UBApplication::boardController->setBoxing(QRect());
} }
adjustPreviousViews(0, 0); adjustPreviousViews(0, 0);
} }
void UBApplicationController::adaptToolBar() void UBApplicationController::adaptToolBar()
{ {
bool highResolution = mMainWindow->width() > 1024; bool highResolution = mMainWindow->width() > 1024;
mMainWindow->actionClearPage->setVisible(Board == mMainMode && highResolution); mMainWindow->actionClearPage->setVisible(Board == mMainMode && highResolution);
mMainWindow->actionBoard->setVisible(Board != mMainMode || highResolution); mMainWindow->actionBoard->setVisible(Board != mMainMode || highResolution);
mMainWindow->actionDocument->setVisible(Document != mMainMode || highResolution); mMainWindow->actionDocument->setVisible(Document != mMainMode || highResolution);
mMainWindow->actionWeb->setVisible(Internet != mMainMode || highResolution); mMainWindow->actionWeb->setVisible(Internet != mMainMode || highResolution);
mMainWindow->boardToolBar->setIconSize(QSize(highResolution ? 48 : 42, mMainWindow->boardToolBar->iconSize().height())); mMainWindow->boardToolBar->setIconSize(QSize(highResolution ? 48 : 42, mMainWindow->boardToolBar->iconSize().height()));
mMainWindow->actionBoard->setEnabled(mMainMode != Board); mMainWindow->actionBoard->setEnabled(mMainMode != Board);
mMainWindow->actionWeb->setEnabled(mMainMode != Internet); mMainWindow->actionWeb->setEnabled(mMainMode != Internet);
mMainWindow->actionDocument->setEnabled(mMainMode != Document); mMainWindow->actionDocument->setEnabled(mMainMode != Document);
if (Document == mMainMode) if (Document == mMainMode)
{ {
connect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *))); connect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *)));
} }
else else
{ {
disconnect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *))); disconnect(UBApplication::instance(), SIGNAL(focusChanged(QWidget *, QWidget *)), UBApplication::documentController, SLOT(focusChanged(QWidget *, QWidget *)));
if (Board == mMainMode) if (Board == mMainMode)
mMainWindow->actionDuplicate->setEnabled(true); mMainWindow->actionDuplicate->setEnabled(true);
} }
UBApplication::boardController->setToolbarTexts(); UBApplication::boardController->setToolbarTexts();
UBApplication::webController->adaptToolBar(); UBApplication::webController->adaptToolBar();
} }
void UBApplicationController::adjustDisplayView() void UBApplicationController::adjustDisplayView()
{ {
if (mDisplayView) if (mDisplayView)
{ {
qreal systemDisplayViewScaleFactor = 1.0; qreal systemDisplayViewScaleFactor = 1.0;
QSize pageSize = UBApplication::boardController->activeScene()->nominalSize(); QSize pageSize = UBApplication::boardController->activeScene()->nominalSize();
QSize displaySize = mDisplayView->size(); QSize displaySize = mDisplayView->size();
qreal hFactor = ((qreal)displaySize.width()) / ((qreal)pageSize.width()); qreal hFactor = ((qreal)displaySize.width()) / ((qreal)pageSize.width());
qreal vFactor = ((qreal)displaySize.height()) / ((qreal)pageSize.height()); qreal vFactor = ((qreal)displaySize.height()) / ((qreal)pageSize.height());
systemDisplayViewScaleFactor = qMin(hFactor, vFactor); systemDisplayViewScaleFactor = qMin(hFactor, vFactor);
QTransform tr; QTransform tr;
qreal scaleFactor = systemDisplayViewScaleFactor * UBApplication::boardController->currentZoom(); qreal scaleFactor = systemDisplayViewScaleFactor * UBApplication::boardController->currentZoom();
tr.scale(scaleFactor, scaleFactor); tr.scale(scaleFactor, scaleFactor);
QRect rect = mControlView->rect(); QRect rect = mControlView->rect();
QPoint center(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2); QPoint center(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2);
QTransform recentTransform = mDisplayView->transform(); QTransform recentTransform = mDisplayView->transform();
if (recentTransform != tr) if (recentTransform != tr)
mDisplayView->setTransform(tr); mDisplayView->setTransform(tr);
mDisplayView->centerOn(mControlView->mapToScene(center)); mDisplayView->centerOn(mControlView->mapToScene(center));
} }
} }
void UBApplicationController::adjustPreviousViews(int pActiveSceneIndex, UBDocumentProxy *pActiveDocument) void UBApplicationController::adjustPreviousViews(int pActiveSceneIndex, UBDocumentProxy *pActiveDocument)
{ {
int viewIndex = pActiveSceneIndex; int viewIndex = pActiveSceneIndex;
foreach(UBBoardView* previousView, mPreviousViews) foreach(UBBoardView* previousView, mPreviousViews)
{ {
if (viewIndex > 0) if (viewIndex > 0)
{ {
viewIndex--; viewIndex--;
UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pActiveDocument, viewIndex); UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pActiveDocument, viewIndex);
if (scene) if (scene)
{ {
previousView->setScene(scene); previousView->setScene(scene);
qreal ratio = ((qreal)previousView->geometry().width()) / ((qreal)previousView->geometry().height()); qreal ratio = ((qreal)previousView->geometry().width()) / ((qreal)previousView->geometry().height());
QRectF sceneRect = scene->normalizedSceneRect(ratio); QRectF sceneRect = scene->normalizedSceneRect(ratio);
qreal scaleRatio = previousView->geometry().width() / sceneRect.width(); qreal scaleRatio = previousView->geometry().width() / sceneRect.width();
previousView->resetTransform(); previousView->resetTransform();
previousView->scale(scaleRatio, scaleRatio); previousView->scale(scaleRatio, scaleRatio);
previousView->centerOn(sceneRect.center()); previousView->centerOn(sceneRect.center());
} }
} }
else else
{ {
previousView->setScene(mBlackScene); previousView->setScene(mBlackScene);
} }
} }
} }
void UBApplicationController::blackout() void UBApplicationController::blackout()
{ {
mDisplayManager->blackout(); mDisplayManager->blackout();
} }
void UBApplicationController::addCapturedPixmap(const QPixmap &pPixmap, bool pageMode, const QUrl& sourceUrl) void UBApplicationController::addCapturedPixmap(const QPixmap &pPixmap, bool pageMode, const QUrl& sourceUrl)
{ {
if (!pPixmap.isNull()) if (!pPixmap.isNull())
{ {
qreal sf = UBApplication::boardController->systemScaleFactor(); qreal sf = UBApplication::boardController->systemScaleFactor();
qreal scaledWidth = ((qreal)pPixmap.width()) / sf; qreal scaledWidth = ((qreal)pPixmap.width()) / sf;
qreal scaledHeight = ((qreal)pPixmap.height()) / sf; qreal scaledHeight = ((qreal)pPixmap.height()) / sf;
QSize pageNominalSize = UBApplication::boardController->activeScene()->nominalSize(); QSize pageNominalSize = UBApplication::boardController->activeScene()->nominalSize();
int newWidth = qMin((int)scaledWidth, pageNominalSize.width()); int newWidth = qMin((int)scaledWidth, pageNominalSize.width());
int newHeight = qMin((int)scaledHeight, pageNominalSize.height()); int newHeight = qMin((int)scaledHeight, pageNominalSize.height());
if (pageMode) if (pageMode)
{ {
newHeight = pPixmap.height(); newHeight = pPixmap.height();
} }
QSizeF scaledSize(scaledWidth, scaledHeight); QSizeF scaledSize(scaledWidth, scaledHeight);
scaledSize.scale(newWidth, newHeight, Qt::KeepAspectRatio); scaledSize.scale(newWidth, newHeight, Qt::KeepAspectRatio);
qreal scaleFactor = qMin(scaledSize.width() / (qreal)pPixmap.width(), scaledSize.height() / (qreal)pPixmap.height()); qreal scaleFactor = qMin(scaledSize.width() / (qreal)pPixmap.width(), scaledSize.height() / (qreal)pPixmap.height());
QPointF pos(0.0, 0.0); QPointF pos(0.0, 0.0);
if (pageMode) if (pageMode)
{ {
pos.setY(pageNominalSize.height() / -2 + scaledSize.height() / 2); pos.setY(pageNominalSize.height() / -2 + scaledSize.height() / 2);
} }
UBApplication::boardController->paletteManager()->addItem(pPixmap, pos, scaleFactor, sourceUrl); UBApplication::boardController->paletteManager()->addItem(pPixmap, pos, scaleFactor, sourceUrl);
} }
} }
void UBApplicationController::addCapturedEmbedCode(const QString& embedCode) void UBApplicationController::addCapturedEmbedCode(const QString& embedCode)
{ {
if (!embedCode.isEmpty()) if (!embedCode.isEmpty())
{ {
showBoard(); showBoard();
const QString userWidgetPath = UBSettings::settings()->userInteractiveDirectory() + "/" + tr("Web"); // TODO UB 4.x synch with w3cWidget const QString userWidgetPath = UBSettings::settings()->userInteractiveDirectory() + "/" + tr("Web"); // TODO UB 4.x synch with w3cWidget
QDir userWidgetDir(userWidgetPath); QDir userWidgetDir(userWidgetPath);
int width = 300; int width = 300;
int height = 150; int height = 150;
QString widgetPath = UBGraphicsW3CWidgetItem::createHtmlWrapperInDir(embedCode, userWidgetDir, QString widgetPath = UBGraphicsW3CWidgetItem::createHtmlWrapperInDir(embedCode, userWidgetDir,
QSize(width, height), UBStringUtils::toCanonicalUuid(QUuid::createUuid())); QSize(width, height), UBStringUtils::toCanonicalUuid(QUuid::createUuid()));
if (widgetPath.length() > 0) if (widgetPath.length() > 0)
UBApplication::boardController->downloadURL(QUrl::fromLocalFile(widgetPath)); UBApplication::boardController->downloadURL(QUrl::fromLocalFile(widgetPath));
} }
} }
void UBApplicationController::showBoard() void UBApplicationController::showBoard()
{ {
mMainWindow->webToolBar->hide(); mMainWindow->webToolBar->hide();
mMainWindow->documentToolBar->hide(); mMainWindow->documentToolBar->hide();
mMainWindow->tutorialToolBar->hide(); mMainWindow->tutorialToolBar->hide();
mMainWindow->boardToolBar->show(); mMainWindow->boardToolBar->show();
if (mMainMode == Document) if (mMainMode == Document)
{ {
int selectedSceneIndex = UBApplication::documentController->getSelectedItemIndex(); int selectedSceneIndex = UBApplication::documentController->getSelectedItemIndex();
if (selectedSceneIndex != -1) if (selectedSceneIndex != -1)
{ {
UBApplication::boardController->setActiveDocumentScene(UBApplication::documentController->selectedDocument(), selectedSceneIndex, true); UBApplication::boardController->setActiveDocumentScene(UBApplication::documentController->selectedDocument(), selectedSceneIndex, true);
} }
} }
mMainMode = Board; mMainMode = Board;
adaptToolBar(); adaptToolBar();
mirroringEnabled(false); mirroringEnabled(false);
mMainWindow->switchToBoardWidget(); mMainWindow->switchToBoardWidget();
if (UBApplication::boardController) if (UBApplication::boardController)
UBApplication::boardController->show(); UBApplication::boardController->show();
mIsShowingDesktop = false; mIsShowingDesktop = false;
UBPlatformUtils::setDesktopMode(false); UBPlatformUtils::setDesktopMode(false);
mUninoteController->hideWindow(); mUninoteController->hideWindow();
mMainWindow->show(); mMainWindow->show();
emit mainModeChanged(Board); emit mainModeChanged(Board);
UBApplication::boardController->freezeW3CWidgets(false); UBApplication::boardController->freezeW3CWidgets(false);
UBApplication::boardController->activeScene()->updateGroupButtonState(); UBApplication::boardController->activeScene()->updateGroupButtonState();
} }
void UBApplicationController::showInternet() void UBApplicationController::showInternet()
{ {
if (UBApplication::boardController) if (UBApplication::boardController)
{ {
UBApplication::boardController->persistCurrentScene(); UBApplication::boardController->persistCurrentScene();
UBApplication::boardController->hide(); UBApplication::boardController->hide();
} }
if (UBSettings::settings()->webUseExternalBrowser->get().toBool()) if (UBSettings::settings()->webUseExternalBrowser->get().toBool())
{ {
showDesktop(true); showDesktop(true);
UBApplication::webController->show(UBWebController::WebBrowser); UBApplication::webController->show(UBWebController::WebBrowser);
// really no have emit mainModeChanged here ? potential problem with virtual keyboard ? // really no have emit mainModeChanged here ? potential problem with virtual keyboard ?
} }
else else
{ {
mMainWindow->boardToolBar->hide(); mMainWindow->boardToolBar->hide();
mMainWindow->documentToolBar->hide(); mMainWindow->documentToolBar->hide();
mMainWindow->tutorialToolBar->hide(); mMainWindow->tutorialToolBar->hide();
mMainWindow->webToolBar->show(); mMainWindow->webToolBar->show();
mMainMode = Internet; mMainMode = Internet;
adaptToolBar(); adaptToolBar();
mMainWindow->show(); mMainWindow->show();
mUninoteController->hideWindow(); mUninoteController->hideWindow();
UBApplication::webController->show(UBWebController::WebBrowser); UBApplication::webController->show(UBWebController::WebBrowser);
emit mainModeChanged(Internet); emit mainModeChanged(Internet);
} }
} }
void UBApplicationController::showDocument() void UBApplicationController::showDocument()
{ {
mMainWindow->webToolBar->hide(); mMainWindow->webToolBar->hide();
mMainWindow->boardToolBar->hide(); mMainWindow->boardToolBar->hide();
mMainWindow->tutorialToolBar->hide(); mMainWindow->tutorialToolBar->hide();
mMainWindow->documentToolBar->show(); mMainWindow->documentToolBar->show();
mMainMode = Document; mMainMode = Document;
adaptToolBar(); adaptToolBar();
mirroringEnabled(false); mirroringEnabled(false);
mMainWindow->switchToDocumentsWidget(); mMainWindow->switchToDocumentsWidget();
if (UBApplication::boardController) if (UBApplication::boardController)
{ {
if (UBApplication::boardController->activeScene()->isModified() || (UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified())) if (UBApplication::boardController->activeScene()->isModified() || (UBApplication::boardController->paletteManager()->teacherGuideDockWidget() && UBApplication::boardController->paletteManager()->teacherGuideDockWidget()->teacherGuideWidget()->isModified()))
UBApplication::boardController->persistCurrentScene(); UBApplication::boardController->persistCurrentScene();
UBApplication::boardController->hide(); UBApplication::boardController->hide();
} }
if (UBApplication::documentController) if (UBApplication::documentController)
UBApplication::documentController->show(); UBApplication::documentController->show();
mMainWindow->show(); mMainWindow->show();
mUninoteController->hideWindow(); mUninoteController->hideWindow();
emit mainModeChanged(Document); emit mainModeChanged(Document);
} }
void UBApplicationController::showDesktop(bool dontSwitchFrontProcess) void UBApplicationController::showDesktop(bool dontSwitchFrontProcess)
{ {
int desktopWidgetIndex = qApp->desktop()->screenNumber(mMainWindow); int desktopWidgetIndex = qApp->desktop()->screenNumber(mMainWindow);
if (UBApplication::boardController) if (UBApplication::boardController)
UBApplication::boardController->hide(); UBApplication::boardController->hide();
mMainWindow->hide(); mMainWindow->hide();
mUninoteController->showWindow(); mUninoteController->showWindow();
if (mMirror) if (mMirror)
{ {
QRect rect = qApp->desktop()->screenGeometry(desktopWidgetIndex); QRect rect = qApp->desktop()->screenGeometry(desktopWidgetIndex);
mMirror->setSourceRect(rect); mMirror->setSourceRect(rect);
} }
mIsShowingDesktop = true; mIsShowingDesktop = true;
emit desktopMode(true); emit desktopMode(true);
if (!dontSwitchFrontProcess) { if (!dontSwitchFrontProcess) {
UBPlatformUtils::bringPreviousProcessToFront(); UBPlatformUtils::bringPreviousProcessToFront();
} }
UBDrawingController::drawingController()->setInDestopMode(true); UBDrawingController::drawingController()->setInDestopMode(true);
UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector); UBDrawingController::drawingController()->setStylusTool(UBStylusTool::Selector);
} }
void UBApplicationController::showTutorial() void UBApplicationController::showTutorial()
{ {
if (UBApplication::boardController) if (UBApplication::boardController)
{ {
UBApplication::boardController->persistCurrentScene(); UBApplication::boardController->persistCurrentScene();
UBApplication::boardController->hide(); UBApplication::boardController->hide();
} }
if (UBSettings::settings()->webUseExternalBrowser->get().toBool()) if (UBSettings::settings()->webUseExternalBrowser->get().toBool())
{ {
showDesktop(true); showDesktop(true);
UBApplication::webController->show(UBWebController::Tutorial); UBApplication::webController->show(UBWebController::Tutorial);
} }
else{ else{
mMainWindow->webToolBar->hide(); mMainWindow->webToolBar->hide();
mMainWindow->boardToolBar->hide(); mMainWindow->boardToolBar->hide();
mMainWindow->documentToolBar->hide(); mMainWindow->documentToolBar->hide();
mMainWindow->tutorialToolBar->show(); mMainWindow->tutorialToolBar->show();
mMainMode = Tutorial; mMainMode = Tutorial;
adaptToolBar(); adaptToolBar();
mUninoteController->hideWindow(); mUninoteController->hideWindow();
UBApplication::webController->show(UBWebController::Tutorial); UBApplication::webController->show(UBWebController::Tutorial);
mirroringEnabled(false); mirroringEnabled(false);
emit mainModeChanged(mMainMode); emit mainModeChanged(mMainMode);
} }
} }
void UBApplicationController::showSankoreEditor() void UBApplicationController::showSankoreEditor()
{ {
if (UBApplication::boardController) if (UBApplication::boardController)
{ {
UBApplication::boardController->persistCurrentScene(); UBApplication::boardController->persistCurrentScene();
UBApplication::boardController->hide(); UBApplication::boardController->hide();
} }
// it's needed not to duplicate webbrowser search in web mode. If I've breaked smbd's code let Ivan know // 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); UBApplication::webController->show(UBWebController::Paraschool);
mMainWindow->webToolBar->hide(); mMainWindow->webToolBar->hide();
mMainWindow->boardToolBar->hide(); mMainWindow->boardToolBar->hide();
mMainWindow->documentToolBar->hide(); mMainWindow->documentToolBar->hide();
mMainWindow->tutorialToolBar->show(); mMainWindow->tutorialToolBar->show();
mMainMode = ParaschoolEditor; mMainMode = ParaschoolEditor;
adaptToolBar(); adaptToolBar();
mUninoteController->hideWindow(); mUninoteController->hideWindow();
mirroringEnabled(false); mirroringEnabled(false);
emit mainModeChanged(mMainMode); emit mainModeChanged(mMainMode);
} }
void UBApplicationController::checkUpdate() void UBApplicationController::checkUpdate()
{ {
if(mHttp) if(mHttp)
delete mHttp; delete mHttp;
QUrl url("http://ftp.open-sankore.org/update.json"); QUrl url("http://ftp.open-sankore.org/update.json");
mHttp = new QHttp(url.host()); mHttp = new QHttp(url.host());
connect(mHttp, SIGNAL(requestFinished(int,bool)), this, SLOT(updateRequestFinished(int,bool))); connect(mHttp, SIGNAL(requestFinished(int,bool)), this, SLOT(updateRequestFinished(int,bool)));
mHttp->get(url.path()); mHttp->get(url.path());
} }
void UBApplicationController::updateRequestFinished(int id, bool error) void UBApplicationController::updateRequestFinished(int id, bool error)
{ {
if (error){ if (error){
qWarning() << "http command id" << id << "return the error: " << mHttp->errorString(); qWarning() << "http command id" << id << "return the error: " << mHttp->errorString();
mHttp->close(); mHttp->close();
} }
else{ else{
QString responseString = QString(mHttp->readAll()); QString responseString = QString(mHttp->readAll());
if (!responseString.isEmpty() && responseString.contains("version") && responseString.contains("url")){ if (!responseString.isEmpty() && responseString.contains("version") && responseString.contains("url")){
mHttp->close(); mHttp->close();
downloadJsonFinished(responseString); downloadJsonFinished(responseString);
} }
} }
} }
void UBApplicationController::downloadJsonFinished(QString currentJson) void UBApplicationController::downloadJsonFinished(QString currentJson)
{ {
QScriptValue scriptValue; QScriptValue scriptValue;
QScriptEngine scriptEngine; QScriptEngine scriptEngine;
scriptValue = scriptEngine.evaluate ("(" + currentJson + ")"); scriptValue = scriptEngine.evaluate ("(" + currentJson + ")");
UBVersion installedVersion (qApp->applicationVersion().left(4)); UBVersion installedVersion (qApp->applicationVersion().left(4));
UBVersion jsonVersion (scriptValue.property("version").toString().left(4)); UBVersion jsonVersion (scriptValue.property("version").toString().left(4));
if (installedVersion.isValid() && jsonVersion.isValid() && jsonVersion > installedVersion) { 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 ?"))){ if (UBApplication::mainWindow->yesNoQuestion(tr("Update available"), tr ("New update available, would you go to the web page ?"))){
QUrl url(scriptValue.property ("url").toString()); QUrl url(scriptValue.property ("url").toString());
QDesktopServices::openUrl (url); QDesktopServices::openUrl (url);
} }
} }
else { else {
if (isNoUpdateDisplayed) { if (isNoUpdateDisplayed) {
mMainWindow->information(tr("Update"), tr("No update available")); mMainWindow->information(tr("Update"), tr("No update available"));
} }
} }
} }
void UBApplicationController::checkUpdateAtLaunch() void UBApplicationController::checkUpdateAtLaunch()
{ {
if(UBSettings::settings()->appEnableAutomaticSoftwareUpdates->get().toBool()){ if(UBSettings::settings()->appEnableAutomaticSoftwareUpdates->get().toBool()){
isNoUpdateDisplayed = false; isNoUpdateDisplayed = false;
checkUpdate (); checkUpdate ();
} }
} }
void UBApplicationController::checkUpdateRequest() void UBApplicationController::checkUpdateRequest()
{ {
isNoUpdateDisplayed = true; isNoUpdateDisplayed = true;
checkUpdate (); checkUpdate ();
} }
void UBApplicationController::hideDesktop() void UBApplicationController::hideDesktop()
{ {
if (mMainMode == Board) if (mMainMode == Board)
{ {
showBoard(); showBoard();
} }
else if (mMainMode == Internet) else if (mMainMode == Internet)
{ {
showInternet(); showInternet();
} }
else if (mMainMode == Document) else if (mMainMode == Document)
{ {
showDocument(); showDocument();
} }
else if (mMainMode == Tutorial) else if (mMainMode == Tutorial)
{ {
showTutorial(); showTutorial();
} }
else if (mMainMode == ParaschoolEditor) else if (mMainMode == ParaschoolEditor)
{ {
showSankoreEditor(); showSankoreEditor();
} }
mIsShowingDesktop = false; mIsShowingDesktop = false;
mDisplayManager->adjustScreens(-1); mDisplayManager->adjustScreens(-1);
emit desktopMode(false); emit desktopMode(false);
} }
void UBApplicationController::setMirrorSourceWidget(QWidget* pWidget) void UBApplicationController::setMirrorSourceWidget(QWidget* pWidget)
{ {
if (mMirror) if (mMirror)
{ {
mMirror->setSourceWidget(pWidget); mMirror->setSourceWidget(pWidget);
} }
} }
void UBApplicationController::mirroringEnabled(bool enabled) void UBApplicationController::mirroringEnabled(bool enabled)
{ {
if (mMirror) if (mMirror)
{ {
if (enabled) if (enabled)
{ {
mMirror->start(); mMirror->start();
mDisplayManager->setDisplayWidget(mMirror); mDisplayManager->setDisplayWidget(mMirror);
} }
else else
{ {
mDisplayManager->setDisplayWidget(mDisplayView); mDisplayManager->setDisplayWidget(mDisplayView);
mMirror->stop(); mMirror->stop();
} }
mMirror->setVisible(enabled && mDisplayManager->numScreens() > 1); mMirror->setVisible(enabled && mDisplayManager->numScreens() > 1);
mUninoteController->updateShowHideState(enabled); mUninoteController->updateShowHideState(enabled);
UBApplication::mainWindow->actionWebShowHideOnDisplay->setChecked(enabled); UBApplication::mainWindow->actionWebShowHideOnDisplay->setChecked(enabled);
} }
else else
{ {
mDisplayManager->setDisplayWidget(mDisplayView); mDisplayManager->setDisplayWidget(mDisplayView);
} }
} }
void UBApplicationController::closing() void UBApplicationController::closing()
{ {
if (mMirror) if (mMirror)
mMirror->stop(); mMirror->stop();
if (mUninoteController) if (mUninoteController)
{ {
mUninoteController->hideWindow(); mUninoteController->hideWindow();
mUninoteController->close(); mUninoteController->close();
} }
if (UBApplication::documentController) if (UBApplication::documentController)
UBApplication::documentController->closing(); UBApplication::documentController->closing();
} }
void UBApplicationController::showMessage(const QString& message, bool showSpinningWheel) void UBApplicationController::showMessage(const QString& message, bool showSpinningWheel)
{ {
if (!UBApplication::closingDown()) if (!UBApplication::closingDown())
{ {
if (mMainMode == Document) if (mMainMode == Document)
{ {
UBApplication::boardController->hideMessage(); UBApplication::boardController->hideMessage();
UBApplication::documentController->showMessage(message, showSpinningWheel); UBApplication::documentController->showMessage(message, showSpinningWheel);
} }
else else
{ {
UBApplication::documentController->hideMessage(); UBApplication::documentController->hideMessage();
UBApplication::boardController->showMessage(message, showSpinningWheel); UBApplication::boardController->showMessage(message, showSpinningWheel);
} }
} }
} }
void UBApplicationController::importFile(const QString& pFilePath) void UBApplicationController::importFile(const QString& pFilePath)
{ {
const QFile fileToOpen(pFilePath); const QFile fileToOpen(pFilePath);
if (!fileToOpen.exists()) if (!fileToOpen.exists())
return; return;
UBDocumentProxy* document = 0; UBDocumentProxy* document = 0;
bool success = false; bool success = false;
document = UBDocumentManager::documentManager()->importFile(fileToOpen, ""); document = UBDocumentManager::documentManager()->importFile(fileToOpen, "");
success = (document != 0); success = (document != 0);
if (success && document) if (success && document)
{ {
if (mMainMode == Board || mMainMode == Internet) if (mMainMode == Board || mMainMode == Internet)
{ {
if (UBApplication::boardController) if (UBApplication::boardController)
{ {
UBApplication::boardController->setActiveDocumentScene(document, 0); UBApplication::boardController->setActiveDocumentScene(document, 0);
showBoard(); showBoard();
} }
} }
else if (mMainMode == Document) else if (mMainMode == Document)
{ {
if (UBApplication::documentController) if (UBApplication::documentController)
UBApplication::documentController->selectDocument(document); UBApplication::documentController->selectDocument(document);
} }
} }
} }
void UBApplicationController::useMultiScreen(bool use) void UBApplicationController::useMultiScreen(bool use)
{ {
mDisplayManager->setUseMultiScreen(use); mDisplayManager->setUseMultiScreen(use);
mDisplayManager->adjustScreens(0); mDisplayManager->adjustScreens(0);
UBSettings::settings()->appUseMultiscreen->set(use); UBSettings::settings()->appUseMultiscreen->set(use);
} }
QStringList UBApplicationController::widgetInlineJavaScripts() QStringList UBApplicationController::widgetInlineJavaScripts()
{ {
QString scriptDirPath = UBPlatformUtils::applicationResourcesDirectory() + "/widget-inline-js"; QString scriptDirPath = UBPlatformUtils::applicationResourcesDirectory() + "/widget-inline-js";
QDir scriptDir(scriptDirPath); QDir scriptDir(scriptDirPath);
QStringList scripts; QStringList scripts;
if (scriptDir.exists()) if (scriptDir.exists())
{ {
QStringList files = scriptDir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); QStringList files = scriptDir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
foreach(QString file, files) foreach(QString file, files)
{ {
QFile scriptFile(scriptDirPath + "/" + file); QFile scriptFile(scriptDirPath + "/" + file);
if (file.endsWith(".js") && scriptFile.open(QIODevice::ReadOnly)) if (file.endsWith(".js") && scriptFile.open(QIODevice::ReadOnly))
{ {
QString s = QString::fromUtf8(scriptFile.readAll()); QString s = QString::fromUtf8(scriptFile.readAll());
if (s.length() > 0) if (s.length() > 0)
scripts << s; scripts << s;
} }
} }
} }
qSort(scripts); qSort(scripts);
return scripts; return scripts;
} }
void UBApplicationController::actionCut() void UBApplicationController::actionCut()
{ {
if (!UBApplication::closingDown()) if (!UBApplication::closingDown())
{ {
if (mMainMode == Board) if (mMainMode == Board)
{ {
UBApplication::boardController->cut(); UBApplication::boardController->cut();
} }
else if(mMainMode == Document) else if(mMainMode == Document)
{ {
UBApplication::documentController->cut(); UBApplication::documentController->cut();
} }
else if(mMainMode == Internet) else if(mMainMode == Internet)
{ {
UBApplication::webController->cut(); UBApplication::webController->cut();
} }
} }
} }
void UBApplicationController::actionCopy() void UBApplicationController::actionCopy()
{ {
if (!UBApplication::closingDown()) if (!UBApplication::closingDown())
{ {
if (mMainMode == Board) if (mMainMode == Board)
{ {
UBApplication::boardController->copy(); UBApplication::boardController->copy();
} }
else if(mMainMode == Document) else if(mMainMode == Document)
{ {
UBApplication::documentController->copy(); UBApplication::documentController->copy();
} }
else if(mMainMode == Internet) else if(mMainMode == Internet)
{ {
UBApplication::webController->copy(); UBApplication::webController->copy();
} }
} }
} }
void UBApplicationController::actionPaste() void UBApplicationController::actionPaste()
{ {
if (!UBApplication::closingDown()) if (!UBApplication::closingDown())
{ {
if (mMainMode == Board) if (mMainMode == Board)
{ {
UBApplication::boardController->paste(); UBApplication::boardController->paste();
} }
else if (mMainMode == Document) else if (mMainMode == Document)
{ {
UBApplication::documentController->paste(); UBApplication::documentController->paste();
} }
else if(mMainMode == Internet) else if(mMainMode == Internet)
{ {
UBApplication::webController->paste(); UBApplication::webController->paste();
} }
} }
} }
...@@ -21,297 +21,297 @@ ...@@ -21,297 +21,297 @@
#include "UBDocumentManager.h" #include "UBDocumentManager.h"
#include "frameworks/UBStringUtils.h" #include "frameworks/UBStringUtils.h"
#include "adaptors/UBExportFullPDF.h" #include "adaptors/UBExportFullPDF.h"
#include "adaptors/UBExportDocument.h" #include "adaptors/UBExportDocument.h"
#include "adaptors/UBExportWeb.h" #include "adaptors/UBExportWeb.h"
#include "adaptors/UBExportCFF.h" #include "adaptors/UBExportCFF.h"
#include "adaptors/UBWebPublisher.h" #include "adaptors/UBWebPublisher.h"
#include "adaptors/UBImportDocument.h" #include "adaptors/UBImportDocument.h"
#include "adaptors/UBImportPDF.h" #include "adaptors/UBImportPDF.h"
#include "adaptors/UBImportImage.h" #include "adaptors/UBImportImage.h"
#include "adaptors/UBImportCFF.h" #include "adaptors/UBImportCFF.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "domain/UBGraphicsSvgItem.h" #include "domain/UBGraphicsSvgItem.h"
#include "domain/UBGraphicsPixmapItem.h" #include "domain/UBGraphicsPixmapItem.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "UBApplication.h" #include "UBApplication.h"
#include "UBSettings.h" #include "UBSettings.h"
#include "UBPersistenceManager.h" #include "UBPersistenceManager.h"
#include "../adaptors/UBExportWeb.h" #include "../adaptors/UBExportWeb.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentManager* UBDocumentManager::sDocumentManager = 0; UBDocumentManager* UBDocumentManager::sDocumentManager = 0;
UBDocumentManager* UBDocumentManager::documentManager() UBDocumentManager* UBDocumentManager::documentManager()
{ {
if (!sDocumentManager) if (!sDocumentManager)
{ {
sDocumentManager = new UBDocumentManager(qApp); sDocumentManager = new UBDocumentManager(qApp);
} }
return sDocumentManager; return sDocumentManager;
} }
UBDocumentManager::UBDocumentManager(QObject *parent) UBDocumentManager::UBDocumentManager(QObject *parent)
:QObject(parent) :QObject(parent)
{ {
// TODO UB 4.7 string used in document persistence (folder names) // TODO UB 4.7 string used in document persistence (folder names)
QString dummyImages = tr("images"); QString dummyImages = tr("images");
QString dummyVideos = tr("videos"); QString dummyVideos = tr("videos");
QString dummyObjects = tr("objects"); QString dummyObjects = tr("objects");
QString dummyWidgets = tr("widgets"); QString dummyWidgets = tr("widgets");
UBExportCFF* cffExporter = new UBExportCFF(this); UBExportCFF* cffExporter = new UBExportCFF(this);
UBExportFullPDF* exportFullPdf = new UBExportFullPDF(this); UBExportFullPDF* exportFullPdf = new UBExportFullPDF(this);
UBExportDocument* exportDocument = new UBExportDocument(this); UBExportDocument* exportDocument = new UBExportDocument(this);
UBWebPublisher* webPublished = new UBWebPublisher(this); UBWebPublisher* webPublished = new UBWebPublisher(this);
mExportAdaptors.append(exportDocument); mExportAdaptors.append(exportDocument);
mExportAdaptors.append(webPublished); mExportAdaptors.append(webPublished);
mExportAdaptors.append(exportFullPdf); mExportAdaptors.append(exportFullPdf);
mExportAdaptors.append(cffExporter); mExportAdaptors.append(cffExporter);
// UBExportWeb* exportWeb = new UBExportWeb(this); // UBExportWeb* exportWeb = new UBExportWeb(this);
// mExportAdaptors.append(exportWeb); // mExportAdaptors.append(exportWeb);
UBImportDocument* documentImport = new UBImportDocument(this); UBImportDocument* documentImport = new UBImportDocument(this);
mImportAdaptors.append(documentImport); mImportAdaptors.append(documentImport);
UBImportPDF* pdfImport = new UBImportPDF(this); UBImportPDF* pdfImport = new UBImportPDF(this);
mImportAdaptors.append(pdfImport); mImportAdaptors.append(pdfImport);
UBImportImage* imageImport = new UBImportImage(this); UBImportImage* imageImport = new UBImportImage(this);
mImportAdaptors.append(imageImport); mImportAdaptors.append(imageImport);
UBImportCFF* cffImport = new UBImportCFF(this); UBImportCFF* cffImport = new UBImportCFF(this);
mImportAdaptors.append(cffImport); mImportAdaptors.append(cffImport);
} }
UBDocumentManager::~UBDocumentManager() UBDocumentManager::~UBDocumentManager()
{ {
// NOOP // NOOP
} }
QStringList UBDocumentManager::importFileExtensions() QStringList UBDocumentManager::importFileExtensions()
{ {
QStringList result; QStringList result;
foreach (UBImportAdaptor *importAdaptor, mImportAdaptors) foreach (UBImportAdaptor *importAdaptor, mImportAdaptors)
{ {
result << importAdaptor->supportedExtentions(); result << importAdaptor->supportedExtentions();
} }
return result; return result;
} }
QString UBDocumentManager::importFileFilter() QString UBDocumentManager::importFileFilter()
{ {
QString result; QString result;
result += tr("All supported files (*.%1)").arg(importFileExtensions().join(" *.")); result += tr("All supported files (*.%1)").arg(importFileExtensions().join(" *."));
foreach (UBImportAdaptor *importAdaptor, mImportAdaptors) foreach (UBImportAdaptor *importAdaptor, mImportAdaptors)
{ {
if (importAdaptor->importFileFilter().length() > 0) if (importAdaptor->importFileFilter().length() > 0)
{ {
if (result.length()) if (result.length())
{ {
result += ";;"; result += ";;";
} }
result += importAdaptor->importFileFilter(); result += importAdaptor->importFileFilter();
} }
} }
qDebug() << "import file filter" << result; qDebug() << "import file filter" << result;
return result; return result;
} }
UBDocumentProxy* UBDocumentManager::importFile(const QFile& pFile, const QString& pGroup) UBDocumentProxy* UBDocumentManager::importFile(const QFile& pFile, const QString& pGroup)
{ {
QFileInfo fileInfo(pFile); QFileInfo fileInfo(pFile);
foreach (UBImportAdaptor *adaptor, mImportAdaptors) foreach (UBImportAdaptor *adaptor, mImportAdaptors)
{ {
if (adaptor->supportedExtentions().lastIndexOf(fileInfo.suffix().toLower()) != -1) if (adaptor->supportedExtentions().lastIndexOf(fileInfo.suffix().toLower()) != -1)
{ {
UBDocumentProxy* document; UBDocumentProxy* document;
UBApplication::setDisabled(true); UBApplication::setDisabled(true);
if (adaptor->isDocumentBased()) if (adaptor->isDocumentBased())
{ {
UBDocumentBasedImportAdaptor* importAdaptor = (UBDocumentBasedImportAdaptor*)adaptor; UBDocumentBasedImportAdaptor* importAdaptor = (UBDocumentBasedImportAdaptor*)adaptor;
document = importAdaptor->importFile(pFile, pGroup); document = importAdaptor->importFile(pFile, pGroup);
} }
else else
{ {
UBPageBasedImportAdaptor* importAdaptor = (UBPageBasedImportAdaptor*)adaptor; UBPageBasedImportAdaptor* importAdaptor = (UBPageBasedImportAdaptor*)adaptor;
// Document import procedure..... // Document import procedure.....
QString documentName = QFileInfo(pFile.fileName()).completeBaseName(); QString documentName = QFileInfo(pFile.fileName()).completeBaseName();
document = UBPersistenceManager::persistenceManager()->createDocument(pGroup, documentName); document = UBPersistenceManager::persistenceManager()->createDocument(pGroup, documentName);
QUuid uuid = QUuid::createUuid(); QUuid uuid = QUuid::createUuid();
QString filepath = pFile.fileName(); QString filepath = pFile.fileName();
if (importAdaptor->folderToCopy() != "") if (importAdaptor->folderToCopy() != "")
{ {
bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(document, pFile.fileName(), importAdaptor->folderToCopy() , uuid, filepath); bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(document, pFile.fileName(), importAdaptor->folderToCopy() , uuid, filepath);
if (!b) if (!b)
{ {
UBPersistenceManager::persistenceManager()->deleteDocument(document); UBPersistenceManager::persistenceManager()->deleteDocument(document);
UBApplication::setDisabled(false); UBApplication::setDisabled(false);
return NULL; return NULL;
} }
} }
QList<UBGraphicsItem*> pages = importAdaptor->import(uuid, filepath); QList<UBGraphicsItem*> pages = importAdaptor->import(uuid, filepath);
int nPage = 0; int nPage = 0;
foreach(UBGraphicsItem* page, pages) foreach(UBGraphicsItem* page, pages)
{ {
UBApplication::showMessage(tr("Inserting page %1 of %2").arg(++nPage).arg(pages.size()), true); UBApplication::showMessage(tr("Inserting page %1 of %2").arg(++nPage).arg(pages.size()), true);
#ifdef Q_WS_MACX #ifdef Q_WS_MACX
//Workaround for issue 912 //Workaround for issue 912
QApplication::processEvents(); QApplication::processEvents();
#endif #endif
int pageIndex = document->pageCount(); int pageIndex = document->pageCount();
UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(document, pageIndex); UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(document, pageIndex);
importAdaptor->placeImportedItemToScene(scene, page); importAdaptor->placeImportedItemToScene(scene, page);
UBPersistenceManager::persistenceManager()->persistDocumentScene(document, scene, pageIndex); UBPersistenceManager::persistenceManager()->persistDocumentScene(document, scene, pageIndex);
} }
UBPersistenceManager::persistenceManager()->persistDocumentMetadata(document); UBPersistenceManager::persistenceManager()->persistDocumentMetadata(document);
UBApplication::showMessage(tr("Import successful.")); UBApplication::showMessage(tr("Import successful."));
} }
UBApplication::setDisabled(false); UBApplication::setDisabled(false);
return document; return document;
} }
} }
return NULL; return NULL;
} }
int UBDocumentManager::addFilesToDocument(UBDocumentProxy* document, QStringList fileNames) int UBDocumentManager::addFilesToDocument(UBDocumentProxy* document, QStringList fileNames)
{ {
int nImportedDocuments = 0; int nImportedDocuments = 0;
foreach(const QString& fileName, fileNames) foreach(const QString& fileName, fileNames)
{ {
UBApplication::showMessage(tr("Importing file %1").arg(fileName)); UBApplication::showMessage(tr("Importing file %1").arg(fileName));
QFile file(fileName); QFile file(fileName);
QFileInfo fileInfo(file); QFileInfo fileInfo(file);
foreach (UBImportAdaptor *adaptor, mImportAdaptors) foreach (UBImportAdaptor *adaptor, mImportAdaptors)
{ {
if (adaptor->supportedExtentions().lastIndexOf(fileInfo.suffix().toLower()) != -1) if (adaptor->supportedExtentions().lastIndexOf(fileInfo.suffix().toLower()) != -1)
{ {
UBApplication::setDisabled(true); UBApplication::setDisabled(true);
if (adaptor->isDocumentBased()) if (adaptor->isDocumentBased())
{ {
UBDocumentBasedImportAdaptor* importAdaptor = (UBDocumentBasedImportAdaptor*)adaptor; UBDocumentBasedImportAdaptor* importAdaptor = (UBDocumentBasedImportAdaptor*)adaptor;
if (importAdaptor->addFileToDocument(document, file)) if (importAdaptor->addFileToDocument(document, file))
nImportedDocuments++; nImportedDocuments++;
} }
else else
{ {
UBPageBasedImportAdaptor* importAdaptor = (UBPageBasedImportAdaptor*)adaptor; UBPageBasedImportAdaptor* importAdaptor = (UBPageBasedImportAdaptor*)adaptor;
QUuid uuid = QUuid::createUuid(); QUuid uuid = QUuid::createUuid();
QString filepath = file.fileName(); QString filepath = file.fileName();
if (importAdaptor->folderToCopy() != "") if (importAdaptor->folderToCopy() != "")
{ {
bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(document, file.fileName(), importAdaptor->folderToCopy() , uuid, filepath); bool b = UBPersistenceManager::persistenceManager()->addFileToDocument(document, file.fileName(), importAdaptor->folderToCopy() , uuid, filepath);
if (!b) if (!b)
{ {
continue; continue;
} }
} }
QList<UBGraphicsItem*> pages = importAdaptor->import(uuid, filepath); QList<UBGraphicsItem*> pages = importAdaptor->import(uuid, filepath);
int nPage = 0; int nPage = 0;
foreach(UBGraphicsItem* page, pages) foreach(UBGraphicsItem* page, pages)
{ {
UBApplication::showMessage(tr("Inserting page %1 of %2").arg(++nPage).arg(pages.size()), true); UBApplication::showMessage(tr("Inserting page %1 of %2").arg(++nPage).arg(pages.size()), true);
int pageIndex = document->pageCount(); int pageIndex = document->pageCount();
UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(document, pageIndex); UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->createDocumentSceneAt(document, pageIndex);
importAdaptor->placeImportedItemToScene(scene, page); importAdaptor->placeImportedItemToScene(scene, page);
UBPersistenceManager::persistenceManager()->persistDocumentScene(document, scene, pageIndex); UBPersistenceManager::persistenceManager()->persistDocumentScene(document, scene, pageIndex);
UBApplication::boardController->addEmptyThumbPage(); UBApplication::boardController->addEmptyThumbPage();
} }
UBPersistenceManager::persistenceManager()->persistDocumentMetadata(document); UBPersistenceManager::persistenceManager()->persistDocumentMetadata(document);
UBApplication::showMessage(tr("Import of file %1 successful.").arg(file.fileName())); UBApplication::showMessage(tr("Import of file %1 successful.").arg(file.fileName()));
nImportedDocuments++; nImportedDocuments++;
} }
UBApplication::setDisabled(false); UBApplication::setDisabled(false);
} }
} }
} }
return nImportedDocuments; return nImportedDocuments;
} }
int UBDocumentManager::addImageDirToDocument(const QDir& pDir, UBDocumentProxy* pDocument) int UBDocumentManager::addImageDirToDocument(const QDir& pDir, UBDocumentProxy* pDocument)
{ {
QStringList filenames = pDir.entryList(QDir::Files | QDir::NoDotAndDotDot); QStringList filenames = pDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
filenames = UBStringUtils::sortByLastDigit(filenames); filenames = UBStringUtils::sortByLastDigit(filenames);
QStringList fileNames; QStringList fileNames;
foreach(QString f, filenames) foreach(QString f, filenames)
{ {
fileNames << pDir.absolutePath() + "/" + f; fileNames << pDir.absolutePath() + "/" + f;
} }
return addFilesToDocument(pDocument, fileNames); return addFilesToDocument(pDocument, fileNames);
} }
UBDocumentProxy* UBDocumentManager::importDir(const QDir& pDir, const QString& pGroup) UBDocumentProxy* UBDocumentManager::importDir(const QDir& pDir, const QString& pGroup)
{ {
UBDocumentProxy* doc = UBPersistenceManager::persistenceManager()->createDocument(pGroup, pDir.dirName()); UBDocumentProxy* doc = UBPersistenceManager::persistenceManager()->createDocument(pGroup, pDir.dirName());
int result = addImageDirToDocument(pDir, doc); int result = addImageDirToDocument(pDir, doc);
if (result > 0) if (result > 0)
{ {
doc->setMetaData(UBSettings::documentGroupName, pGroup); doc->setMetaData(UBSettings::documentGroupName, pGroup);
doc->setMetaData(UBSettings::documentName, pDir.dirName()); doc->setMetaData(UBSettings::documentName, pDir.dirName());
UBPersistenceManager::persistenceManager()->persistDocumentMetadata(doc); UBPersistenceManager::persistenceManager()->persistDocumentMetadata(doc);
UBApplication::showMessage(tr("File %1 saved").arg(pDir.dirName())); UBApplication::showMessage(tr("File %1 saved").arg(pDir.dirName()));
} }
else else
{ {
UBPersistenceManager::persistenceManager()->deleteDocument(doc); UBPersistenceManager::persistenceManager()->deleteDocument(doc);
} }
return doc; return doc;
} }
QList<UBExportAdaptor*> UBDocumentManager::supportedExportAdaptors() QList<UBExportAdaptor*> UBDocumentManager::supportedExportAdaptors()
{ {
return mExportAdaptors; return mExportAdaptors;
} }
void UBDocumentManager::emitDocumentUpdated(UBDocumentProxy* pDocument) void UBDocumentManager::emitDocumentUpdated(UBDocumentProxy* pDocument)
{ {
emit documentUpdated(pDocument); emit documentUpdated(pDocument);
} }
...@@ -28,22 +28,22 @@ ...@@ -28,22 +28,22 @@
UBWindowCapture::UBWindowCapture(UBDesktopAnnotationController *parent) UBWindowCapture::UBWindowCapture(UBDesktopAnnotationController *parent)
: QObject(parent) : QObject(parent)
, mParent(parent) , mParent(parent)
{ {
// NOOP // NOOP
} }
UBWindowCapture::~UBWindowCapture() UBWindowCapture::~UBWindowCapture()
{ {
// NOOP // NOOP
} }
const QPixmap UBWindowCapture::getCapturedWindow() const QPixmap UBWindowCapture::getCapturedWindow()
{ {
return mWindowPixmap; return mWindowPixmap;
} }
...@@ -51,20 +51,20 @@ int UBWindowCapture::execute() ...@@ -51,20 +51,20 @@ int UBWindowCapture::execute()
{ {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *path = [NSString pathWithComponents: [NSArray arrayWithObjects: NSTemporaryDirectory(), NSString *path = [NSString pathWithComponents: [NSArray arrayWithObjects: NSTemporaryDirectory(),
[[NSString stringWithFormat:@"%d",[NSDate timeIntervalSinceReferenceDate]] stringByAppendingPathExtension:@"uninote"], [[NSString stringWithFormat:@"%d",[NSDate timeIntervalSinceReferenceDate]] stringByAppendingPathExtension:@"uninote"],
nil]]; nil]];
NSTask *task = [[NSTask alloc] init]; NSTask *task = [[NSTask alloc] init];
NSArray *arguments = [NSArray arrayWithObjects: @"-i", @"-W", @"-m", @"-tpng", path, nil]; NSArray *arguments = [NSArray arrayWithObjects: @"-i", @"-W", @"-m", @"-tpng", path, nil];
[task setLaunchPath: @"/usr/sbin/screencapture"]; [task setLaunchPath: @"/usr/sbin/screencapture"];
[task setArguments: arguments]; [task setArguments: arguments];
[task launch]; [task launch];
[task waitUntilExit]; [task waitUntilExit];
[task release]; [task release];
QString resultPath = QString::fromUtf8([path UTF8String], strlen([path UTF8String])); QString resultPath = QString::fromUtf8([path UTF8String], strlen([path UTF8String]));
mWindowPixmap.load(resultPath); mWindowPixmap.load(resultPath);
QFile::remove(resultPath); QFile::remove(resultPath);
......
...@@ -19,128 +19,128 @@ ...@@ -19,128 +19,128 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBDocumentContainer.h" #include "UBDocumentContainer.h"
#include "adaptors/UBThumbnailAdaptor.h" #include "adaptors/UBThumbnailAdaptor.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentContainer::UBDocumentContainer(QObject * parent) UBDocumentContainer::UBDocumentContainer(QObject * parent)
:QObject(parent) :QObject(parent)
,mCurrentDocument(NULL) ,mCurrentDocument(NULL)
{} {}
UBDocumentContainer::~UBDocumentContainer() UBDocumentContainer::~UBDocumentContainer()
{ {
foreach(const QPixmap* pm, mDocumentThumbs){ foreach(const QPixmap* pm, mDocumentThumbs){
delete pm; delete pm;
pm = NULL; pm = NULL;
} }
} }
void UBDocumentContainer::setDocument(UBDocumentProxy* document, bool forceReload) void UBDocumentContainer::setDocument(UBDocumentProxy* document, bool forceReload)
{ {
if (mCurrentDocument != document || forceReload) if (mCurrentDocument != document || forceReload)
{ {
mCurrentDocument = document; mCurrentDocument = document;
reloadThumbnails(); reloadThumbnails();
emit documentSet(mCurrentDocument); emit documentSet(mCurrentDocument);
} }
} }
void UBDocumentContainer::duplicatePages(QList<int>& pageIndexes) void UBDocumentContainer::duplicatePages(QList<int>& pageIndexes)
{ {
int offset = 0; int offset = 0;
foreach(int sceneIndex, pageIndexes) foreach(int sceneIndex, pageIndexes)
{ {
UBPersistenceManager::persistenceManager()->duplicateDocumentScene(mCurrentDocument, sceneIndex + offset); UBPersistenceManager::persistenceManager()->duplicateDocumentScene(mCurrentDocument, sceneIndex + offset);
offset++; offset++;
} }
} }
bool UBDocumentContainer::movePageToIndex(int source, int target) bool UBDocumentContainer::movePageToIndex(int source, int target)
{ {
if (source==0) if (source==0)
{ {
// Title page - cant be moved // Title page - cant be moved
return false; return false;
} }
UBPersistenceManager::persistenceManager()->moveSceneToIndex(mCurrentDocument, source, target); UBPersistenceManager::persistenceManager()->moveSceneToIndex(mCurrentDocument, source, target);
deleteThumbPage(source); deleteThumbPage(source);
insertThumbPage(target); insertThumbPage(target);
emit documentThumbnailsUpdated(this); emit documentThumbnailsUpdated(this);
return true; return true;
} }
void UBDocumentContainer::deletePages(QList<int>& pageIndexes) void UBDocumentContainer::deletePages(QList<int>& pageIndexes)
{ {
UBPersistenceManager::persistenceManager()->deleteDocumentScenes(mCurrentDocument, pageIndexes); UBPersistenceManager::persistenceManager()->deleteDocumentScenes(mCurrentDocument, pageIndexes);
int offset = 0; int offset = 0;
foreach(int index, pageIndexes) foreach(int index, pageIndexes)
{ {
deleteThumbPage(index - offset); deleteThumbPage(index - offset);
offset++; offset++;
} }
emit documentThumbnailsUpdated(this); emit documentThumbnailsUpdated(this);
} }
void UBDocumentContainer::addPage(int index) void UBDocumentContainer::addPage(int index)
{ {
UBPersistenceManager::persistenceManager()->createDocumentSceneAt(mCurrentDocument, index); UBPersistenceManager::persistenceManager()->createDocumentSceneAt(mCurrentDocument, index);
insertThumbPage(index); insertThumbPage(index);
emit documentThumbnailsUpdated(this); emit documentThumbnailsUpdated(this);
} }
void UBDocumentContainer::updatePage(int index) void UBDocumentContainer::updatePage(int index)
{ {
updateThumbPage(index); updateThumbPage(index);
emit documentThumbnailsUpdated(this); emit documentThumbnailsUpdated(this);
} }
void UBDocumentContainer::deleteThumbPage(int index) void UBDocumentContainer::deleteThumbPage(int index)
{ {
mDocumentThumbs.removeAt(index); mDocumentThumbs.removeAt(index);
} }
void UBDocumentContainer::updateThumbPage(int index) void UBDocumentContainer::updateThumbPage(int index)
{ {
mDocumentThumbs[index] = UBThumbnailAdaptor::get(mCurrentDocument, index); mDocumentThumbs[index] = UBThumbnailAdaptor::get(mCurrentDocument, index);
emit documentPageUpdated(index); emit documentPageUpdated(index);
} }
void UBDocumentContainer::insertThumbPage(int index) void UBDocumentContainer::insertThumbPage(int index)
{ {
mDocumentThumbs.insert(index, UBThumbnailAdaptor::get(mCurrentDocument, index)); mDocumentThumbs.insert(index, UBThumbnailAdaptor::get(mCurrentDocument, index));
} }
void UBDocumentContainer::reloadThumbnails() void UBDocumentContainer::reloadThumbnails()
{ {
if (mCurrentDocument) if (mCurrentDocument)
{ {
UBThumbnailAdaptor::load(mCurrentDocument, mDocumentThumbs); UBThumbnailAdaptor::load(mCurrentDocument, mDocumentThumbs);
qDebug() << "Reloading Thumbnails. new mDocumentThumbs size: " << mDocumentThumbs.size(); qDebug() << "Reloading Thumbnails. new mDocumentThumbs size: " << mDocumentThumbs.size();
emit documentThumbnailsUpdated(this); emit documentThumbnailsUpdated(this);
} }
} }
int UBDocumentContainer::pageFromSceneIndex(int sceneIndex) int UBDocumentContainer::pageFromSceneIndex(int sceneIndex)
{ {
if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()) if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool())
return sceneIndex; return sceneIndex;
return sceneIndex+1; return sceneIndex+1;
} }
int UBDocumentContainer::sceneIndexFromPage(int page) int UBDocumentContainer::sceneIndexFromPage(int page)
{ {
if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()) if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool())
return page; return page;
return page-1; return page-1;
} }
void UBDocumentContainer::addEmptyThumbPage() void UBDocumentContainer::addEmptyThumbPage()
{ {
const QPixmap* pThumb = new QPixmap(); const QPixmap* pThumb = new QPixmap();
mDocumentThumbs.append(pThumb); mDocumentThumbs.append(pThumb);
} }
...@@ -19,54 +19,54 @@ ...@@ -19,54 +19,54 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBDOCUMENTCONTAINER_H_ #ifndef UBDOCUMENTCONTAINER_H_
#define UBDOCUMENTCONTAINER_H_ #define UBDOCUMENTCONTAINER_H_
#include <QtGui> #include <QtGui>
#include "UBDocumentProxy.h" #include "UBDocumentProxy.h"
class UBDocumentContainer : public QObject class UBDocumentContainer : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
UBDocumentContainer(QObject * parent = 0); UBDocumentContainer(QObject * parent = 0);
virtual ~UBDocumentContainer(); virtual ~UBDocumentContainer();
void setDocument(UBDocumentProxy* document, bool forceReload = false); void setDocument(UBDocumentProxy* document, bool forceReload = false);
UBDocumentProxy* selectedDocument(){return mCurrentDocument;} UBDocumentProxy* selectedDocument(){return mCurrentDocument;}
int pageCount(){return mDocumentThumbs.size();} int pageCount(){return mDocumentThumbs.size();}
const QPixmap* pageAt(int index){return mDocumentThumbs[index];} const QPixmap* pageAt(int index){return mDocumentThumbs[index];}
static int pageFromSceneIndex(int sceneIndex); static int pageFromSceneIndex(int sceneIndex);
static int sceneIndexFromPage(int sceneIndex); static int sceneIndexFromPage(int sceneIndex);
void duplicatePages(QList<int>& pageIndexes); void duplicatePages(QList<int>& pageIndexes);
bool movePageToIndex(int source, int target); bool movePageToIndex(int source, int target);
void deletePages(QList<int>& pageIndexes); void deletePages(QList<int>& pageIndexes);
void addPage(int index); void addPage(int index);
void updatePage(int index); void updatePage(int index);
void addEmptyThumbPage(); void addEmptyThumbPage();
private: private:
UBDocumentProxy* mCurrentDocument; UBDocumentProxy* mCurrentDocument;
QList<const QPixmap*> mDocumentThumbs; QList<const QPixmap*> mDocumentThumbs;
protected: protected:
void deleteThumbPage(int index); void deleteThumbPage(int index);
void updateThumbPage(int index); void updateThumbPage(int index);
void insertThumbPage(int index); void insertThumbPage(int index);
void reloadThumbnails(); void reloadThumbnails();
signals: signals:
void documentSet(UBDocumentProxy* document); void documentSet(UBDocumentProxy* document);
void documentPageUpdated(int index); void documentPageUpdated(int index);
void documentThumbnailsUpdated(UBDocumentContainer* source); void documentThumbnailsUpdated(UBDocumentContainer* source);
}; };
#endif /* UBDOCUMENTPROXY_H_ */ #endif /* UBDOCUMENTPROXY_H_ */
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -19,136 +19,136 @@ ...@@ -19,136 +19,136 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBDOCUMENTCONTROLLER_H_ #ifndef UBDOCUMENTCONTROLLER_H_
#define UBDOCUMENTCONTROLLER_H_ #define UBDOCUMENTCONTROLLER_H_
#include <QtGui> #include <QtGui>
#include "document/UBDocumentContainer.h" #include "document/UBDocumentContainer.h"
namespace Ui namespace Ui
{ {
class documents; class documents;
} }
#include "gui/UBMessageWindow.h" #include "gui/UBMessageWindow.h"
class UBGraphicsScene; class UBGraphicsScene;
class QDialog; class QDialog;
class UBDocumentProxy; class UBDocumentProxy;
class UBBoardController; class UBBoardController;
class UBThumbnailsScene; class UBThumbnailsScene;
class UBDocumentGroupTreeItem; class UBDocumentGroupTreeItem;
class UBDocumentProxyTreeItem; class UBDocumentProxyTreeItem;
class UBMainWindow; class UBMainWindow;
class UBDocumentToolsPalette; class UBDocumentToolsPalette;
class UBDocumentController : public UBDocumentContainer class UBDocumentController : public UBDocumentContainer
{ {
Q_OBJECT; Q_OBJECT;
public: public:
UBDocumentController(UBMainWindow* mainWindow); UBDocumentController(UBMainWindow* mainWindow);
virtual ~UBDocumentController(); virtual ~UBDocumentController();
void closing(); void closing();
QWidget* controlView(); QWidget* controlView();
UBDocumentProxyTreeItem* findDocument(UBDocumentProxy* proxy); UBDocumentProxyTreeItem* findDocument(UBDocumentProxy* proxy);
bool addFileToDocument(UBDocumentProxy* document); bool addFileToDocument(UBDocumentProxy* document);
void deletePages(QList<QGraphicsItem*> itemsToDelete); void deletePages(QList<QGraphicsItem*> itemsToDelete);
int getSelectedItemIndex(); int getSelectedItemIndex();
bool pageCanBeMovedUp(int page); bool pageCanBeMovedUp(int page);
bool pageCanBeMovedDown(int page); bool pageCanBeMovedDown(int page);
bool pageCanBeDuplicated(int page); bool pageCanBeDuplicated(int page);
bool pageCanBeDeleted(int page); bool pageCanBeDeleted(int page);
QString documentTrashGroupName(){ return mDocumentTrashGroupName;} QString documentTrashGroupName(){ return mDocumentTrashGroupName;}
QString defaultDocumentGroupName(){ return mDefaultDocumentGroupName;} QString defaultDocumentGroupName(){ return mDefaultDocumentGroupName;}
signals: signals:
void exportDone(); void exportDone();
public slots: public slots:
void createNewDocument(); void createNewDocument();
void createNewDocumentGroup(); void createNewDocumentGroup();
void deleteSelectedItem(); void deleteSelectedItem();
void renameSelectedItem(); void renameSelectedItem();
void openSelectedItem(); void openSelectedItem();
void duplicateSelectedItem(); void duplicateSelectedItem();
void importFile(); void importFile();
void moveSceneToIndex(UBDocumentProxy* proxy, int source, int target); void moveSceneToIndex(UBDocumentProxy* proxy, int source, int target);
void selectDocument(UBDocumentProxy* proxy, bool setAsCurrentDocument = true); void selectDocument(UBDocumentProxy* proxy, bool setAsCurrentDocument = true);
void show(); void show();
void hide(); void hide();
void showMessage(const QString& message, bool showSpinningWheel = false); void showMessage(const QString& message, bool showSpinningWheel = false);
void hideMessage(); void hideMessage();
void toggleDocumentToolsPalette(); void toggleDocumentToolsPalette();
void cut(); void cut();
void copy(); void copy();
void paste(); void paste();
void focusChanged(QWidget *old, QWidget *current); void focusChanged(QWidget *old, QWidget *current);
protected: protected:
virtual void setupViews(); virtual void setupViews();
virtual void setupToolbar(); virtual void setupToolbar();
void setupPalettes(); void setupPalettes();
bool isOKToOpenDocument(UBDocumentProxy* proxy); bool isOKToOpenDocument(UBDocumentProxy* proxy);
UBDocumentProxy* selectedDocumentProxy(); UBDocumentProxy* selectedDocumentProxy();
UBDocumentProxyTreeItem* selectedDocumentProxyTreeItem(); UBDocumentProxyTreeItem* selectedDocumentProxyTreeItem();
UBDocumentGroupTreeItem* selectedDocumentGroupTreeItem(); UBDocumentGroupTreeItem* selectedDocumentGroupTreeItem();
QStringList allGroupNames(); QStringList allGroupNames();
enum LastSelectedElementType enum LastSelectedElementType
{ {
None = 0, Folder, Document, Page None = 0, Folder, Document, Page
}; };
LastSelectedElementType mSelectionType; LastSelectedElementType mSelectionType;
private: private:
QWidget *mParentWidget; QWidget *mParentWidget;
UBBoardController *mBoardController; UBBoardController *mBoardController;
Ui::documents* mDocumentUI; Ui::documents* mDocumentUI;
UBMainWindow* mMainWindow; UBMainWindow* mMainWindow;
QWidget *mDocumentWidget; QWidget *mDocumentWidget;
QPointer<UBMessageWindow> mMessageWindow; QPointer<UBMessageWindow> mMessageWindow;
QAction* mAddFolderOfImagesAction; QAction* mAddFolderOfImagesAction;
QAction* mAddFileToDocumentAction; QAction* mAddFileToDocumentAction;
QAction* mAddImagesAction; QAction* mAddImagesAction;
bool mIsClosing; bool mIsClosing;
UBDocumentToolsPalette *mToolsPalette; UBDocumentToolsPalette *mToolsPalette;
bool mToolsPalettePositionned; bool mToolsPalettePositionned;
UBDocumentGroupTreeItem* mTrashTi; UBDocumentGroupTreeItem* mTrashTi;
void moveDocumentToTrash(UBDocumentGroupTreeItem* groupTi, UBDocumentProxyTreeItem *proxyTi); void moveDocumentToTrash(UBDocumentGroupTreeItem* groupTi, UBDocumentProxyTreeItem *proxyTi);
void moveFolderToTrash(UBDocumentGroupTreeItem* groupTi); void moveFolderToTrash(UBDocumentGroupTreeItem* groupTi);
QString mDocumentTrashGroupName; QString mDocumentTrashGroupName;
QString mDefaultDocumentGroupName; QString mDefaultDocumentGroupName;
private slots: private slots:
void documentZoomSliderValueChanged (int value); void documentZoomSliderValueChanged (int value);
void loadDocumentProxies(); void loadDocumentProxies();
void itemSelectionChanged(); void itemSelectionChanged();
void exportDocument(); void exportDocument();
void itemChanged(QTreeWidgetItem * item, int column); void itemChanged(QTreeWidgetItem * item, int column);
void thumbnailViewResized(); void thumbnailViewResized();
void pageSelectionChanged(); void pageSelectionChanged();
void selectionChanged(); void selectionChanged();
void documentSceneChanged(UBDocumentProxy* proxy, int pSceneIndex); void documentSceneChanged(UBDocumentProxy* proxy, int pSceneIndex);
void pageDoubleClicked(QGraphicsItem* item, int index); void pageDoubleClicked(QGraphicsItem* item, int index);
void pageClicked(QGraphicsItem* item, int index); void pageClicked(QGraphicsItem* item, int index);
void itemClicked(QTreeWidgetItem * item, int column ); void itemClicked(QTreeWidgetItem * item, int column );
void addToDocument(); void addToDocument();
void addDocumentInTree(UBDocumentProxy* pDocument); void addDocumentInTree(UBDocumentProxy* pDocument);
void updateDocumentInTree(UBDocumentProxy* pDocument); void updateDocumentInTree(UBDocumentProxy* pDocument);
void addFolderOfImages(); void addFolderOfImages();
void addFileToDocument(); void addFileToDocument();
void addImages(); void addImages();
void refreshDocumentThumbnailsView(UBDocumentContainer* source); void refreshDocumentThumbnailsView(UBDocumentContainer* source);
}; };
#endif /* UBDOCUMENTCONTROLLER_H_ */ #endif /* UBDOCUMENTCONTROLLER_H_ */
...@@ -19,222 +19,222 @@ ...@@ -19,222 +19,222 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBDocumentProxy.h" #include "UBDocumentProxy.h"
#include "frameworks/UBStringUtils.h" #include "frameworks/UBStringUtils.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "core/UBDocumentManager.h" #include "core/UBDocumentManager.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentProxy::UBDocumentProxy() UBDocumentProxy::UBDocumentProxy()
: mPageCount(0) : mPageCount(0)
{ {
init(); init();
} }
UBDocumentProxy::UBDocumentProxy(const QString& pPersistancePath) UBDocumentProxy::UBDocumentProxy(const QString& pPersistancePath)
: mPageCount(0) : mPageCount(0)
{ {
init(); init();
setPersistencePath(pPersistancePath); setPersistencePath(pPersistancePath);
} }
void UBDocumentProxy::init() void UBDocumentProxy::init()
{ {
setMetaData(UBSettings::documentGroupName, ""); setMetaData(UBSettings::documentGroupName, "");
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
setMetaData(UBSettings::documentName, now.toString(Qt::SystemLocaleShortDate)); setMetaData(UBSettings::documentName, now.toString(Qt::SystemLocaleShortDate));
setUuid(QUuid::createUuid()); setUuid(QUuid::createUuid());
setDefaultDocumentSize(UBSettings::settings()->pageSize->get().toSize()); setDefaultDocumentSize(UBSettings::settings()->pageSize->get().toSize());
//teacherGuide metadata //teacherGuide metadata
setMetaData(UBSettings::sessionTitle,""); setMetaData(UBSettings::sessionTitle,"");
setMetaData(UBSettings::sessionAuthors,""); setMetaData(UBSettings::sessionAuthors,"");
setMetaData(UBSettings::sessionObjectives,""); setMetaData(UBSettings::sessionObjectives,"");
setMetaData(UBSettings::sessionKeywords,""); setMetaData(UBSettings::sessionKeywords,"");
setMetaData(UBSettings::sessionGradeLevel,""); setMetaData(UBSettings::sessionGradeLevel,"");
setMetaData(UBSettings::sessionSubjects,""); setMetaData(UBSettings::sessionSubjects,"");
setMetaData(UBSettings::sessionType,""); setMetaData(UBSettings::sessionType,"");
setMetaData(UBSettings::sessionLicence,""); setMetaData(UBSettings::sessionLicence,"");
} }
UBDocumentProxy::~UBDocumentProxy() UBDocumentProxy::~UBDocumentProxy()
{ {
// NOOP // NOOP
} }
int UBDocumentProxy::pageCount() int UBDocumentProxy::pageCount()
{ {
return mPageCount; return mPageCount;
} }
void UBDocumentProxy::setPageCount(int pPageCount) void UBDocumentProxy::setPageCount(int pPageCount)
{ {
mPageCount = pPageCount; mPageCount = pPageCount;
} }
int UBDocumentProxy::incPageCount() int UBDocumentProxy::incPageCount()
{ {
if (mPageCount <= 0) if (mPageCount <= 0)
{ {
mPageCount = 1; mPageCount = 1;
} }
else else
{ {
mPageCount++; mPageCount++;
} }
return mPageCount; return mPageCount;
} }
int UBDocumentProxy::decPageCount() int UBDocumentProxy::decPageCount()
{ {
mPageCount --; mPageCount --;
if (mPageCount < 0) if (mPageCount < 0)
{ {
mPageCount = 0; mPageCount = 0;
} }
return mPageCount; return mPageCount;
} }
QString UBDocumentProxy::persistencePath() const QString UBDocumentProxy::persistencePath() const
{ {
return mPersistencePath; return mPersistencePath;
} }
void UBDocumentProxy::setPersistencePath(const QString& pPersistencePath) void UBDocumentProxy::setPersistencePath(const QString& pPersistencePath)
{ {
if (pPersistencePath != mPersistencePath) if (pPersistencePath != mPersistencePath)
{ {
mIsModified = true; mIsModified = true;
mPersistencePath = pPersistencePath; mPersistencePath = pPersistencePath;
} }
} }
void UBDocumentProxy::setMetaData(const QString& pKey, const QVariant& pValue) void UBDocumentProxy::setMetaData(const QString& pKey, const QVariant& pValue)
{ {
if (mMetaDatas.contains(pKey) && mMetaDatas.value(pKey) == pValue) if (mMetaDatas.contains(pKey) && mMetaDatas.value(pKey) == pValue)
return; return;
else else
{ {
mIsModified = true; mIsModified = true;
mMetaDatas.insert(pKey, pValue); mMetaDatas.insert(pKey, pValue);
if (pKey == UBSettings::documentUpdatedAt) if (pKey == UBSettings::documentUpdatedAt)
{ {
UBDocumentManager *documentManager = UBDocumentManager::documentManager(); UBDocumentManager *documentManager = UBDocumentManager::documentManager();
if (documentManager) if (documentManager)
documentManager->emitDocumentUpdated(this); documentManager->emitDocumentUpdated(this);
} }
} }
} }
QVariant UBDocumentProxy::metaData(const QString& pKey) const QVariant UBDocumentProxy::metaData(const QString& pKey) const
{ {
if (mMetaDatas.contains(pKey)) if (mMetaDatas.contains(pKey))
{ {
return mMetaDatas.value(pKey); return mMetaDatas.value(pKey);
} }
else else
{ {
qDebug() << "Unknown metadata key" << pKey; qDebug() << "Unknown metadata key" << pKey;
return QString(""); // failsafe return QString(""); // failsafe
} }
} }
QHash<QString, QVariant> UBDocumentProxy::metaDatas() const QHash<QString, QVariant> UBDocumentProxy::metaDatas() const
{ {
return mMetaDatas; return mMetaDatas;
} }
QString UBDocumentProxy::name() const QString UBDocumentProxy::name() const
{ {
return metaData(UBSettings::documentName).toString(); return metaData(UBSettings::documentName).toString();
} }
QString UBDocumentProxy::groupName() const QString UBDocumentProxy::groupName() const
{ {
return metaData(UBSettings::documentGroupName).toString(); return metaData(UBSettings::documentGroupName).toString();
} }
QSize UBDocumentProxy::defaultDocumentSize() const QSize UBDocumentProxy::defaultDocumentSize() const
{ {
if (mMetaDatas.contains(UBSettings::documentSize)) if (mMetaDatas.contains(UBSettings::documentSize))
return metaData(UBSettings::documentSize).toSize(); return metaData(UBSettings::documentSize).toSize();
else else
return UBSettings::settings()->pageSize->get().toSize(); return UBSettings::settings()->pageSize->get().toSize();
} }
void UBDocumentProxy::setDefaultDocumentSize(QSize pSize) void UBDocumentProxy::setDefaultDocumentSize(QSize pSize)
{ {
if (defaultDocumentSize() != pSize) if (defaultDocumentSize() != pSize)
{ {
setMetaData(UBSettings::documentSize, QVariant(pSize)); setMetaData(UBSettings::documentSize, QVariant(pSize));
emit defaultDocumentSizeChanged(); emit defaultDocumentSizeChanged();
mIsModified = true; mIsModified = true;
} }
} }
void UBDocumentProxy::setDefaultDocumentSize(int pWidth, int pHeight) void UBDocumentProxy::setDefaultDocumentSize(int pWidth, int pHeight)
{ {
setDefaultDocumentSize(QSize(pWidth, pHeight)); setDefaultDocumentSize(QSize(pWidth, pHeight));
} }
QUuid UBDocumentProxy::uuid() const QUuid UBDocumentProxy::uuid() const
{ {
QString id = metaData(UBSettings::documentIdentifer).toString(); QString id = metaData(UBSettings::documentIdentifer).toString();
QString sUuid = id.replace(UBSettings::uniboardDocumentNamespaceUri + "/", ""); QString sUuid = id.replace(UBSettings::uniboardDocumentNamespaceUri + "/", "");
return QUuid(sUuid); return QUuid(sUuid);
} }
void UBDocumentProxy::setUuid(const QUuid& uuid) void UBDocumentProxy::setUuid(const QUuid& uuid)
{ {
setMetaData(UBSettings::documentIdentifer, setMetaData(UBSettings::documentIdentifer,
UBSettings::uniboardDocumentNamespaceUri + "/" + UBStringUtils::toCanonicalUuid(uuid)); UBSettings::uniboardDocumentNamespaceUri + "/" + UBStringUtils::toCanonicalUuid(uuid));
} }
QDateTime UBDocumentProxy::documentDate() QDateTime UBDocumentProxy::documentDate()
{ {
if(mMetaDatas.contains(UBSettings::documentDate)) if(mMetaDatas.contains(UBSettings::documentDate))
return UBStringUtils::fromUtcIsoDate(metaData(UBSettings::documentDate).toString()); return UBStringUtils::fromUtcIsoDate(metaData(UBSettings::documentDate).toString());
return QDateTime::currentDateTime(); return QDateTime::currentDateTime();
} }
QDateTime UBDocumentProxy::lastUpdate() QDateTime UBDocumentProxy::lastUpdate()
{ {
if(mMetaDatas.contains(UBSettings::documentUpdatedAt)) if(mMetaDatas.contains(UBSettings::documentUpdatedAt))
return UBStringUtils::fromUtcIsoDate(metaData(UBSettings::documentUpdatedAt).toString()); return UBStringUtils::fromUtcIsoDate(metaData(UBSettings::documentUpdatedAt).toString());
return QDateTime().currentDateTime(); return QDateTime().currentDateTime();
} }
bool UBDocumentProxy::isModified() const bool UBDocumentProxy::isModified() const
{ {
return mIsModified; return mIsModified;
} }
...@@ -19,89 +19,89 @@ ...@@ -19,89 +19,89 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBDOCUMENTPROXY_H_ #ifndef UBDOCUMENTPROXY_H_
#define UBDOCUMENTPROXY_H_ #define UBDOCUMENTPROXY_H_
#include <QtGui> #include <QtGui>
#include "frameworks/UBStringUtils.h" #include "frameworks/UBStringUtils.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
class UBGraphicsScene; class UBGraphicsScene;
class UBDocumentProxy : public QObject class UBDocumentProxy : public QObject
{ {
Q_OBJECT Q_OBJECT
friend class UBPersistenceManager; friend class UBPersistenceManager;
public: public:
UBDocumentProxy(); UBDocumentProxy();
UBDocumentProxy(const QString& pPersistencePath); UBDocumentProxy(const QString& pPersistencePath);
virtual ~UBDocumentProxy(); virtual ~UBDocumentProxy();
QString persistencePath() const; QString persistencePath() const;
void setPersistencePath(const QString& pPersistencePath); void setPersistencePath(const QString& pPersistencePath);
void setMetaData(const QString& pKey , const QVariant& pValue); void setMetaData(const QString& pKey , const QVariant& pValue);
QVariant metaData(const QString& pKey) const; QVariant metaData(const QString& pKey) const;
QHash<QString, QVariant> metaDatas() const; QHash<QString, QVariant> metaDatas() const;
QString name() const; QString name() const;
QString groupName() const; QString groupName() const;
QDateTime documentDate(); QDateTime documentDate();
QDateTime lastUpdate(); QDateTime lastUpdate();
QSize defaultDocumentSize() const; QSize defaultDocumentSize() const;
void setDefaultDocumentSize(QSize pSize); void setDefaultDocumentSize(QSize pSize);
void setDefaultDocumentSize(int pWidth, int pHeight); void setDefaultDocumentSize(int pWidth, int pHeight);
QUuid uuid() const; QUuid uuid() const;
void setUuid(const QUuid& uuid); void setUuid(const QUuid& uuid);
bool isModified() const; bool isModified() const;
int pageCount(); int pageCount();
protected: protected:
void setPageCount(int pPageCount); void setPageCount(int pPageCount);
int incPageCount(); int incPageCount();
int decPageCount(); int decPageCount();
signals: signals:
void defaultDocumentSizeChanged(); void defaultDocumentSizeChanged();
private: private:
void init(); void init();
QString mPersistencePath; QString mPersistencePath;
QHash<QString, QVariant> mMetaDatas; QHash<QString, QVariant> mMetaDatas;
bool mIsModified; bool mIsModified;
int mPageCount; int mPageCount;
}; };
inline bool operator==(const UBDocumentProxy &proxy1, const UBDocumentProxy &proxy2) inline bool operator==(const UBDocumentProxy &proxy1, const UBDocumentProxy &proxy2)
{ {
return proxy1.persistencePath() == proxy2.persistencePath(); return proxy1.persistencePath() == proxy2.persistencePath();
} }
inline uint qHash(const UBDocumentProxy &key) inline uint qHash(const UBDocumentProxy &key)
{ {
return qHash(key.persistencePath()); return qHash(key.persistencePath());
} }
#endif /* UBDOCUMENTPROXY_H_ */ #endif /* UBDOCUMENTPROXY_H_ */
...@@ -19,987 +19,987 @@ ...@@ -19,987 +19,987 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBGraphicsDelegateFrame.h" #include "UBGraphicsDelegateFrame.h"
#include <QtGui> #include <QtGui>
#include <QtSvg> #include <QtSvg>
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "board/UBBoardView.h" #include "board/UBBoardView.h"
#include "domain/UBGraphicsItemDelegate.h" #include "domain/UBGraphicsItemDelegate.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "domain/UBGraphicsProxyWidget.h" #include "domain/UBGraphicsProxyWidget.h"
#include "gui/UBResources.h" #include "gui/UBResources.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBGraphicsDelegateFrame::UBGraphicsDelegateFrame(UBGraphicsItemDelegate* pDelegate, QRectF pRect, qreal pFrameWidth, bool respectRatio) UBGraphicsDelegateFrame::UBGraphicsDelegateFrame(UBGraphicsItemDelegate* pDelegate, QRectF pRect, qreal pFrameWidth, bool respectRatio)
: QGraphicsRectItem(), QObject(pDelegate) : QGraphicsRectItem(), QObject(pDelegate)
, mCurrentTool(None) , mCurrentTool(None)
, mDelegate(pDelegate) , mDelegate(pDelegate)
, mVisible(true) , mVisible(true)
, mFrameWidth(pFrameWidth) , mFrameWidth(pFrameWidth)
, mNominalFrameWidth(pFrameWidth) , mNominalFrameWidth(pFrameWidth)
, mRespectRatio(respectRatio) , mRespectRatio(respectRatio)
, mAngle(0) , mAngle(0)
, mAngleOffset(0) , mAngleOffset(0)
, mTotalScaleX(-1) , mTotalScaleX(-1)
, mTotalScaleY(-1) , mTotalScaleY(-1)
, mTranslateX(0) , mTranslateX(0)
, mTranslateY(0) , mTranslateY(0)
, mTotalTranslateX(0) , mTotalTranslateX(0)
, mTotalTranslateY(0) , mTotalTranslateY(0)
, mOperationMode(Scaling) , mOperationMode(Scaling)
, mFlippedX(false) , mFlippedX(false)
, mFlippedY(false) , mFlippedY(false)
, mMirrorX(false) , mMirrorX(false)
, mMirrorY(false) , mMirrorY(false)
{ {
mAngleTolerance = UBSettings::settings()->angleTolerance->get().toReal(); mAngleTolerance = UBSettings::settings()->angleTolerance->get().toReal();
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
setAcceptedMouseButtons(Qt::LeftButton); setAcceptedMouseButtons(Qt::LeftButton);
setRect(pRect.adjusted(mFrameWidth, mFrameWidth, mFrameWidth * -1, mFrameWidth * -1)); setRect(pRect.adjusted(mFrameWidth, mFrameWidth, mFrameWidth * -1, mFrameWidth * -1));
setBrush(QBrush(UBSettings::paletteColor)); setBrush(QBrush(UBSettings::paletteColor));
setPen(Qt::NoPen); setPen(Qt::NoPen);
setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Control)); setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Control));
mBottomRightResizeGripSvgItem = new QGraphicsSvgItem(":/images/resize.svg", this); mBottomRightResizeGripSvgItem = new QGraphicsSvgItem(":/images/resize.svg", this);
mBottomResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeBottom.svg", this); mBottomResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeBottom.svg", this);
mLeftResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeLeft.svg", this); mLeftResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeLeft.svg", this);
mRightResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeRight.svg", this); mRightResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeRight.svg", this);
mTopResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeTop.svg", this); mTopResizeGripSvgItem = new QGraphicsSvgItem(":/images/resizeTop.svg", this);
mBottomRightResizeGrip = new QGraphicsRectItem(this); mBottomRightResizeGrip = new QGraphicsRectItem(this);
mBottomRightResizeGrip->setPen(Qt::NoPen); mBottomRightResizeGrip->setPen(Qt::NoPen);
mBottomResizeGrip = new QGraphicsRectItem(this); mBottomResizeGrip = new QGraphicsRectItem(this);
mBottomResizeGrip->setPen(Qt::NoPen); mBottomResizeGrip->setPen(Qt::NoPen);
mLeftResizeGrip = new QGraphicsRectItem(this); mLeftResizeGrip = new QGraphicsRectItem(this);
mLeftResizeGrip->setPen(Qt::NoPen); mLeftResizeGrip->setPen(Qt::NoPen);
mRightResizeGrip = new QGraphicsRectItem(this); mRightResizeGrip = new QGraphicsRectItem(this);
mRightResizeGrip->setPen(Qt::NoPen); mRightResizeGrip->setPen(Qt::NoPen);
mTopResizeGrip = new QGraphicsRectItem(this); mTopResizeGrip = new QGraphicsRectItem(this);
mTopResizeGrip->setPen(Qt::NoPen); mTopResizeGrip->setPen(Qt::NoPen);
mRotateButton = new QGraphicsSvgItem(":/images/rotate.svg", this); mRotateButton = new QGraphicsSvgItem(":/images/rotate.svg", this);
mRotateButton->setCursor(UBResources::resources()->rotateCursor); mRotateButton->setCursor(UBResources::resources()->rotateCursor);
mRotateButton->setVisible(mDelegate->canRotate()); mRotateButton->setVisible(mDelegate->canRotate());
updateResizeCursors(); updateResizeCursors();
setAntiScale(1.0); setAntiScale(1.0);
positionHandles(); positionHandles();
this->setAcceptHoverEvents(true); this->setAcceptHoverEvents(true);
} }
UBGraphicsDelegateFrame::~UBGraphicsDelegateFrame() UBGraphicsDelegateFrame::~UBGraphicsDelegateFrame()
{ {
// NOOP // NOOP
} }
void UBGraphicsDelegateFrame::setAntiScale(qreal pAntiScale) void UBGraphicsDelegateFrame::setAntiScale(qreal pAntiScale)
{ {
mFrameWidth = mNominalFrameWidth * pAntiScale; mFrameWidth = mNominalFrameWidth * pAntiScale;
QTransform tr; QTransform tr;
tr.scale(pAntiScale, pAntiScale); tr.scale(pAntiScale, pAntiScale);
mBottomRightResizeGripSvgItem->setTransform(tr); mBottomRightResizeGripSvgItem->setTransform(tr);
mBottomResizeGripSvgItem->setTransform(tr); mBottomResizeGripSvgItem->setTransform(tr);
mLeftResizeGripSvgItem->setTransform(tr); mLeftResizeGripSvgItem->setTransform(tr);
mRightResizeGripSvgItem->setTransform(tr); mRightResizeGripSvgItem->setTransform(tr);
mTopResizeGripSvgItem->setTransform(tr); mTopResizeGripSvgItem->setTransform(tr);
mRotateButton->setTransform(tr); mRotateButton->setTransform(tr);
} }
void UBGraphicsDelegateFrame::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) void UBGraphicsDelegateFrame::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ {
Q_UNUSED(option); Q_UNUSED(option);
Q_UNUSED(widget); Q_UNUSED(widget);
QPainterPath path; QPainterPath path;
path.addRoundedRect(rect(), mFrameWidth / 2, mFrameWidth / 2); path.addRoundedRect(rect(), mFrameWidth / 2, mFrameWidth / 2);
if (rect().width() > 1 && rect().height() > 1) if (rect().width() > 1 && rect().height() > 1)
{ {
QPainterPath extruded; QPainterPath extruded;
extruded.addRect(rect().adjusted(mFrameWidth, mFrameWidth, (mFrameWidth * -1), (mFrameWidth * -1))); extruded.addRect(rect().adjusted(mFrameWidth, mFrameWidth, (mFrameWidth * -1), (mFrameWidth * -1)));
path = path.subtracted(extruded); path = path.subtracted(extruded);
} }
painter->fillPath(path, brush()); painter->fillPath(path, brush());
} }
QPainterPath UBGraphicsDelegateFrame::shape() const QPainterPath UBGraphicsDelegateFrame::shape() const
{ {
QPainterPath path; QPainterPath path;
//We do not use the rounded rect here because we want the bottom right corner //We do not use the rounded rect here because we want the bottom right corner
//to be included in the frame (for resize grip handling : #702) //to be included in the frame (for resize grip handling : #702)
path.addRect(rect()); path.addRect(rect());
if (rect().width() > 0 && rect().height() > 0) if (rect().width() > 0 && rect().height() > 0)
{ {
QPainterPath extruded; QPainterPath extruded;
extruded.addRect(rect().adjusted(mFrameWidth, mFrameWidth, mFrameWidth * -1, mFrameWidth * -1)); extruded.addRect(rect().adjusted(mFrameWidth, mFrameWidth, mFrameWidth * -1, mFrameWidth * -1));
path = path.subtracted(extruded); path = path.subtracted(extruded);
} }
return path; return path;
} }
void UBGraphicsDelegateFrame::initializeTransform() void UBGraphicsDelegateFrame::initializeTransform()
{ {
QTransform itemTransform = delegated()->sceneTransform(); QTransform itemTransform = delegated()->sceneTransform();
QRectF itemRect = delegated()->boundingRect(); QRectF itemRect = delegated()->boundingRect();
QPointF topLeft = itemTransform.map(itemRect.topLeft()); QPointF topLeft = itemTransform.map(itemRect.topLeft());
QPointF topRight = itemTransform.map(itemRect.topRight()); QPointF topRight = itemTransform.map(itemRect.topRight());
QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft()); QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft());
qreal horizontalFlip = (topLeft.x() > topRight.x()) ? -1 : 1; qreal horizontalFlip = (topLeft.x() > topRight.x()) ? -1 : 1;
mMirrorX = horizontalFlip < 0 ; mMirrorX = horizontalFlip < 0 ;
if(horizontalFlip < 0){ if(horizontalFlip < 0){
// why this is because of the way of calculating the translations that checks which side is the most is the // why this is because of the way of calculating the translations that checks which side is the most is the
// nearest instead of checking which one is the left side. // nearest instead of checking which one is the left side.
QPointF tmp = topLeft; QPointF tmp = topLeft;
topLeft = topRight; topLeft = topRight;
topRight = tmp; topRight = tmp;
// because of the calculation of the height is done by lenght and not deltaY // because of the calculation of the height is done by lenght and not deltaY
bottomLeft = itemTransform.map(itemRect.bottomRight()); bottomLeft = itemTransform.map(itemRect.bottomRight());
} }
qreal verticalFlip = (bottomLeft.y() < topLeft.y()) ? -1 : 1; qreal verticalFlip = (bottomLeft.y() < topLeft.y()) ? -1 : 1;
// not sure that is usefull // not sure that is usefull
mMirrorY = verticalFlip < 0; mMirrorY = verticalFlip < 0;
if(verticalFlip < 0 && !mMirrorX){ if(verticalFlip < 0 && !mMirrorX){
topLeft = itemTransform.map(itemRect.bottomLeft()); topLeft = itemTransform.map(itemRect.bottomLeft());
topRight = itemTransform.map(itemRect.bottomRight()); topRight = itemTransform.map(itemRect.bottomRight());
bottomLeft = itemTransform.map(itemRect.topLeft()); bottomLeft = itemTransform.map(itemRect.topLeft());
} }
QLineF topLine(topLeft, topRight); QLineF topLine(topLeft, topRight);
QLineF leftLine(topLeft, bottomLeft); QLineF leftLine(topLeft, bottomLeft);
qreal width = topLine.length(); qreal width = topLine.length();
qreal height = leftLine.length(); qreal height = leftLine.length();
mAngle = topLine.angle(); mAngle = topLine.angle();
// the fact the the length is used we loose the horizontalFlip information // the fact the the length is used we loose the horizontalFlip information
// a better way to do this is using DeltaX that preserve the direction information. // a better way to do this is using DeltaX that preserve the direction information.
mTotalScaleX = (width / itemRect.width()) * horizontalFlip; mTotalScaleX = (width / itemRect.width()) * horizontalFlip;
mTotalScaleY = height / itemRect.height() * verticalFlip; mTotalScaleY = height / itemRect.height() * verticalFlip;
QTransform tr; QTransform tr;
QPointF center = delegated()->boundingRect().center(); QPointF center = delegated()->boundingRect().center();
tr.translate(center.x() * mTotalScaleX, center.y() * mTotalScaleY); tr.translate(center.x() * mTotalScaleX, center.y() * mTotalScaleY);
tr.rotate(-mAngle); tr.rotate(-mAngle);
tr.translate(-center.x() * mTotalScaleX, -center.y() * mTotalScaleY); tr.translate(-center.x() * mTotalScaleX, -center.y() * mTotalScaleY);
tr.scale(mTotalScaleX, mTotalScaleY); tr.scale(mTotalScaleX, mTotalScaleY);
mTotalTranslateX = delegated()->transform().dx() - tr.dx(); mTotalTranslateX = delegated()->transform().dx() - tr.dx();
mTotalTranslateY = delegated()->transform().dy() - tr.dy(); mTotalTranslateY = delegated()->transform().dy() - tr.dy();
} }
void UBGraphicsDelegateFrame::mousePressEvent(QGraphicsSceneMouseEvent *event) void UBGraphicsDelegateFrame::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
mDelegate->startUndoStep(); mDelegate->startUndoStep();
mStartingPoint = event->scenePos(); mStartingPoint = event->scenePos();
initializeTransform(); initializeTransform();
mScaleX = 1; mScaleX = 1;
mScaleY = 1; mScaleY = 1;
mTranslateX = 0; mTranslateX = 0;
mTranslateY = 0; mTranslateY = 0;
mAngleOffset = 0; mAngleOffset = 0;
mInitialTransform = buildTransform(); mInitialTransform = buildTransform();
mOriginalSize = delegated()->boundingRect().size(); mOriginalSize = delegated()->boundingRect().size();
mCurrentTool = toolFromPos(event->pos()); mCurrentTool = toolFromPos(event->pos());
setCursorFromAngle(QString::number((int)mAngle % 360)); setCursorFromAngle(QString::number((int)mAngle % 360));
event->accept(); event->accept();
if (moving()) if (moving())
prepareFramesToMove(getLinkedFrames()); prepareFramesToMove(getLinkedFrames());
} }
void UBGraphicsDelegateFrame::setCursorFromAngle(QString angle) void UBGraphicsDelegateFrame::setCursorFromAngle(QString angle)
{ {
if (mCurrentTool == Rotate) if (mCurrentTool == Rotate)
{ {
QWidget *controlViewport = UBApplication::boardController->controlView()->viewport(); QWidget *controlViewport = UBApplication::boardController->controlView()->viewport();
QSize cursorSize(45,30); QSize cursorSize(45,30);
QImage mask_img(cursorSize, QImage::Format_Mono); QImage mask_img(cursorSize, QImage::Format_Mono);
mask_img.fill(0xff); mask_img.fill(0xff);
QPainter mask_ptr(&mask_img); QPainter mask_ptr(&mask_img);
mask_ptr.setBrush( QBrush( QColor(0, 0, 0) ) ); mask_ptr.setBrush( QBrush( QColor(0, 0, 0) ) );
mask_ptr.drawRoundedRect(0,0, cursorSize.width()-1, cursorSize.height()-1, 6, 6); mask_ptr.drawRoundedRect(0,0, cursorSize.width()-1, cursorSize.height()-1, 6, 6);
QBitmap bmpMask = QBitmap::fromImage(mask_img); QBitmap bmpMask = QBitmap::fromImage(mask_img);
QPixmap pixCursor(cursorSize); QPixmap pixCursor(cursorSize);
pixCursor.fill(QColor(Qt::white)); pixCursor.fill(QColor(Qt::white));
QPainter painter(&pixCursor); QPainter painter(&pixCursor);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.setBrush(QBrush(Qt::white)); painter.setBrush(QBrush(Qt::white));
painter.setPen(QPen(QColor(Qt::black))); painter.setPen(QPen(QColor(Qt::black)));
painter.drawRoundedRect(1,1,cursorSize.width()-2,cursorSize.height()-2,6,6); painter.drawRoundedRect(1,1,cursorSize.width()-2,cursorSize.height()-2,6,6);
painter.setFont(QFont("Arial", 10)); painter.setFont(QFont("Arial", 10));
painter.drawText(1,1,cursorSize.width(),cursorSize.height(), Qt::AlignCenter, angle.append(QChar(176))); painter.drawText(1,1,cursorSize.width(),cursorSize.height(), Qt::AlignCenter, angle.append(QChar(176)));
painter.end(); painter.end();
pixCursor.setMask(bmpMask); pixCursor.setMask(bmpMask);
controlViewport->setCursor(pixCursor); controlViewport->setCursor(pixCursor);
} }
} }
bool UBGraphicsDelegateFrame::canResizeBottomRight(qreal width, qreal height, qreal scaleFactor) bool UBGraphicsDelegateFrame::canResizeBottomRight(qreal width, qreal height, qreal scaleFactor)
{ {
bool res = false; bool res = false;
if(!mMirrorX && !mMirrorX && ((width * scaleFactor) > 2*mFrameWidth && (height * scaleFactor) > 2*mFrameWidth)){ if(!mMirrorX && !mMirrorX && ((width * scaleFactor) > 2*mFrameWidth && (height * scaleFactor) > 2*mFrameWidth)){
res = true; res = true;
}else if(mMirrorX && !mMirrorY && (-width * scaleFactor) > 2*mFrameWidth && (height*scaleFactor) > 2*mFrameWidth){ }else if(mMirrorX && !mMirrorY && (-width * scaleFactor) > 2*mFrameWidth && (height*scaleFactor) > 2*mFrameWidth){
res = true; res = true;
}else if(!mMirrorX && mMirrorY && (width * scaleFactor) > 2*mFrameWidth && (-height*scaleFactor) > 2*mFrameWidth){ }else if(!mMirrorX && mMirrorY && (width * scaleFactor) > 2*mFrameWidth && (-height*scaleFactor) > 2*mFrameWidth){
res = true; res = true;
}else if(mMirrorX && mMirrorY && (-width * scaleFactor) > 2*mFrameWidth && (-height*scaleFactor) > 2*mFrameWidth){ }else if(mMirrorX && mMirrorY && (-width * scaleFactor) > 2*mFrameWidth && (-height*scaleFactor) > 2*mFrameWidth){
res = true; res = true;
} }
return res; return res;
} }
QPointF UBGraphicsDelegateFrame::getFixedPointFromPos() QPointF UBGraphicsDelegateFrame::getFixedPointFromPos()
{ {
QPointF fixedPoint; QPointF fixedPoint;
if (!moving() && !rotating()) if (!moving() && !rotating())
{ {
if (resizingTop()) if (resizingTop())
{ {
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
{ {
if ((0 < mAngle) && (mAngle < 90)) if ((0 < mAngle) && (mAngle < 90))
fixedPoint = delegated()->sceneBoundingRect().topLeft(); fixedPoint = delegated()->sceneBoundingRect().topLeft();
else else
fixedPoint = delegated()->sceneBoundingRect().topRight(); fixedPoint = delegated()->sceneBoundingRect().topRight();
} }
else else
{ {
if ((0 < mAngle) && (mAngle <= 90)) if ((0 < mAngle) && (mAngle <= 90))
fixedPoint = delegated()->sceneBoundingRect().bottomRight(); fixedPoint = delegated()->sceneBoundingRect().bottomRight();
else else
fixedPoint = delegated()->sceneBoundingRect().bottomLeft(); fixedPoint = delegated()->sceneBoundingRect().bottomLeft();
} }
} }
else if (resizingLeft()) else if (resizingLeft())
{ {
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
{ {
if ((0 < mAngle) && (mAngle < 90)) if ((0 < mAngle) && (mAngle < 90))
fixedPoint = delegated()->sceneBoundingRect().bottomLeft(); fixedPoint = delegated()->sceneBoundingRect().bottomLeft();
else else
fixedPoint = delegated()->sceneBoundingRect().topLeft(); fixedPoint = delegated()->sceneBoundingRect().topLeft();
} }
else else
{ {
if ((0 < mAngle) && (mAngle <= 90)) if ((0 < mAngle) && (mAngle <= 90))
fixedPoint = delegated()->sceneBoundingRect().topRight(); fixedPoint = delegated()->sceneBoundingRect().topRight();
else else
fixedPoint = delegated()->sceneBoundingRect().bottomRight(); fixedPoint = delegated()->sceneBoundingRect().bottomRight();
} }
} }
} }
return fixedPoint; return fixedPoint;
} }
QSizeF UBGraphicsDelegateFrame::getResizeVector(qreal moveX, qreal moveY) QSizeF UBGraphicsDelegateFrame::getResizeVector(qreal moveX, qreal moveY)
{ {
qreal dPosX = 0; qreal dPosX = 0;
qreal dPosY = 0; qreal dPosY = 0;
if (resizingTop()) if (resizingTop())
{ {
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
dPosY = moveY; dPosY = moveY;
else else
dPosY = -moveY; dPosY = -moveY;
} }
else if (resizingLeft()) else if (resizingLeft())
{ {
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
dPosX = moveX; dPosX = moveX;
else else
dPosX = -moveX; dPosX = -moveX;
} }
else if (resizingRight()) else if (resizingRight())
dPosX = (mMirrorX) ? -moveX : moveX; dPosX = (mMirrorX) ? -moveX : moveX;
else if (resizingBottom()) else if (resizingBottom())
dPosY = mMirrorY ? -moveY : moveY; dPosY = mMirrorY ? -moveY : moveY;
return QSizeF(dPosX, dPosY); return QSizeF(dPosX, dPosY);
} }
QSizeF UBGraphicsDelegateFrame::resizeDelegate(qreal moveX, qreal moveY) QSizeF UBGraphicsDelegateFrame::resizeDelegate(qreal moveX, qreal moveY)
{ {
QSizeF incVector; QSizeF incVector;
mFixedPoint = getFixedPointFromPos(); mFixedPoint = getFixedPointFromPos();
UBResizableGraphicsItem* resizableItem = dynamic_cast<UBResizableGraphicsItem*>(delegated()); UBResizableGraphicsItem* resizableItem = dynamic_cast<UBResizableGraphicsItem*>(delegated());
if (resizableItem) if (resizableItem)
{ {
incVector = getResizeVector(moveX, moveY); incVector = getResizeVector(moveX, moveY);
resizableItem->resize(mOriginalSize + incVector); resizableItem->resize(mOriginalSize + incVector);
if (resizingTop() || resizingLeft() || ((mMirrorX || mMirrorY) && resizingBottomRight())) if (resizingTop() || resizingLeft() || ((mMirrorX || mMirrorY) && resizingBottomRight()))
{ {
QPointF pos1 = getFixedPointFromPos(); QPointF pos1 = getFixedPointFromPos();
delegated()->setPos(delegated()->pos()-pos1+mFixedPoint); delegated()->setPos(delegated()->pos()-pos1+mFixedPoint);
} }
} }
return incVector; return incVector;
} }
void UBGraphicsDelegateFrame::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void UBGraphicsDelegateFrame::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (None == mCurrentTool) if (None == mCurrentTool)
return; return;
QLineF move = QLineF(mStartingPoint, event->scenePos()); QLineF move = QLineF(mStartingPoint, event->scenePos());
qreal moveX = move.length() * cos((move.angle() - mAngle) * PI / 180); qreal moveX = move.length() * cos((move.angle() - mAngle) * PI / 180);
qreal moveY = -move.length() * sin((move.angle() - mAngle) * PI / 180); qreal moveY = -move.length() * sin((move.angle() - mAngle) * PI / 180);
qreal width = delegated()->boundingRect().width() * mTotalScaleX; qreal width = delegated()->boundingRect().width() * mTotalScaleX;
qreal height = delegated()->boundingRect().height() * mTotalScaleY; qreal height = delegated()->boundingRect().height() * mTotalScaleY;
if (mOperationMode == Scaling) if (mOperationMode == Scaling)
{ {
if(!rotating()) if(!rotating())
{ {
mTranslateX = moveX; mTranslateX = moveX;
// Perform the resize // Perform the resize
if (resizingBottomRight()) if (resizingBottomRight())
{ {
// ----------------------------------------------------- // -----------------------------------------------------
// ! We want to keep the aspect ratio with this resize ! // ! We want to keep the aspect ratio with this resize !
// ----------------------------------------------------- // -----------------------------------------------------
qreal scaleX; qreal scaleX;
qreal scaleY; qreal scaleY;
if(!mMirrorX){ if(!mMirrorX){
scaleX = (width + moveX) / width; scaleX = (width + moveX) / width;
}else{ }else{
scaleX = (width - moveX) / width; scaleX = (width - moveX) / width;
} }
if(!mMirrorY){ if(!mMirrorY){
scaleY = (height + moveY) / height; scaleY = (height + moveY) / height;
}else{ }else{
scaleY = (height - moveY) / height; scaleY = (height - moveY) / height;
} }
qreal scaleFactor = (scaleX + scaleY) / 2; qreal scaleFactor = (scaleX + scaleY) / 2;
// Do not allow resizing of image size under frame size // Do not allow resizing of image size under frame size
if (canResizeBottomRight(width, height, scaleFactor)) if (canResizeBottomRight(width, height, scaleFactor))
{ {
if (mRespectRatio) if (mRespectRatio)
{ {
mScaleX = scaleFactor; mScaleX = scaleFactor;
mScaleY = scaleFactor; mScaleY = scaleFactor;
} }
else else
{ {
mScaleX = scaleX; mScaleX = scaleX;
mScaleY = scaleY; mScaleY = scaleY;
} }
} }
}else if (resizingLeft() || resizingRight()) }else if (resizingLeft() || resizingRight())
{ {
if(width != 0){ if(width != 0){
qreal scaleX = 0.0; qreal scaleX = 0.0;
if(resizingLeft()){ if(resizingLeft()){
scaleX = (width - moveX) / width; scaleX = (width - moveX) / width;
}else if(resizingRight()){ }else if(resizingRight()){
scaleX = (width + moveX) / width; scaleX = (width + moveX) / width;
} }
if(mDelegate->isFlippable() && qAbs(scaleX) != 0){ if(mDelegate->isFlippable() && qAbs(scaleX) != 0){
if((qAbs(width * scaleX)) < 2*mFrameWidth){ if((qAbs(width * scaleX)) < 2*mFrameWidth){
bool negative = (scaleX < 0)?true:false; bool negative = (scaleX < 0)?true:false;
if(negative){ if(negative){
if(mMirrorX) if(mMirrorX)
scaleX = 2*mFrameWidth/width; scaleX = 2*mFrameWidth/width;
else else
scaleX = -2*mFrameWidth/width; scaleX = -2*mFrameWidth/width;
}else{ }else{
scaleX = -1; scaleX = -1;
mFlippedX = !mFlippedX; mFlippedX = !mFlippedX;
} }
} }
mScaleX = scaleX; mScaleX = scaleX;
}else if (scaleX > 1 || (width * scaleX) > 2 * mFrameWidth){ }else if (scaleX > 1 || (width * scaleX) > 2 * mFrameWidth){
mScaleX = scaleX; mScaleX = scaleX;
if(resizingLeft()){ if(resizingLeft()){
mTranslateX = moveX; mTranslateX = moveX;
} }
} }
} }
}else if(resizingTop() || resizingBottom()){ }else if(resizingTop() || resizingBottom()){
if(height != 0){ if(height != 0){
qreal scaleY = 0.0; qreal scaleY = 0.0;
if(resizingTop()){ if(resizingTop()){
scaleY = (height - moveY) / height; scaleY = (height - moveY) / height;
}else if(resizingBottom()){ }else if(resizingBottom()){
scaleY = (height + moveY) / height; scaleY = (height + moveY) / height;
} }
if(mDelegate->isFlippable() && qAbs(scaleY) != 0){ if(mDelegate->isFlippable() && qAbs(scaleY) != 0){
if((qAbs(height * scaleY)) < 2*mFrameWidth){ if((qAbs(height * scaleY)) < 2*mFrameWidth){
bool negative = (scaleY < 0)?true:false; bool negative = (scaleY < 0)?true:false;
if(negative){ if(negative){
if(mMirrorY) if(mMirrorY)
scaleY = 2*mFrameWidth/width; scaleY = 2*mFrameWidth/width;
else else
scaleY = -2*mFrameWidth/width; scaleY = -2*mFrameWidth/width;
}else{ }else{
scaleY = -1; scaleY = -1;
mFlippedY = !mFlippedY; mFlippedY = !mFlippedY;
} }
} }
mScaleY = scaleY; mScaleY = scaleY;
}else if (scaleY > 1 || (height * scaleY) > 2 * mFrameWidth) }else if (scaleY > 1 || (height * scaleY) > 2 * mFrameWidth)
{ {
mScaleY = scaleY; mScaleY = scaleY;
if(resizingTop()){ if(resizingTop()){
mTranslateY = moveY; mTranslateY = moveY;
} }
} }
} }
} }
} }
} }
if (rotating()) if (rotating())
{ {
mTranslateX = 0; mTranslateX = 0;
mTranslateY = 0; mTranslateY = 0;
QLineF startLine(sceneBoundingRect().center(), event->lastScenePos()); QLineF startLine(sceneBoundingRect().center(), event->lastScenePos());
QLineF currentLine(sceneBoundingRect().center(), event->scenePos()); QLineF currentLine(sceneBoundingRect().center(), event->scenePos());
mAngle += startLine.angleTo(currentLine); mAngle += startLine.angleTo(currentLine);
if ((int)mAngle % 45 >= 45 - mAngleTolerance || (int)mAngle % 45 <= mAngleTolerance) if ((int)mAngle % 45 >= 45 - mAngleTolerance || (int)mAngle % 45 <= mAngleTolerance)
{ {
mAngle = qRound(mAngle / 45) * 45; mAngle = qRound(mAngle / 45) * 45;
mAngleOffset += startLine.angleTo(currentLine); mAngleOffset += startLine.angleTo(currentLine);
if ((int)mAngleOffset % 360 > mAngleTolerance && (int)mAngleOffset % 360 < 360 - mAngleTolerance) if ((int)mAngleOffset % 360 > mAngleTolerance && (int)mAngleOffset % 360 < 360 - mAngleTolerance)
{ {
mAngle += mAngleOffset; mAngle += mAngleOffset;
mAngleOffset = 0; mAngleOffset = 0;
} }
} }
else if ((int)mAngle % 30 >= 30 - mAngleTolerance || (int)mAngle % 30 <= mAngleTolerance) else if ((int)mAngle % 30 >= 30 - mAngleTolerance || (int)mAngle % 30 <= mAngleTolerance)
{ {
mAngle = qRound(mAngle / 30) * 30; mAngle = qRound(mAngle / 30) * 30;
mAngleOffset += startLine.angleTo(currentLine); mAngleOffset += startLine.angleTo(currentLine);
if ((int)mAngleOffset % 360 > mAngleTolerance && (int)mAngleOffset % 360 < 360 - mAngleTolerance) if ((int)mAngleOffset % 360 > mAngleTolerance && (int)mAngleOffset % 360 < 360 - mAngleTolerance)
{ {
mAngle += mAngleOffset; mAngle += mAngleOffset;
mAngleOffset = 0; mAngleOffset = 0;
} }
} }
setCursorFromAngle(QString::number((int)mAngle % 360)); setCursorFromAngle(QString::number((int)mAngle % 360));
} }
else if (moving()) else if (moving())
{ {
mTranslateX = move.dx(); mTranslateX = move.dx();
mTranslateY = move.dy(); mTranslateY = move.dy();
moveLinkedItems(move); moveLinkedItems(move);
} }
if (mOperationMode == Scaling || moving() || rotating()) if (mOperationMode == Scaling || moving() || rotating())
{ {
QTransform tr = buildTransform(); QTransform tr = buildTransform();
if (resizingRight() || resizingBottom() || resizingBottomRight()) if (resizingRight() || resizingBottom() || resizingBottomRight())
{ {
QPointF ref; QPointF ref;
// we just detects coordinates of corner before and after scaling and then moves object at diff between them. // we just detects coordinates of corner before and after scaling and then moves object at diff between them.
if (resizingBottomRight() && (mMirrorX || mMirrorY)) if (resizingBottomRight() && (mMirrorX || mMirrorY))
{ {
if (mFlippedX && !mMirrorX && mFlippedY)// && !mMirrorY) if (mFlippedX && !mMirrorX && mFlippedY)// && !mMirrorY)
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).x() - tr.map(delegated()->boundingRect().bottomLeft()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).x() - tr.map(delegated()->boundingRect().bottomLeft()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).y() - tr.map(delegated()->boundingRect().bottomLeft()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).y() - tr.map(delegated()->boundingRect().bottomLeft()).y();
} }
else if ((mFlippedX || mMirrorX) && (mFlippedY || mMirrorY)) else if ((mFlippedX || mMirrorX) && (mFlippedY || mMirrorY))
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomRight()).x() - tr.map(delegated()->boundingRect().bottomRight()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomRight()).x() - tr.map(delegated()->boundingRect().bottomRight()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomRight()).y() - tr.map(delegated()->boundingRect().bottomRight()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomRight()).y() - tr.map(delegated()->boundingRect().bottomRight()).y();
} }
else if (mFlippedX || mMirrorX) else if (mFlippedX || mMirrorX)
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().topRight()).x() - tr.map(delegated()->boundingRect().topRight()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().topRight()).x() - tr.map(delegated()->boundingRect().topRight()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().topRight()).y() - tr.map(delegated()->boundingRect().topRight()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().topRight()).y() - tr.map(delegated()->boundingRect().topRight()).y();
} }
else if (mFlippedY || mMirrorY) else if (mFlippedY || mMirrorY)
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).x() - tr.map(delegated()->boundingRect().bottomLeft()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).x() - tr.map(delegated()->boundingRect().bottomLeft()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).y() - tr.map(delegated()->boundingRect().bottomLeft()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomLeft()).y() - tr.map(delegated()->boundingRect().bottomLeft()).y();
} }
else else
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomRight()).x() - tr.map(delegated()->boundingRect().bottomRight()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().bottomRight()).x() - tr.map(delegated()->boundingRect().bottomRight()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomRight()).y() - tr.map(delegated()->boundingRect().bottomRight()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().bottomRight()).y() - tr.map(delegated()->boundingRect().bottomRight()).y();
} }
} }
else else
{ {
mTranslateX += mInitialTransform.map(delegated()->boundingRect().topLeft()).x() - tr.map(delegated()->boundingRect().topLeft()).x(); mTranslateX += mInitialTransform.map(delegated()->boundingRect().topLeft()).x() - tr.map(delegated()->boundingRect().topLeft()).x();
mTranslateY += mInitialTransform.map(delegated()->boundingRect().topLeft()).y() - tr.map(delegated()->boundingRect().topLeft()).y(); mTranslateY += mInitialTransform.map(delegated()->boundingRect().topLeft()).y() - tr.map(delegated()->boundingRect().topLeft()).y();
} }
} }
else if (resizingTop() || resizingLeft()) else if (resizingTop() || resizingLeft())
{ {
QPointF bottomRight = tr.map(delegated()->boundingRect().bottomRight()); QPointF bottomRight = tr.map(delegated()->boundingRect().bottomRight());
QPointF fixedPoint = mInitialTransform.map(delegated()->boundingRect().bottomRight()); QPointF fixedPoint = mInitialTransform.map(delegated()->boundingRect().bottomRight());
mTranslateX += fixedPoint.x() - bottomRight.x(); mTranslateX += fixedPoint.x() - bottomRight.x();
mTranslateY += fixedPoint.y() - bottomRight.y(); mTranslateY += fixedPoint.y() - bottomRight.y();
} }
delegated()->setTransform(buildTransform()); delegated()->setTransform(buildTransform());
} }
else // resizing/resizing horizontally else // resizing/resizing horizontally
{ {
if (resizingBottomRight()) if (resizingBottomRight())
{ {
static QSizeF incV = QSizeF(); static QSizeF incV = QSizeF();
static QSizeF incH = QSizeF(); static QSizeF incH = QSizeF();
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
mCurrentTool = ResizeTop; mCurrentTool = ResizeTop;
else else
mCurrentTool = ResizeBottom; mCurrentTool = ResizeBottom;
incV = resizeDelegate(moveX, moveY); incV = resizeDelegate(moveX, moveY);
mOriginalSize += incV; mOriginalSize += incV;
if (mMirrorX && mMirrorY) if (mMirrorX && mMirrorY)
mCurrentTool = ResizeLeft; mCurrentTool = ResizeLeft;
else else
mCurrentTool = ResizeRight; mCurrentTool = ResizeRight;
move = QLineF(event->lastScenePos(), event->scenePos()); move = QLineF(event->lastScenePos(), event->scenePos());
moveX = move.length() * cos((move.angle() - mAngle) * PI / 180); moveX = move.length() * cos((move.angle() - mAngle) * PI / 180);
moveY = -move.length() * sin((move.angle() - mAngle) * PI / 180); moveY = -move.length() * sin((move.angle() - mAngle) * PI / 180);
mFixedPoint = getFixedPointFromPos(); mFixedPoint = getFixedPointFromPos();
incH = resizeDelegate(moveX, moveY); incH = resizeDelegate(moveX, moveY);
mOriginalSize -= incV; mOriginalSize -= incV;
mOriginalSize += incH; mOriginalSize += incH;
mCurrentTool = ResizeBottomRight; mCurrentTool = ResizeBottomRight;
} }
else else
resizeDelegate(moveX, moveY); resizeDelegate(moveX, moveY);
} }
event->accept(); event->accept();
} }
QList<UBGraphicsDelegateFrame *> UBGraphicsDelegateFrame::getLinkedFrames() QList<UBGraphicsDelegateFrame *> UBGraphicsDelegateFrame::getLinkedFrames()
{ {
QList<UBGraphicsDelegateFrame*> linkedFrames; QList<UBGraphicsDelegateFrame*> linkedFrames;
QList<QGraphicsItem*> sItems = mDelegate->delegated()->scene()->selectedItems(); QList<QGraphicsItem*> sItems = mDelegate->delegated()->scene()->selectedItems();
if (sItems.count()) if (sItems.count())
{ {
sItems.removeAll(delegated()); sItems.removeAll(delegated());
foreach(QGraphicsItem *item, sItems) foreach(QGraphicsItem *item, sItems)
{ {
UBGraphicsItem *gitem = dynamic_cast<UBGraphicsItem*>(item); UBGraphicsItem *gitem = dynamic_cast<UBGraphicsItem*>(item);
if (gitem) if (gitem)
linkedFrames << gitem->Delegate()->frame(); linkedFrames << gitem->Delegate()->frame();
} }
} }
return linkedFrames; return linkedFrames;
} }
void UBGraphicsDelegateFrame::prepareFramesToMove(QList<UBGraphicsDelegateFrame *> framesToMove) void UBGraphicsDelegateFrame::prepareFramesToMove(QList<UBGraphicsDelegateFrame *> framesToMove)
{ {
mLinkedFrames = framesToMove; mLinkedFrames = framesToMove;
foreach (UBGraphicsDelegateFrame *frame, mLinkedFrames) foreach (UBGraphicsDelegateFrame *frame, mLinkedFrames)
{ {
frame->prepareLinkedFrameToMove(); frame->prepareLinkedFrameToMove();
} }
} }
void UBGraphicsDelegateFrame::prepareLinkedFrameToMove() void UBGraphicsDelegateFrame::prepareLinkedFrameToMove()
{ {
mDelegate->startUndoStep(); mDelegate->startUndoStep();
mStartingPoint = QPointF(0,0); mStartingPoint = QPointF(0,0);
initializeTransform(); initializeTransform();
mScaleX = 1; mScaleX = 1;
mScaleY = 1; mScaleY = 1;
mTranslateX = 0; mTranslateX = 0;
mTranslateY = 0; mTranslateY = 0;
mAngleOffset = 0; mAngleOffset = 0;
mInitialTransform = buildTransform(); mInitialTransform = buildTransform();
mCurrentTool = Move; mCurrentTool = Move;
} }
void UBGraphicsDelegateFrame::moveLinkedItems(QLineF movingVector, bool bLinked) void UBGraphicsDelegateFrame::moveLinkedItems(QLineF movingVector, bool bLinked)
{ {
if (bLinked) if (bLinked)
{ {
mCurrentTool = Move; mCurrentTool = Move;
mTranslateX = movingVector.dx(); mTranslateX = movingVector.dx();
mTranslateY = movingVector.dy(); mTranslateY = movingVector.dy();
delegated()->setTransform(buildTransform(), false); delegated()->setTransform(buildTransform(), false);
} }
else else
{ {
foreach(UBGraphicsDelegateFrame* frame, mLinkedFrames) foreach(UBGraphicsDelegateFrame* frame, mLinkedFrames)
{ {
frame->moveLinkedItems(movingVector, true); frame->moveLinkedItems(movingVector, true);
} }
} }
} }
QTransform UBGraphicsDelegateFrame::buildTransform() QTransform UBGraphicsDelegateFrame::buildTransform()
{ {
QTransform tr; QTransform tr;
QPointF center = delegated()->boundingRect().center(); QPointF center = delegated()->boundingRect().center();
// Translate // Translate
tr.translate(mTotalTranslateX + mTranslateX, mTotalTranslateY + mTranslateY); tr.translate(mTotalTranslateX + mTranslateX, mTotalTranslateY + mTranslateY);
// Set angle // Set angle
tr.translate(center.x() * mTotalScaleX * mScaleX, center.y() * mTotalScaleY * mScaleY); tr.translate(center.x() * mTotalScaleX * mScaleX, center.y() * mTotalScaleY * mScaleY);
tr.rotate(-mAngle); tr.rotate(-mAngle);
tr.translate(-center.x() * mTotalScaleX * mScaleX, -center.y() * mTotalScaleY * mScaleY); tr.translate(-center.x() * mTotalScaleX * mScaleX, -center.y() * mTotalScaleY * mScaleY);
// Scale // Scale
tr.scale(mTotalScaleX * mScaleX, mTotalScaleY * mScaleY); tr.scale(mTotalScaleX * mScaleX, mTotalScaleY * mScaleY);
return tr; return tr;
} }
void UBGraphicsDelegateFrame::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void UBGraphicsDelegateFrame::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
updateResizeCursors(); updateResizeCursors();
mDelegate->commitUndoStep(); mDelegate->commitUndoStep();
mTotalScaleX *= mScaleX; mTotalScaleX *= mScaleX;
mTotalScaleY *= mScaleY; mTotalScaleY *= mScaleY;
mTotalTranslateX += mTranslateX; mTotalTranslateX += mTranslateX;
mTotalTranslateY += mTranslateY; mTotalTranslateY += mTranslateY;
event->accept(); event->accept();
mCurrentTool = None; mCurrentTool = None;
QGraphicsRectItem::mouseReleaseEvent(event); QGraphicsRectItem::mouseReleaseEvent(event);
// Show the buttons // Show the buttons
if(isResizing()){ if(isResizing()){
mResizing = false; mResizing = false;
} }
} }
void UBGraphicsDelegateFrame::updateResizeCursors() void UBGraphicsDelegateFrame::updateResizeCursors()
{ {
QPixmap pix(":/images/cursors/resize.png"); QPixmap pix(":/images/cursors/resize.png");
QTransform tr; QTransform tr;
tr.rotate(-mAngle); tr.rotate(-mAngle);
QCursor resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2); QCursor resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2);
mLeftResizeGrip->setCursor(resizeCursor); mLeftResizeGrip->setCursor(resizeCursor);
mRightResizeGrip->setCursor(resizeCursor); mRightResizeGrip->setCursor(resizeCursor);
tr.rotate(-90); tr.rotate(-90);
resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2); resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2);
mBottomResizeGrip->setCursor(resizeCursor); mBottomResizeGrip->setCursor(resizeCursor);
mTopResizeGrip->setCursor(resizeCursor); mTopResizeGrip->setCursor(resizeCursor);
tr.rotate(-45); tr.rotate(-45);
resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2); resizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2);
mBottomRightResizeGrip->setCursor(resizeCursor); mBottomRightResizeGrip->setCursor(resizeCursor);
} }
void UBGraphicsDelegateFrame::setVisible(bool visible) void UBGraphicsDelegateFrame::setVisible(bool visible)
{ {
mVisible = visible; mVisible = visible;
if (mVisible) if (mVisible)
setBrush(QBrush(UBSettings::paletteColor)); setBrush(QBrush(UBSettings::paletteColor));
else else
setBrush(Qt::NoBrush); setBrush(Qt::NoBrush);
} }
void UBGraphicsDelegateFrame::positionHandles() void UBGraphicsDelegateFrame::positionHandles()
{ {
QRectF itemRect = delegated()->boundingRect(); QRectF itemRect = delegated()->boundingRect();
if (mDelegate->getToolBarItem() && mDelegate->getToolBarItem()->isVisibleOnBoard() if (mDelegate->getToolBarItem() && mDelegate->getToolBarItem()->isVisibleOnBoard()
&& mDelegate->getToolBarItem()->isShifting()) && mDelegate->getToolBarItem()->isShifting())
{ {
QPointF graphicsItemPosition = itemRect.topLeft(); QPointF graphicsItemPosition = itemRect.topLeft();
itemRect.setTopLeft(graphicsItemPosition-QPointF(0,mDelegate->getToolBarItem()->boundingRect().height()* mDelegate->antiScaleRatio())); itemRect.setTopLeft(graphicsItemPosition-QPointF(0,mDelegate->getToolBarItem()->boundingRect().height()* mDelegate->antiScaleRatio()));
} }
QTransform itemTransform = delegated()->sceneTransform(); QTransform itemTransform = delegated()->sceneTransform();
QPointF topLeft = itemTransform.map(itemRect.topLeft()); QPointF topLeft = itemTransform.map(itemRect.topLeft());
QPointF topRight = itemTransform.map(itemRect.topRight()); QPointF topRight = itemTransform.map(itemRect.topRight());
QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft()); QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft());
QPointF bottomRight = itemTransform.map(itemRect.bottomRight()); QPointF bottomRight = itemTransform.map(itemRect.bottomRight());
QPointF center = itemTransform.map(itemRect.center()); QPointF center = itemTransform.map(itemRect.center());
int rotateHeight = QLineF(topLeft, bottomLeft).length(); int rotateHeight = QLineF(topLeft, bottomLeft).length();
// Handle the mirroring // Handle the mirroring
if(topLeft.x() > topRight.x()){ if(topLeft.x() > topRight.x()){
QPointF topTmp = topRight; QPointF topTmp = topRight;
QPointF bottomTmp = bottomRight; QPointF bottomTmp = bottomRight;
topRight = topLeft; topRight = topLeft;
topLeft = topTmp; topLeft = topTmp;
bottomRight = bottomLeft; bottomRight = bottomLeft;
bottomLeft = bottomTmp; bottomLeft = bottomTmp;
} }
if(bottomLeft.y() > topLeft.y()){ if(bottomLeft.y() > topLeft.y()){
QPointF leftTmp = bottomLeft; QPointF leftTmp = bottomLeft;
QPointF rightTmp = bottomRight; QPointF rightTmp = bottomRight;
bottomLeft = topLeft; bottomLeft = topLeft;
topLeft = leftTmp; topLeft = leftTmp;
bottomRight = topRight; bottomRight = topRight;
topRight = rightTmp; topRight = rightTmp;
} }
QLineF topLine(topLeft, topRight); QLineF topLine(topLeft, topRight);
qreal angle = topLine.angle(); qreal angle = topLine.angle();
qreal width = topLine.length(); qreal width = topLine.length();
QLineF leftLine(topLeft, bottomLeft); QLineF leftLine(topLeft, bottomLeft);
qreal height = leftLine.length(); qreal height = leftLine.length();
int h = rotating()?rotateHeight:height; int h = rotating()?rotateHeight:height;
if (mVisible) if (mVisible)
{ {
setRect(center.x() - mFrameWidth - width / 2, center.y() - mFrameWidth - h / 2, width + 2 * mFrameWidth, h + 2 * mFrameWidth); setRect(center.x() - mFrameWidth - width / 2, center.y() - mFrameWidth - h / 2, width + 2 * mFrameWidth, h + 2 * mFrameWidth);
} }
else else
{ {
setRect(center.x() - width / 2, center.y() - h / 2, width, h); setRect(center.x() - width / 2, center.y() - h / 2, width, h);
} }
resetTransform(); resetTransform();
translate(center.x(), center.y()); translate(center.x(), center.y());
rotate(-angle); rotate(-angle);
translate(-center.x(), -center.y()); translate(-center.x(), -center.y());
mBottomRightResizeGripSvgItem->setParentItem(this); mBottomRightResizeGripSvgItem->setParentItem(this);
mBottomResizeGripSvgItem->setParentItem(this); mBottomResizeGripSvgItem->setParentItem(this);
mLeftResizeGripSvgItem->setParentItem(this); mLeftResizeGripSvgItem->setParentItem(this);
mRightResizeGripSvgItem->setParentItem(this); mRightResizeGripSvgItem->setParentItem(this);
mTopResizeGripSvgItem->setParentItem(this); mTopResizeGripSvgItem->setParentItem(this);
mRotateButton->setParentItem(this); mRotateButton->setParentItem(this);
mBottomRightResizeGrip->setParentItem(this); mBottomRightResizeGrip->setParentItem(this);
mBottomResizeGrip->setParentItem(this); mBottomResizeGrip->setParentItem(this);
mLeftResizeGrip->setParentItem(this); mLeftResizeGrip->setParentItem(this);
mRightResizeGrip->setParentItem(this); mRightResizeGrip->setParentItem(this);
mTopResizeGrip->setParentItem(this); mTopResizeGrip->setParentItem(this);
QRectF brRect = mBottomRightResizeGripSvgItem->mapRectToParent(mBottomRightResizeGripSvgItem->boundingRect()); QRectF brRect = mBottomRightResizeGripSvgItem->mapRectToParent(mBottomRightResizeGripSvgItem->boundingRect());
QRectF bRect = mBottomResizeGripSvgItem->mapRectToParent(mBottomResizeGripSvgItem->boundingRect()); QRectF bRect = mBottomResizeGripSvgItem->mapRectToParent(mBottomResizeGripSvgItem->boundingRect());
QRectF lRect = mLeftResizeGripSvgItem->mapRectToParent(mLeftResizeGripSvgItem->boundingRect()); QRectF lRect = mLeftResizeGripSvgItem->mapRectToParent(mLeftResizeGripSvgItem->boundingRect());
QRectF rRect = mRightResizeGripSvgItem->mapRectToParent(mRightResizeGripSvgItem->boundingRect()); QRectF rRect = mRightResizeGripSvgItem->mapRectToParent(mRightResizeGripSvgItem->boundingRect());
QRectF trRect = mTopResizeGripSvgItem->mapRectToParent(mTopResizeGripSvgItem->boundingRect()); QRectF trRect = mTopResizeGripSvgItem->mapRectToParent(mTopResizeGripSvgItem->boundingRect());
mBottomRightResizeGripSvgItem->setPos(rect().right() - brRect.width(), rect().bottom() - brRect.height()); mBottomRightResizeGripSvgItem->setPos(rect().right() - brRect.width(), rect().bottom() - brRect.height());
mBottomResizeGripSvgItem->setPos(rect().center().x() - bRect.width() / 2, rect().bottom() - bRect.height()); mBottomResizeGripSvgItem->setPos(rect().center().x() - bRect.width() / 2, rect().bottom() - bRect.height());
mLeftResizeGripSvgItem->setPos(rect().left(), rect().center().y() - lRect.height() / 2); mLeftResizeGripSvgItem->setPos(rect().left(), rect().center().y() - lRect.height() / 2);
mRightResizeGripSvgItem->setPos(rect().right() - rRect.width(), rect().center().y() - rRect.height() / 2); mRightResizeGripSvgItem->setPos(rect().right() - rRect.width(), rect().center().y() - rRect.height() / 2);
mTopResizeGripSvgItem->setPos(rect().center().x() - trRect.width() / 2, rect().y()); mTopResizeGripSvgItem->setPos(rect().center().x() - trRect.width() / 2, rect().y());
mRotateButton->setPos(rect().right() - mFrameWidth - 5, rect().top() + 5); mRotateButton->setPos(rect().right() - mFrameWidth - 5, rect().top() + 5);
mBottomRightResizeGrip->setRect(bottomRightResizeGripRect()); mBottomRightResizeGrip->setRect(bottomRightResizeGripRect());
mBottomResizeGrip->setRect(bottomResizeGripRect()); mBottomResizeGrip->setRect(bottomResizeGripRect());
mLeftResizeGrip->setRect(leftResizeGripRect()); mLeftResizeGrip->setRect(leftResizeGripRect());
mRightResizeGrip->setRect(rightResizeGripRect()); mRightResizeGrip->setRect(rightResizeGripRect());
mTopResizeGrip->setRect(topResizeGripRect()); mTopResizeGrip->setRect(topResizeGripRect());
QVariant vLocked = delegated()->data(UBGraphicsItemData::ItemLocked); QVariant vLocked = delegated()->data(UBGraphicsItemData::ItemLocked);
bool isLocked = (vLocked.isValid() && vLocked.toBool()); bool isLocked = (vLocked.isValid() && vLocked.toBool());
bool bShowHorizontalResizers = ResizingHorizontally == mOperationMode; bool bShowHorizontalResizers = ResizingHorizontally == mOperationMode;
bool bShowVerticalResizers = ResizingHorizontally != mOperationMode; bool bShowVerticalResizers = ResizingHorizontally != mOperationMode;
bool bShowAllResizers = Resizing == mOperationMode || Scaling == mOperationMode ; bool bShowAllResizers = Resizing == mOperationMode || Scaling == mOperationMode ;
mBottomRightResizeGripSvgItem->setVisible(!isLocked && bShowAllResizers); mBottomRightResizeGripSvgItem->setVisible(!isLocked && bShowAllResizers);
mBottomResizeGripSvgItem->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers)); mBottomResizeGripSvgItem->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers));
mLeftResizeGripSvgItem->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers)); mLeftResizeGripSvgItem->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers));
mRightResizeGripSvgItem->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers)); mRightResizeGripSvgItem->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers));
mTopResizeGripSvgItem->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers)); mTopResizeGripSvgItem->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers));
mRotateButton->setVisible(mDelegate->canRotate() && !isLocked); mRotateButton->setVisible(mDelegate->canRotate() && !isLocked);
mBottomRightResizeGrip->setVisible(!isLocked && bShowAllResizers); mBottomRightResizeGrip->setVisible(!isLocked && bShowAllResizers);
mBottomResizeGrip->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers)); mBottomResizeGrip->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers));
mLeftResizeGrip->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers)); mLeftResizeGrip->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers));
mRightResizeGrip->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers)); mRightResizeGrip->setVisible(!isLocked && (bShowHorizontalResizers || bShowAllResizers));
mTopResizeGrip->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers)); mTopResizeGrip->setVisible(!isLocked && (bShowVerticalResizers || bShowAllResizers));
if (isLocked) if (isLocked)
{ {
QColor baseColor = UBSettings::paletteColor; QColor baseColor = UBSettings::paletteColor;
baseColor.setAlphaF(baseColor.alphaF() / 3); baseColor.setAlphaF(baseColor.alphaF() / 3);
setBrush(QBrush(baseColor)); setBrush(QBrush(baseColor));
} }
else else
{ {
setBrush(QBrush(UBSettings::paletteColor)); setBrush(QBrush(UBSettings::paletteColor));
} }
//make frame interact like delegated item when selected. Maybe should be deleted if selection logic will change //make frame interact like delegated item when selected. Maybe should be deleted if selection logic will change
setZValue(delegated()->zValue()); setZValue(delegated()->zValue());
} }
QGraphicsItem* UBGraphicsDelegateFrame::delegated() QGraphicsItem* UBGraphicsDelegateFrame::delegated()
{ {
return mDelegate->delegated(); return mDelegate->delegated();
} }
UBGraphicsDelegateFrame::FrameTool UBGraphicsDelegateFrame::toolFromPos(QPointF pos) UBGraphicsDelegateFrame::FrameTool UBGraphicsDelegateFrame::toolFromPos(QPointF pos)
{ {
if(mDelegate->isLocked()) if(mDelegate->isLocked())
return None; return None;
else if (bottomRightResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode) else if (bottomRightResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode)
return ResizeBottomRight; return ResizeBottomRight;
else if (bottomResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode){ else if (bottomResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode){
if(mMirrorY){ if(mMirrorY){
return ResizeTop; return ResizeTop;
}else{ }else{
return ResizeBottom; return ResizeBottom;
} }
} }
else if (leftResizeGripRect().contains(pos)){ else if (leftResizeGripRect().contains(pos)){
if(mMirrorX){ if(mMirrorX){
return ResizeRight; return ResizeRight;
}else{ }else{
return ResizeLeft; return ResizeLeft;
} }
return ResizeLeft; return ResizeLeft;
} }
else if (rightResizeGripRect().contains(pos)){ else if (rightResizeGripRect().contains(pos)){
if(mMirrorX){ if(mMirrorX){
return ResizeLeft; return ResizeLeft;
}else{ }else{
return ResizeRight; return ResizeRight;
} }
} }
else if (topResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode){ else if (topResizeGripRect().contains(pos) && ResizingHorizontally != mOperationMode){
if(mMirrorY){ if(mMirrorY){
return ResizeBottom; return ResizeBottom;
}else{ }else{
return ResizeTop; return ResizeTop;
} }
} }
else if (rotateButtonBounds().contains(pos) && mDelegate && mDelegate->canRotate()) else if (rotateButtonBounds().contains(pos) && mDelegate && mDelegate->canRotate())
return Rotate; return Rotate;
else else
return Move; return Move;
} }
QRectF UBGraphicsDelegateFrame::bottomRightResizeGripRect() const QRectF UBGraphicsDelegateFrame::bottomRightResizeGripRect() const
{ {
return QRectF(rect().right() - mFrameWidth, rect().bottom() - mFrameWidth, mFrameWidth, mFrameWidth); return QRectF(rect().right() - mFrameWidth, rect().bottom() - mFrameWidth, mFrameWidth, mFrameWidth);
} }
QRectF UBGraphicsDelegateFrame::bottomResizeGripRect() const QRectF UBGraphicsDelegateFrame::bottomResizeGripRect() const
{ {
return QRectF(rect().center().x() - mFrameWidth / 2, rect().bottom() - mFrameWidth, mFrameWidth, mFrameWidth); return QRectF(rect().center().x() - mFrameWidth / 2, rect().bottom() - mFrameWidth, mFrameWidth, mFrameWidth);
} }
QRectF UBGraphicsDelegateFrame::leftResizeGripRect() const QRectF UBGraphicsDelegateFrame::leftResizeGripRect() const
{ {
return QRectF(rect().left(), rect().center().y() - mFrameWidth / 2, mFrameWidth, mFrameWidth); return QRectF(rect().left(), rect().center().y() - mFrameWidth / 2, mFrameWidth, mFrameWidth);
} }
QRectF UBGraphicsDelegateFrame::rightResizeGripRect() const QRectF UBGraphicsDelegateFrame::rightResizeGripRect() const
{ {
return QRectF(rect().right() - mFrameWidth, rect().center().y() - mFrameWidth / 2, mFrameWidth, mFrameWidth); return QRectF(rect().right() - mFrameWidth, rect().center().y() - mFrameWidth / 2, mFrameWidth, mFrameWidth);
} }
QRectF UBGraphicsDelegateFrame::topResizeGripRect() const QRectF UBGraphicsDelegateFrame::topResizeGripRect() const
{ {
return QRectF(rect().center().x() - mFrameWidth / 2, rect().top(), mFrameWidth, mFrameWidth); return QRectF(rect().center().x() - mFrameWidth / 2, rect().top(), mFrameWidth, mFrameWidth);
} }
QRectF UBGraphicsDelegateFrame::rotateButtonBounds() const QRectF UBGraphicsDelegateFrame::rotateButtonBounds() const
{ {
return QRectF(rect().right()- mFrameWidth, rect().top(), mFrameWidth, mFrameWidth); return QRectF(rect().right()- mFrameWidth, rect().top(), mFrameWidth, mFrameWidth);
} }
void UBGraphicsDelegateFrame::refreshGeometry() void UBGraphicsDelegateFrame::refreshGeometry()
{ {
// Here we want to have the left on the left, the right on the right, the top on the top and the bottom on the bottom! // Here we want to have the left on the left, the right on the right, the top on the top and the bottom on the bottom!
QRectF itemRect = delegated()->boundingRect(); QRectF itemRect = delegated()->boundingRect();
QTransform itemTransform = delegated()->sceneTransform(); QTransform itemTransform = delegated()->sceneTransform();
QPointF topLeft = itemTransform.map(itemRect.topLeft()); QPointF topLeft = itemTransform.map(itemRect.topLeft());
QPointF topRight = itemTransform.map(itemRect.topRight()); QPointF topRight = itemTransform.map(itemRect.topRight());
QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft()); QPointF bottomLeft = itemTransform.map(itemRect.bottomLeft());
QLineF topLine(topLeft, topRight); QLineF topLine(topLeft, topRight);
qreal width = topLine.length(); qreal width = topLine.length();
QLineF leftLine(topLeft, bottomLeft); QLineF leftLine(topLeft, bottomLeft);
qreal height = leftLine.length(); qreal height = leftLine.length();
setRect(topRight.x() - mFrameWidth, topLeft.y() - mFrameWidth, width + 2*mFrameWidth, height + 2*mFrameWidth); setRect(topRight.x() - mFrameWidth, topLeft.y() - mFrameWidth, width + 2*mFrameWidth, height + 2*mFrameWidth);
} }
...@@ -19,221 +19,221 @@ ...@@ -19,221 +19,221 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBGraphicsItemUndoCommand.h" #include "UBGraphicsItemUndoCommand.h"
#include <QtGui> #include <QtGui>
#include "UBGraphicsScene.h" #include "UBGraphicsScene.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "core/memcheck.h" #include "core/memcheck.h"
#include "domain/UBGraphicsGroupContainerItem.h" #include "domain/UBGraphicsGroupContainerItem.h"
#include "domain/UBGraphicsPolygonItem.h" #include "domain/UBGraphicsPolygonItem.h"
UBGraphicsItemUndoCommand::UBGraphicsItemUndoCommand(UBGraphicsScene* pScene, const QSet<QGraphicsItem*>& pRemovedItems, UBGraphicsItemUndoCommand::UBGraphicsItemUndoCommand(UBGraphicsScene* pScene, const QSet<QGraphicsItem*>& pRemovedItems,
const QSet<QGraphicsItem*>& pAddedItems, const GroupDataTable &groupsMap) const QSet<QGraphicsItem*>& pAddedItems, const GroupDataTable &groupsMap)
: mScene(pScene) : mScene(pScene)
, mRemovedItems(pRemovedItems - pAddedItems) , mRemovedItems(pRemovedItems - pAddedItems)
, mAddedItems(pAddedItems - pRemovedItems) , mAddedItems(pAddedItems - pRemovedItems)
, mExcludedFromGroup(groupsMap) , mExcludedFromGroup(groupsMap)
{ {
mFirstRedo = true; mFirstRedo = true;
QSetIterator<QGraphicsItem*> itAdded(mAddedItems); QSetIterator<QGraphicsItem*> itAdded(mAddedItems);
while (itAdded.hasNext()) while (itAdded.hasNext())
{ {
UBApplication::boardController->freezeW3CWidget(itAdded.next(), true); UBApplication::boardController->freezeW3CWidget(itAdded.next(), true);
} }
QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems); QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems);
while (itRemoved.hasNext()) while (itRemoved.hasNext())
{ {
UBApplication::boardController->freezeW3CWidget(itRemoved.next(), false); UBApplication::boardController->freezeW3CWidget(itRemoved.next(), false);
} }
} }
UBGraphicsItemUndoCommand::UBGraphicsItemUndoCommand(UBGraphicsScene* pScene, QGraphicsItem* pRemovedItem, UBGraphicsItemUndoCommand::UBGraphicsItemUndoCommand(UBGraphicsScene* pScene, QGraphicsItem* pRemovedItem,
QGraphicsItem* pAddedItem) : QGraphicsItem* pAddedItem) :
mScene(pScene) mScene(pScene)
{ {
if (pRemovedItem) if (pRemovedItem)
{ {
mRemovedItems.insert(pRemovedItem); mRemovedItems.insert(pRemovedItem);
} }
if (pAddedItem) if (pAddedItem)
{ {
mAddedItems.insert(pAddedItem); mAddedItems.insert(pAddedItem);
} }
mFirstRedo = true; mFirstRedo = true;
} }
UBGraphicsItemUndoCommand::~UBGraphicsItemUndoCommand() UBGraphicsItemUndoCommand::~UBGraphicsItemUndoCommand()
{ {
//NOOP //NOOP
} }
void UBGraphicsItemUndoCommand::undo() void UBGraphicsItemUndoCommand::undo()
{ {
if (!mScene){ if (!mScene){
return; return;
} }
QSetIterator<QGraphicsItem*> itAdded(mAddedItems); QSetIterator<QGraphicsItem*> itAdded(mAddedItems);
while (itAdded.hasNext()) while (itAdded.hasNext())
{ {
QGraphicsItem* item = itAdded.next(); QGraphicsItem* item = itAdded.next();
UBApplication::boardController->freezeW3CWidget(item, true); UBApplication::boardController->freezeW3CWidget(item, true);
item->setSelected(false); item->setSelected(false);
mScene->removeItem(item); mScene->removeItem(item);
} }
QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems); QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems);
while (itRemoved.hasNext()) while (itRemoved.hasNext())
{ {
QGraphicsItem* item = itRemoved.next(); QGraphicsItem* item = itRemoved.next();
if (item) if (item)
{ {
if (UBItemLayerType::FixedBackground == item->data(UBGraphicsItemData::ItemLayerType)) if (UBItemLayerType::FixedBackground == item->data(UBGraphicsItemData::ItemLayerType))
mScene->setAsBackgroundObject(item); mScene->setAsBackgroundObject(item);
else else
mScene->addItem(item); mScene->addItem(item);
if (UBGraphicsPolygonItem::Type == item->type()) if (UBGraphicsPolygonItem::Type == item->type())
{ {
UBGraphicsPolygonItem *polygonItem = qgraphicsitem_cast<UBGraphicsPolygonItem*>(item); UBGraphicsPolygonItem *polygonItem = qgraphicsitem_cast<UBGraphicsPolygonItem*>(item);
if (polygonItem) if (polygonItem)
{ {
mScene->removeItem(polygonItem); mScene->removeItem(polygonItem);
mScene->removeItemFromDeletion(polygonItem); mScene->removeItemFromDeletion(polygonItem);
polygonItem->strokesGroup()->addToGroup(polygonItem); polygonItem->strokesGroup()->addToGroup(polygonItem);
} }
} }
UBApplication::boardController->freezeW3CWidget(item, false); UBApplication::boardController->freezeW3CWidget(item, false);
} }
} }
QMapIterator<UBGraphicsGroupContainerItem*, QUuid> curMapElement(mExcludedFromGroup); QMapIterator<UBGraphicsGroupContainerItem*, QUuid> curMapElement(mExcludedFromGroup);
UBGraphicsGroupContainerItem *nextGroup = NULL; UBGraphicsGroupContainerItem *nextGroup = NULL;
UBGraphicsGroupContainerItem *previousGroupItem = NULL; UBGraphicsGroupContainerItem *previousGroupItem = NULL;
bool groupChanged = false; bool groupChanged = false;
while (curMapElement.hasNext()) { while (curMapElement.hasNext()) {
curMapElement.next(); curMapElement.next();
groupChanged = previousGroupItem != curMapElement.key(); groupChanged = previousGroupItem != curMapElement.key();
//trying to find the group on the scene; //trying to find the group on the scene;
if (!nextGroup || groupChanged) { if (!nextGroup || groupChanged) {
UBGraphicsGroupContainerItem *groupCandidate = curMapElement.key(); UBGraphicsGroupContainerItem *groupCandidate = curMapElement.key();
if (groupCandidate) { if (groupCandidate) {
nextGroup = groupCandidate; nextGroup = groupCandidate;
if(!mScene->items().contains(nextGroup)) { if(!mScene->items().contains(nextGroup)) {
mScene->addItem(nextGroup); mScene->addItem(nextGroup);
} }
nextGroup->setVisible(true); nextGroup->setVisible(true);
} }
} }
QGraphicsItem *groupedItem = mScene->itemForUuid(curMapElement.value()); QGraphicsItem *groupedItem = mScene->itemForUuid(curMapElement.value());
if (groupedItem) { if (groupedItem) {
nextGroup->addToGroup(groupedItem); nextGroup->addToGroup(groupedItem);
} }
previousGroupItem = curMapElement.key(); previousGroupItem = curMapElement.key();
UBGraphicsItem::Delegate(nextGroup)->update(); UBGraphicsItem::Delegate(nextGroup)->update();
} }
// force refresh, QT is a bit lazy and take a lot of time (nb item ^2 ?) to trigger repaint // force refresh, QT is a bit lazy and take a lot of time (nb item ^2 ?) to trigger repaint
mScene->update(mScene->sceneRect()); mScene->update(mScene->sceneRect());
} }
void UBGraphicsItemUndoCommand::redo() void UBGraphicsItemUndoCommand::redo()
{ {
// the Undo framework calls a redo while appending the undo command. // the Undo framework calls a redo while appending the undo command.
// as we have already plotted the elements, we do not want to do it twice // as we have already plotted the elements, we do not want to do it twice
if (!mFirstRedo) if (!mFirstRedo)
{ {
if (!mScene){ if (!mScene){
return; return;
} }
QMapIterator<UBGraphicsGroupContainerItem*, QUuid> curMapElement(mExcludedFromGroup); QMapIterator<UBGraphicsGroupContainerItem*, QUuid> curMapElement(mExcludedFromGroup);
UBGraphicsGroupContainerItem *nextGroup = NULL; UBGraphicsGroupContainerItem *nextGroup = NULL;
UBGraphicsGroupContainerItem *previousGroupItem = NULL; UBGraphicsGroupContainerItem *previousGroupItem = NULL;
bool groupChanged = false; bool groupChanged = false;
while (curMapElement.hasNext()) { while (curMapElement.hasNext()) {
curMapElement.next(); curMapElement.next();
groupChanged = previousGroupItem != curMapElement.key(); groupChanged = previousGroupItem != curMapElement.key();
//trying to find the group on the scene; //trying to find the group on the scene;
if (!nextGroup || groupChanged) { if (!nextGroup || groupChanged) {
UBGraphicsGroupContainerItem *groupCandidate = curMapElement.key(); UBGraphicsGroupContainerItem *groupCandidate = curMapElement.key();
if (groupCandidate) { if (groupCandidate) {
nextGroup = groupCandidate; nextGroup = groupCandidate;
} }
} }
QGraphicsItem *groupedItem = mScene->itemForUuid(curMapElement.value()); QGraphicsItem *groupedItem = mScene->itemForUuid(curMapElement.value());
if (groupedItem) { if (groupedItem) {
if (nextGroup->childItems().count() == 1) { if (nextGroup->childItems().count() == 1) {
nextGroup->destroy(false); nextGroup->destroy(false);
break; break;
} }
nextGroup->removeFromGroup(groupedItem); nextGroup->removeFromGroup(groupedItem);
} }
previousGroupItem = curMapElement.key(); previousGroupItem = curMapElement.key();
UBGraphicsItem::Delegate(nextGroup)->update(); UBGraphicsItem::Delegate(nextGroup)->update();
} }
QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems); QSetIterator<QGraphicsItem*> itRemoved(mRemovedItems);
while (itRemoved.hasNext()) while (itRemoved.hasNext())
{ {
QGraphicsItem* item = itRemoved.next(); QGraphicsItem* item = itRemoved.next();
item->setSelected(false); item->setSelected(false);
mScene->removeItem(item); mScene->removeItem(item);
UBApplication::boardController->freezeW3CWidget(item, true); UBApplication::boardController->freezeW3CWidget(item, true);
} }
QSetIterator<QGraphicsItem*> itAdded(mAddedItems); QSetIterator<QGraphicsItem*> itAdded(mAddedItems);
while (itAdded.hasNext()) while (itAdded.hasNext())
{ {
QGraphicsItem* item = itAdded.next(); QGraphicsItem* item = itAdded.next();
if (item) if (item)
{ {
UBApplication::boardController->freezeW3CWidget(item, false); UBApplication::boardController->freezeW3CWidget(item, false);
if (UBItemLayerType::FixedBackground == item->data(UBGraphicsItemData::ItemLayerType)) if (UBItemLayerType::FixedBackground == item->data(UBGraphicsItemData::ItemLayerType))
mScene->setAsBackgroundObject(item); mScene->setAsBackgroundObject(item);
else else
mScene->addItem(item); mScene->addItem(item);
UBGraphicsPolygonItem *polygonItem = qgraphicsitem_cast<UBGraphicsPolygonItem*>(item); UBGraphicsPolygonItem *polygonItem = qgraphicsitem_cast<UBGraphicsPolygonItem*>(item);
if (polygonItem) if (polygonItem)
{ {
mScene->removeItem(polygonItem); mScene->removeItem(polygonItem);
mScene->removeItemFromDeletion(polygonItem); mScene->removeItemFromDeletion(polygonItem);
polygonItem->strokesGroup()->addToGroup(polygonItem); polygonItem->strokesGroup()->addToGroup(polygonItem);
} }
} }
} }
// force refresh, QT is a bit lazy and take a lot of time (nb item ^2) to trigger repaint // force refresh, QT is a bit lazy and take a lot of time (nb item ^2) to trigger repaint
mScene->update(mScene->sceneRect()); mScene->update(mScene->sceneRect());
} }
else else
{ {
mFirstRedo = false; mFirstRedo = false;
} }
} }
...@@ -19,106 +19,106 @@ ...@@ -19,106 +19,106 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBGRAPHICSVIDEOITEMDELEGATE_H_ #ifndef UBGRAPHICSVIDEOITEMDELEGATE_H_
#define UBGRAPHICSVIDEOITEMDELEGATE_H_ #define UBGRAPHICSVIDEOITEMDELEGATE_H_
#include <QtGui> #include <QtGui>
#include <phonon/MediaObject> #include <phonon/MediaObject>
#include "core/UB.h" #include "core/UB.h"
#include "UBGraphicsItemDelegate.h" #include "UBGraphicsItemDelegate.h"
class QGraphicsSceneMouseEvent; class QGraphicsSceneMouseEvent;
class QGraphicsItem; class QGraphicsItem;
class UBGraphicsVideoItem; class UBGraphicsVideoItem;
class DelegateVideoControl: public QGraphicsRectItem class DelegateVideoControl: public QGraphicsRectItem
{ {
public: public:
DelegateVideoControl(UBGraphicsVideoItem* pDelegated, QGraphicsItem * parent = 0); DelegateVideoControl(UBGraphicsVideoItem* pDelegated, QGraphicsItem * parent = 0);
virtual ~DelegateVideoControl() virtual ~DelegateVideoControl()
{ {
// NOOP // NOOP
} }
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget); QWidget *widget);
QPainterPath shape() const; QPainterPath shape() const;
void setAntiScale(qreal antiScale){ mAntiScale = antiScale; } void setAntiScale(qreal antiScale){ mAntiScale = antiScale; }
virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void updateTicker(qint64 time); void updateTicker(qint64 time);
void totalTimeChanged( qint64 newTotalTime); void totalTimeChanged( qint64 newTotalTime);
protected: protected:
void seekToMousePos(QPointF mousePos); void seekToMousePos(QPointF mousePos);
UBGraphicsVideoItem* mDelegate; UBGraphicsVideoItem* mDelegate;
bool mDisplayCurrentTime; bool mDisplayCurrentTime;
qreal mAntiScale; qreal mAntiScale;
qint64 mCurrentTimeInMs; qint64 mCurrentTimeInMs;
qint64 mTotalTimeInMs; qint64 mTotalTimeInMs;
private: private:
int mStartWidth; int mStartWidth;
QRectF mBalloon; QRectF mBalloon;
}; };
class UBGraphicsVideoItemDelegate : public UBGraphicsItemDelegate class UBGraphicsVideoItemDelegate : public UBGraphicsItemDelegate
{ {
Q_OBJECT Q_OBJECT
public: public:
UBGraphicsVideoItemDelegate(UBGraphicsVideoItem* pDelegated, Phonon::MediaObject* pMedia, QObject * parent = 0); UBGraphicsVideoItemDelegate(UBGraphicsVideoItem* pDelegated, Phonon::MediaObject* pMedia, QObject * parent = 0);
virtual ~UBGraphicsVideoItemDelegate(); virtual ~UBGraphicsVideoItemDelegate();
virtual void positionHandles(); virtual void positionHandles();
public slots: public slots:
void toggleMute(); void toggleMute();
void updateTicker(qint64 time); void updateTicker(qint64 time);
protected slots: protected slots:
virtual void remove(bool canUndo = true); virtual void remove(bool canUndo = true);
void togglePlayPause(); void togglePlayPause();
void mediaStateChanged ( Phonon::State newstate, Phonon::State oldstate ); void mediaStateChanged ( Phonon::State newstate, Phonon::State oldstate );
void updatePlayPauseState(); void updatePlayPauseState();
void totalTimeChanged( qint64 newTotalTime); void totalTimeChanged( qint64 newTotalTime);
protected: protected:
virtual void buildButtons(); virtual void buildButtons();
private: private:
UBGraphicsVideoItem* delegated(); UBGraphicsVideoItem* delegated();
DelegateButton* mPlayPauseButton; DelegateButton* mPlayPauseButton;
DelegateButton* mStopButton; DelegateButton* mStopButton;
DelegateButton* mMuteButton; DelegateButton* mMuteButton;
DelegateVideoControl *mVideoControl; DelegateVideoControl *mVideoControl;
Phonon::MediaObject* mMedia; Phonon::MediaObject* mMedia;
}; };
#endif /* UBGRAPHICSVIDEOITEMDELEGATE_H_ */ #endif /* UBGRAPHICSVIDEOITEMDELEGATE_H_ */
...@@ -19,221 +19,221 @@ ...@@ -19,221 +19,221 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBGeometryUtils.h" #include "UBGeometryUtils.h"
#include "core/memcheck.h" #include "core/memcheck.h"
const double PI = 4.0 * atan(1.0); const double PI = 4.0 * atan(1.0);
const int UBGeometryUtils::centimeterGraduationHeight = 15; const int UBGeometryUtils::centimeterGraduationHeight = 15;
const int UBGeometryUtils::halfCentimeterGraduationHeight = 10; const int UBGeometryUtils::halfCentimeterGraduationHeight = 10;
const int UBGeometryUtils::millimeterGraduationHeight = 5; const int UBGeometryUtils::millimeterGraduationHeight = 5;
const int UBGeometryUtils::millimetersPerCentimeter = 10; const int UBGeometryUtils::millimetersPerCentimeter = 10;
const int UBGeometryUtils::millimetersPerHalfCentimeter = 5; const int UBGeometryUtils::millimetersPerHalfCentimeter = 5;
const float UBGeometryUtils::inchSize = 25.4f; const float UBGeometryUtils::inchSize = 25.4f;
UBGeometryUtils::UBGeometryUtils() UBGeometryUtils::UBGeometryUtils()
{ {
// NOOP // NOOP
} }
UBGeometryUtils::~UBGeometryUtils() UBGeometryUtils::~UBGeometryUtils()
{ {
// NOOP // NOOP
} }
QPolygonF UBGeometryUtils::lineToPolygon(const QLineF& pLine, const qreal& pWidth) QPolygonF UBGeometryUtils::lineToPolygon(const QLineF& pLine, const qreal& pWidth)
{ {
qreal x1 = pLine.x1(); qreal x1 = pLine.x1();
qreal y1 = pLine.y1(); qreal y1 = pLine.y1();
qreal x2 = pLine.x2(); qreal x2 = pLine.x2();
qreal y2 = pLine.y2(); qreal y2 = pLine.y2();
qreal alpha = (90.0 - pLine.angle()) * PI / 180.0; qreal alpha = (90.0 - pLine.angle()) * PI / 180.0;
qreal hypothenuse = pWidth / 2; qreal hypothenuse = pWidth / 2;
// TODO UB 4.x PERF cache sin/cos table // TODO UB 4.x PERF cache sin/cos table
qreal opposite = sin(alpha) * hypothenuse; qreal opposite = sin(alpha) * hypothenuse;
qreal adjacent = cos(alpha) * hypothenuse; qreal adjacent = cos(alpha) * hypothenuse;
QPointF p1a(x1 - adjacent, y1 - opposite); QPointF p1a(x1 - adjacent, y1 - opposite);
QPointF p1b(x1 + adjacent, y1 + opposite); QPointF p1b(x1 + adjacent, y1 + opposite);
QPointF p2a(x2 - adjacent, y2 - opposite); QPointF p2a(x2 - adjacent, y2 - opposite);
QPointF p2b(x2 + adjacent, y2 + opposite); QPointF p2b(x2 + adjacent, y2 + opposite);
QPainterPath painterPath; QPainterPath painterPath;
painterPath.moveTo(p1a); painterPath.moveTo(p1a);
painterPath.lineTo(p2a); painterPath.lineTo(p2a);
painterPath.arcTo(x2 - hypothenuse, y2 - hypothenuse, pWidth, pWidth, (90.0 + pLine.angle()), -180.0); painterPath.arcTo(x2 - hypothenuse, y2 - hypothenuse, pWidth, pWidth, (90.0 + pLine.angle()), -180.0);
//painterPath.lineTo(p2b); //painterPath.lineTo(p2b);
painterPath.lineTo(p1b); painterPath.lineTo(p1b);
painterPath.arcTo(x1 - hypothenuse, y1 - hypothenuse, pWidth, pWidth, -1 * (90.0 - pLine.angle()), -180.0); painterPath.arcTo(x1 - hypothenuse, y1 - hypothenuse, pWidth, pWidth, -1 * (90.0 - pLine.angle()), -180.0);
painterPath.closeSubpath(); painterPath.closeSubpath();
return painterPath.toFillPolygon(); return painterPath.toFillPolygon();
} }
QPolygonF UBGeometryUtils::lineToPolygon(const QPointF& pStart, const QPointF& pEnd, QPolygonF UBGeometryUtils::lineToPolygon(const QPointF& pStart, const QPointF& pEnd,
const qreal& pStartWidth, const qreal& pEndWidth) const qreal& pStartWidth, const qreal& pEndWidth)
{ {
qreal x1 = pStart.x(); qreal x1 = pStart.x();
qreal y1 = pStart.y(); qreal y1 = pStart.y();
qreal x2 = pEnd.x(); qreal x2 = pEnd.x();
qreal y2 = pEnd.y(); qreal y2 = pEnd.y();
QLineF line(pStart, pEnd); QLineF line(pStart, pEnd);
qreal alpha = (90.0 - line.angle()) * PI / 180.0; qreal alpha = (90.0 - line.angle()) * PI / 180.0;
qreal hypothenuseStart = pStartWidth / 2; qreal hypothenuseStart = pStartWidth / 2;
qreal hypothenuseEnd = pEndWidth / 2; qreal hypothenuseEnd = pEndWidth / 2;
qreal sinAlpha = sin(alpha); qreal sinAlpha = sin(alpha);
qreal cosAlpha = cos(alpha); qreal cosAlpha = cos(alpha);
// TODO UB 4.x PERF cache sin/cos table // TODO UB 4.x PERF cache sin/cos table
qreal oppositeStart = sinAlpha * hypothenuseStart; qreal oppositeStart = sinAlpha * hypothenuseStart;
qreal adjacentStart = cosAlpha * hypothenuseStart; qreal adjacentStart = cosAlpha * hypothenuseStart;
QPointF p1a(x1 - adjacentStart, y1 - oppositeStart); QPointF p1a(x1 - adjacentStart, y1 - oppositeStart);
QPointF p1b(x1 + adjacentStart, y1 + oppositeStart); QPointF p1b(x1 + adjacentStart, y1 + oppositeStart);
qreal oppositeEnd = sinAlpha * hypothenuseEnd; qreal oppositeEnd = sinAlpha * hypothenuseEnd;
qreal adjacentEnd = cosAlpha * hypothenuseEnd; qreal adjacentEnd = cosAlpha * hypothenuseEnd;
QPointF p2a(x2 - adjacentEnd, y2 - oppositeEnd); QPointF p2a(x2 - adjacentEnd, y2 - oppositeEnd);
QPainterPath painterPath; QPainterPath painterPath;
painterPath.moveTo(p1a); painterPath.moveTo(p1a);
painterPath.lineTo(p2a); painterPath.lineTo(p2a);
painterPath.arcTo(x2 - hypothenuseEnd, y2 - hypothenuseEnd, pEndWidth, pEndWidth, (90.0 + line.angle()), -180.0); painterPath.arcTo(x2 - hypothenuseEnd, y2 - hypothenuseEnd, pEndWidth, pEndWidth, (90.0 + line.angle()), -180.0);
painterPath.lineTo(p1b); painterPath.lineTo(p1b);
painterPath.arcTo(x1 - hypothenuseStart, y1 - hypothenuseStart, pStartWidth, pStartWidth, -1 * (90.0 - line.angle()), -180.0); painterPath.arcTo(x1 - hypothenuseStart, y1 - hypothenuseStart, pStartWidth, pStartWidth, -1 * (90.0 - line.angle()), -180.0);
painterPath.closeSubpath(); painterPath.closeSubpath();
return painterPath.toFillPolygon(); return painterPath.toFillPolygon();
} }
QPolygonF UBGeometryUtils::arcToPolygon(const QLineF& startRadius, qreal spanAngleInDegrees, qreal width) QPolygonF UBGeometryUtils::arcToPolygon(const QLineF& startRadius, qreal spanAngleInDegrees, qreal width)
{ {
qreal startAngleInDegrees = - startRadius.angle(); qreal startAngleInDegrees = - startRadius.angle();
if (startAngleInDegrees > 180) if (startAngleInDegrees > 180)
startAngleInDegrees -= 360; startAngleInDegrees -= 360;
else if (startAngleInDegrees < -180) else if (startAngleInDegrees < -180)
startAngleInDegrees += 360; startAngleInDegrees += 360;
qreal radiusLength = startRadius.length(); qreal radiusLength = startRadius.length();
qreal angle = 2 * asin(width / (2 * radiusLength)) * 180 / PI; qreal angle = 2 * asin(width / (2 * radiusLength)) * 180 / PI;
bool overlap = abs(spanAngleInDegrees) > 360 - angle; bool overlap = abs(spanAngleInDegrees) > 360 - angle;
if (overlap) if (overlap)
spanAngleInDegrees = spanAngleInDegrees < 0 ? -360 : 360; spanAngleInDegrees = spanAngleInDegrees < 0 ? -360 : 360;
qreal endAngleInDegrees = startAngleInDegrees + spanAngleInDegrees; qreal endAngleInDegrees = startAngleInDegrees + spanAngleInDegrees;
qreal innerRadius = radiusLength - width / 2; qreal innerRadius = radiusLength - width / 2;
QRectF innerSquare( QRectF innerSquare(
startRadius.p1().x() - innerRadius, startRadius.p1().x() - innerRadius,
startRadius.p1().y() - innerRadius, startRadius.p1().y() - innerRadius,
2 * innerRadius, 2 * innerRadius,
2 * innerRadius); 2 * innerRadius);
qreal outerRadius = radiusLength + width / 2; qreal outerRadius = radiusLength + width / 2;
QRectF outerSquare( QRectF outerSquare(
startRadius.p1().x() - outerRadius, startRadius.p1().x() - outerRadius,
startRadius.p1().y() - outerRadius, startRadius.p1().y() - outerRadius,
2 * outerRadius, 2 * outerRadius,
2 * outerRadius); 2 * outerRadius);
QRectF startSquare( QRectF startSquare(
startRadius.p2().x() - width / 2, startRadius.p2().x() - width / 2,
startRadius.p2().y() - width / 2, startRadius.p2().y() - width / 2,
width, width,
width); width);
QRectF endSquare( QRectF endSquare(
startRadius.p1().x() + radiusLength * cos(endAngleInDegrees * PI / 180.0) - width / 2, startRadius.p1().x() + radiusLength * cos(endAngleInDegrees * PI / 180.0) - width / 2,
startRadius.p1().y() + radiusLength * sin(endAngleInDegrees * PI / 180.0) - width / 2, startRadius.p1().y() + radiusLength * sin(endAngleInDegrees * PI / 180.0) - width / 2,
width, width,
width); width);
QPainterPath painterPath( QPainterPath painterPath(
QPointF( QPointF(
startRadius.p1().x() + innerRadius * cos(startAngleInDegrees * PI / 180.0), startRadius.p1().x() + innerRadius * cos(startAngleInDegrees * PI / 180.0),
startRadius.p1().y() + innerRadius * sin(startAngleInDegrees * PI / 180.0))); startRadius.p1().y() + innerRadius * sin(startAngleInDegrees * PI / 180.0)));
startAngleInDegrees = - startAngleInDegrees; startAngleInDegrees = - startAngleInDegrees;
endAngleInDegrees = - endAngleInDegrees; endAngleInDegrees = - endAngleInDegrees;
spanAngleInDegrees = - spanAngleInDegrees; spanAngleInDegrees = - spanAngleInDegrees;
if (overlap) if (overlap)
{ {
painterPath.addEllipse(outerSquare); painterPath.addEllipse(outerSquare);
QPainterPath innerPainterPath; QPainterPath innerPainterPath;
innerPainterPath.addEllipse(innerSquare); innerPainterPath.addEllipse(innerSquare);
painterPath = painterPath.subtracted(innerPainterPath); painterPath = painterPath.subtracted(innerPainterPath);
} }
else else
{ {
painterPath.arcTo(innerSquare, startAngleInDegrees, spanAngleInDegrees); painterPath.arcTo(innerSquare, startAngleInDegrees, spanAngleInDegrees);
painterPath.arcTo(endSquare, 180.0 + endAngleInDegrees, spanAngleInDegrees > 0 ? -180.0 : 180.0); painterPath.arcTo(endSquare, 180.0 + endAngleInDegrees, spanAngleInDegrees > 0 ? -180.0 : 180.0);
painterPath.arcTo(outerSquare, endAngleInDegrees, - spanAngleInDegrees); painterPath.arcTo(outerSquare, endAngleInDegrees, - spanAngleInDegrees);
painterPath.arcTo(startSquare, startAngleInDegrees, spanAngleInDegrees > 0 ? -180.0 : 180.0); painterPath.arcTo(startSquare, startAngleInDegrees, spanAngleInDegrees > 0 ? -180.0 : 180.0);
painterPath.closeSubpath(); painterPath.closeSubpath();
} }
return painterPath.toFillPolygon(); return painterPath.toFillPolygon();
} }
QPointF UBGeometryUtils::pointConstrainedInRect(QPointF point, QRectF rect) QPointF UBGeometryUtils::pointConstrainedInRect(QPointF point, QRectF rect)
{ {
return QPointF(qMax(rect.x(), qMin(rect.x() + rect.width(), point.x())), qMax(rect.y(), qMin(rect.y() + rect.height(), point.y()))); return QPointF(qMax(rect.x(), qMin(rect.x() + rect.width(), point.x())), qMax(rect.y(), qMin(rect.y() + rect.height(), point.y())));
} }
QPoint UBGeometryUtils::pointConstrainedInRect(QPoint point, QRect rect) QPoint UBGeometryUtils::pointConstrainedInRect(QPoint point, QRect rect)
{ {
return QPoint(qMax(rect.x(), qMin(rect.x() + rect.width(), point.x())), qMax(rect.y(), qMin(rect.y() + rect.height(), point.y()))); return QPoint(qMax(rect.x(), qMin(rect.x() + rect.width(), point.x())), qMax(rect.y(), qMin(rect.y() + rect.height(), point.y())));
} }
QRectF UBGeometryUtils::lineToInnerRect(const QLineF& pLine, const qreal& pWidth) QRectF UBGeometryUtils::lineToInnerRect(const QLineF& pLine, const qreal& pWidth)
{ {
qreal centerX = (pLine.x1() + pLine.x2()) / 2; qreal centerX = (pLine.x1() + pLine.x2()) / 2;
qreal centerY = (pLine.y1() + pLine.y2()) / 2; qreal centerY = (pLine.y1() + pLine.y2()) / 2;
// Please put a fucking comment here // Please put a fucking comment here
qreal side = sqrt((pWidth * pWidth) / 2); qreal side = sqrt((pWidth * pWidth) / 2);
qreal halfSide = side / 2; qreal halfSide = side / 2;
return QRectF(centerX - halfSide, centerY - halfSide, side, side); return QRectF(centerX - halfSide, centerY - halfSide, side, side);
} }
void UBGeometryUtils::crashPointList(QVector<QPointF> &points) void UBGeometryUtils::crashPointList(QVector<QPointF> &points)
{ {
// QVector<QPointF> result(points); // QVector<QPointF> result(points);
int position = 1; int position = 1;
while(position < points.size()) while(position < points.size())
{ {
if (points.at(position) == points.at(position - 1)) if (points.at(position) == points.at(position - 1))
{ {
points.remove(position); points.remove(position);
} }
else else
{ {
++position; ++position;
} }
} }
} }
...@@ -19,39 +19,39 @@ ...@@ -19,39 +19,39 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBGEOMETRYUTILS_H_ #ifndef UBGEOMETRYUTILS_H_
#define UBGEOMETRYUTILS_H_ #define UBGEOMETRYUTILS_H_
#include <QtGui> #include <QtGui>
class UBGeometryUtils class UBGeometryUtils
{ {
private: private:
UBGeometryUtils(); UBGeometryUtils();
virtual ~UBGeometryUtils(); virtual ~UBGeometryUtils();
public: public:
static QPolygonF lineToPolygon(const QLineF& pLine, const qreal& pWidth); static QPolygonF lineToPolygon(const QLineF& pLine, const qreal& pWidth);
static QRectF lineToInnerRect(const QLineF& pLine, const qreal& pWidth); static QRectF lineToInnerRect(const QLineF& pLine, const qreal& pWidth);
static QPolygonF arcToPolygon(const QLineF& startRadius, qreal spanAngle, qreal width); static QPolygonF arcToPolygon(const QLineF& startRadius, qreal spanAngle, qreal width);
static QPolygonF lineToPolygon(const QPointF& pStart, const QPointF& pEnd, static QPolygonF lineToPolygon(const QPointF& pStart, const QPointF& pEnd,
const qreal& pStartWidth, const qreal& pEndWidth); const qreal& pStartWidth, const qreal& pEndWidth);
static QPointF pointConstrainedInRect(QPointF point, QRectF rect); static QPointF pointConstrainedInRect(QPointF point, QRectF rect);
static QPoint pointConstrainedInRect(QPoint point, QRect rect); static QPoint pointConstrainedInRect(QPoint point, QRect rect);
static void crashPointList(QVector<QPointF> &points); static void crashPointList(QVector<QPointF> &points);
const static int centimeterGraduationHeight; const static int centimeterGraduationHeight;
const static int halfCentimeterGraduationHeight; const static int halfCentimeterGraduationHeight;
const static int millimeterGraduationHeight; const static int millimeterGraduationHeight;
const static int millimetersPerCentimeter; const static int millimetersPerCentimeter;
const static int millimetersPerHalfCentimeter; const static int millimetersPerHalfCentimeter;
const static float inchSize; const static float inchSize;
}; };
#endif /* UBGEOMETRYUTILS_H_ */ #endif /* UBGEOMETRYUTILS_H_ */
...@@ -461,8 +461,8 @@ void UBPlatformUtils::initializeKeyboardLayouts() ...@@ -461,8 +461,8 @@ void UBPlatformUtils::initializeKeyboardLayouts()
int count = CFArrayGetCount(kbds); int count = CFArrayGetCount(kbds);
QList<UBKeyboardLocale*> result; QList<UBKeyboardLocale*> result;
qDebug() << "initializeKeyboardLayouts"; qDebug() << "initializeKeyboardLayouts";
qDebug() << "Found system locales: " << count; qDebug() << "Found system locales: " << count;
for(int i=0; i<count; i++) for(int i=0; i<count; i++)
{ {
...@@ -554,7 +554,7 @@ void UBPlatformUtils::initializeKeyboardLayouts() ...@@ -554,7 +554,7 @@ void UBPlatformUtils::initializeKeyboardLayouts()
const QString resName = ":/images/flags/" + name + ".png"; const QString resName = ":/images/flags/" + name + ".png";
QIcon *iconLang = new QIcon(resName); QIcon *iconLang = new QIcon(resName);
qDebug() << "Locale: " << ID << ", name: " << name; qDebug() << "Locale: " << ID << ", name: " << name;
result.append(new UBKeyboardLocale(fullName, name, ID, iconLang, keybt)); result.append(new UBKeyboardLocale(fullName, name, ID, iconLang, keybt));
} }
......
...@@ -19,271 +19,271 @@ ...@@ -19,271 +19,271 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QList> #include <QList>
#include <QPointF> #include <QPointF>
#include <QPixmap> #include <QPixmap>
#include <QTransform> #include <QTransform>
#include <QScrollBar> #include <QScrollBar>
#include <QFontMetrics> #include <QFontMetrics>
#include <QGraphicsItem> #include <QGraphicsItem>
#include <QGraphicsPixmapItem> #include <QGraphicsPixmapItem>
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "UBDocumentNavigator.h" #include "UBDocumentNavigator.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "adaptors/UBThumbnailAdaptor.h" #include "adaptors/UBThumbnailAdaptor.h"
#include "adaptors/UBSvgSubsetAdaptor.h" #include "adaptors/UBSvgSubsetAdaptor.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "board/UBBoardPaletteManager.h" #include "board/UBBoardPaletteManager.h"
#include "core/UBApplicationController.h" #include "core/UBApplicationController.h"
#include "core/memcheck.h" #include "core/memcheck.h"
/** /**
* \brief Constructor * \brief Constructor
* @param parent as the parent widget * @param parent as the parent widget
* @param name as the object name * @param name as the object name
*/ */
UBDocumentNavigator::UBDocumentNavigator(QWidget *parent, const char *name):QGraphicsView(parent) UBDocumentNavigator::UBDocumentNavigator(QWidget *parent, const char *name):QGraphicsView(parent)
, mScene(NULL) , mScene(NULL)
, mNbColumns(1) , mNbColumns(1)
, mThumbnailWidth(0) , mThumbnailWidth(0)
, mThumbnailMinWidth(100) , mThumbnailMinWidth(100)
{ {
setObjectName(name); setObjectName(name);
mScene = new QGraphicsScene(this); mScene = new QGraphicsScene(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setScene(mScene); setScene(mScene);
mThumbnailWidth = width() - 2*border(); mThumbnailWidth = width() - 2*border();
setFrameShadow(QFrame::Plain); setFrameShadow(QFrame::Plain);
connect(UBApplication::boardController, SIGNAL(documentThumbnailsUpdated(UBDocumentContainer*)), this, SLOT(generateThumbnails(UBDocumentContainer*))); connect(UBApplication::boardController, SIGNAL(documentThumbnailsUpdated(UBDocumentContainer*)), this, SLOT(generateThumbnails(UBDocumentContainer*)));
connect(UBApplication::boardController, SIGNAL(documentPageUpdated(int)), this, SLOT(updateSpecificThumbnail(int))); connect(UBApplication::boardController, SIGNAL(documentPageUpdated(int)), this, SLOT(updateSpecificThumbnail(int)));
connect(UBApplication::boardController, SIGNAL(pageSelectionChanged(int)), this, SLOT(onScrollToSelectedPage(int))); connect(UBApplication::boardController, SIGNAL(pageSelectionChanged(int)), this, SLOT(onScrollToSelectedPage(int)));
} }
/** /**
* \brief Destructor * \brief Destructor
*/ */
UBDocumentNavigator::~UBDocumentNavigator() UBDocumentNavigator::~UBDocumentNavigator()
{ {
if(NULL != mScene) if(NULL != mScene)
{ {
delete mScene; delete mScene;
mScene = NULL; mScene = NULL;
} }
} }
#include "gui/UBDockTeacherGuideWidget.h" #include "gui/UBDockTeacherGuideWidget.h"
#include "gui/UBTeacherGuideWidget.h" #include "gui/UBTeacherGuideWidget.h"
/** /**
* \brief Generate the thumbnails * \brief Generate the thumbnails
*/ */
void UBDocumentNavigator::generateThumbnails(UBDocumentContainer* source) void UBDocumentNavigator::generateThumbnails(UBDocumentContainer* source)
{ {
mThumbsWithLabels.clear(); mThumbsWithLabels.clear();
foreach(QGraphicsItem* it, mScene->items()) foreach(QGraphicsItem* it, mScene->items())
{ {
mScene->removeItem(it); mScene->removeItem(it);
delete it; delete it;
it = NULL; it = NULL;
} }
for(int i = 0; i < source->selectedDocument()->pageCount(); i++) for(int i = 0; i < source->selectedDocument()->pageCount(); i++)
{ {
const QPixmap* pix = source->pageAt(i); const QPixmap* pix = source->pageAt(i);
Q_ASSERT(!pix->isNull()); Q_ASSERT(!pix->isNull());
int pageIndex = UBDocumentContainer::pageFromSceneIndex(i); int pageIndex = UBDocumentContainer::pageFromSceneIndex(i);
UBSceneThumbnailNavigPixmap* pixmapItem = new UBSceneThumbnailNavigPixmap(*pix, source->selectedDocument(), i); UBSceneThumbnailNavigPixmap* pixmapItem = new UBSceneThumbnailNavigPixmap(*pix, source->selectedDocument(), i);
QString label = pageIndex == 0 ? tr("Title page") : tr("Page %0").arg(pageIndex); QString label = pageIndex == 0 ? tr("Title page") : tr("Page %0").arg(pageIndex);
UBThumbnailTextItem *labelItem = new UBThumbnailTextItem(label); UBThumbnailTextItem *labelItem = new UBThumbnailTextItem(label);
UBImgTextThumbnailElement thumbWithText(pixmapItem, labelItem); UBImgTextThumbnailElement thumbWithText(pixmapItem, labelItem);
thumbWithText.setBorder(border()); thumbWithText.setBorder(border());
mThumbsWithLabels.append(thumbWithText); mThumbsWithLabels.append(thumbWithText);
mScene->addItem(pixmapItem); mScene->addItem(pixmapItem);
mScene->addItem(labelItem); mScene->addItem(labelItem);
} }
// Draw the items // Draw the items
refreshScene(); refreshScene();
} }
void UBDocumentNavigator::onScrollToSelectedPage(int index) void UBDocumentNavigator::onScrollToSelectedPage(int index)
{ {
int c = 0; int c = 0;
foreach(UBImgTextThumbnailElement el, mThumbsWithLabels) foreach(UBImgTextThumbnailElement el, mThumbsWithLabels)
{ {
if (c==index) if (c==index)
{ {
el.getThumbnail()->setSelected(true); el.getThumbnail()->setSelected(true);
} }
else else
{ {
el.getThumbnail()->setSelected(false); el.getThumbnail()->setSelected(false);
} }
c++; c++;
} }
} }
/** /**
* \brief Refresh the given thumbnail * \brief Refresh the given thumbnail
* @param iPage as the given page related thumbnail * @param iPage as the given page related thumbnail
*/ */
void UBDocumentNavigator::updateSpecificThumbnail(int iPage) void UBDocumentNavigator::updateSpecificThumbnail(int iPage)
{ {
// Generate the new thumbnail // Generate the new thumbnail
//UBGraphicsScene* pScene = UBApplication::boardController->activeScene(); //UBGraphicsScene* pScene = UBApplication::boardController->activeScene();
const QPixmap* pix = UBApplication::boardController->pageAt(iPage); const QPixmap* pix = UBApplication::boardController->pageAt(iPage);
UBSceneThumbnailNavigPixmap* newItem = new UBSceneThumbnailNavigPixmap(*pix, UBApplication::boardController->selectedDocument(), iPage); UBSceneThumbnailNavigPixmap* newItem = new UBSceneThumbnailNavigPixmap(*pix, UBApplication::boardController->selectedDocument(), iPage);
// Get the old thumbnail // Get the old thumbnail
UBSceneThumbnailNavigPixmap* oldItem = mThumbsWithLabels.at(iPage).getThumbnail(); UBSceneThumbnailNavigPixmap* oldItem = mThumbsWithLabels.at(iPage).getThumbnail();
if(NULL != oldItem) if(NULL != oldItem)
{ {
mScene->removeItem(oldItem); mScene->removeItem(oldItem);
mScene->addItem(newItem); mScene->addItem(newItem);
mThumbsWithLabels[iPage].setThumbnail(newItem); mThumbsWithLabels[iPage].setThumbnail(newItem);
delete oldItem; delete oldItem;
oldItem = NULL; oldItem = NULL;
} }
} }
/** /**
* \brief Put the element in the right place in the scene. * \brief Put the element in the right place in the scene.
*/ */
void UBDocumentNavigator::refreshScene() void UBDocumentNavigator::refreshScene()
{ {
qreal thumbnailHeight = mThumbnailWidth / UBSettings::minScreenRatio; qreal thumbnailHeight = mThumbnailWidth / UBSettings::minScreenRatio;
for(int i = 0; i < mThumbsWithLabels.size(); i++) for(int i = 0; i < mThumbsWithLabels.size(); i++)
{ {
// Get the item // Get the item
UBImgTextThumbnailElement& item = mThumbsWithLabels[i]; UBImgTextThumbnailElement& item = mThumbsWithLabels[i];
int columnIndex = i % mNbColumns; int columnIndex = i % mNbColumns;
int rowIndex = i / mNbColumns; int rowIndex = i / mNbColumns;
item.Place(rowIndex, columnIndex, mThumbnailWidth, thumbnailHeight); item.Place(rowIndex, columnIndex, mThumbnailWidth, thumbnailHeight);
} }
scene()->setSceneRect(scene()->itemsBoundingRect()); scene()->setSceneRect(scene()->itemsBoundingRect());
} }
/** /**
* \brief Set the number of thumbnails columns * \brief Set the number of thumbnails columns
* @param nbColumns as the number of columns * @param nbColumns as the number of columns
*/ */
void UBDocumentNavigator::setNbColumns(int nbColumns) void UBDocumentNavigator::setNbColumns(int nbColumns)
{ {
mNbColumns = nbColumns; mNbColumns = nbColumns;
} }
/** /**
* \brief Get the number of columns * \brief Get the number of columns
* @return the number of thumbnails columns * @return the number of thumbnails columns
*/ */
int UBDocumentNavigator::nbColumns() int UBDocumentNavigator::nbColumns()
{ {
return mNbColumns; return mNbColumns;
} }
/** /**
* \brief Set the thumbnails minimum width * \brief Set the thumbnails minimum width
* @param width as the minimum width * @param width as the minimum width
*/ */
void UBDocumentNavigator::setThumbnailMinWidth(int width) void UBDocumentNavigator::setThumbnailMinWidth(int width)
{ {
mThumbnailMinWidth = width; mThumbnailMinWidth = width;
} }
/** /**
* \brief Get the thumbnails minimum width * \brief Get the thumbnails minimum width
* @return the minimum thumbnails width * @return the minimum thumbnails width
*/ */
int UBDocumentNavigator::thumbnailMinWidth() int UBDocumentNavigator::thumbnailMinWidth()
{ {
return mThumbnailMinWidth; return mThumbnailMinWidth;
} }
/** /**
* \brief Get the border size * \brief Get the border size
* @return the border size in pixels * @return the border size in pixels
*/ */
int UBDocumentNavigator::border() int UBDocumentNavigator::border()
{ {
return 20; return 20;
} }
/** /**
* \brief Handle the resize event * \brief Handle the resize event
* @param event as the resize event * @param event as the resize event
*/ */
void UBDocumentNavigator::resizeEvent(QResizeEvent *event) void UBDocumentNavigator::resizeEvent(QResizeEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
// Update the thumbnails width // Update the thumbnails width
mThumbnailWidth = (width() > mThumbnailMinWidth) ? width() - 2*border() : mThumbnailMinWidth; mThumbnailWidth = (width() > mThumbnailMinWidth) ? width() - 2*border() : mThumbnailMinWidth;
// Refresh the scene // Refresh the scene
refreshScene(); refreshScene();
} }
/** /**
* \brief Handle the mouse press event * \brief Handle the mouse press event
* @param event as the mouse event * @param event as the mouse event
*/ */
void UBDocumentNavigator::mousePressEvent(QMouseEvent *event) void UBDocumentNavigator::mousePressEvent(QMouseEvent *event)
{ {
QGraphicsItem* pClickedItem = itemAt(event->pos()); QGraphicsItem* pClickedItem = itemAt(event->pos());
if(NULL != pClickedItem) if(NULL != pClickedItem)
{ {
// First, select the clicked item // First, select the clicked item
UBSceneThumbnailNavigPixmap* pCrntItem = dynamic_cast<UBSceneThumbnailNavigPixmap*>(pClickedItem); UBSceneThumbnailNavigPixmap* pCrntItem = dynamic_cast<UBSceneThumbnailNavigPixmap*>(pClickedItem);
if(NULL == pCrntItem) if(NULL == pCrntItem)
{ {
// If we fall here we may have clicked on the label instead of the thumbnail // If we fall here we may have clicked on the label instead of the thumbnail
UBThumbnailTextItem* pTextItem = dynamic_cast<UBThumbnailTextItem*>(pClickedItem); UBThumbnailTextItem* pTextItem = dynamic_cast<UBThumbnailTextItem*>(pClickedItem);
if(NULL != pTextItem) if(NULL != pTextItem)
{ {
for(int i = 0; i < mThumbsWithLabels.size(); i++) for(int i = 0; i < mThumbsWithLabels.size(); i++)
{ {
const UBImgTextThumbnailElement& el = mThumbsWithLabels.at(i); const UBImgTextThumbnailElement& el = mThumbsWithLabels.at(i);
if(el.getCaption() == pTextItem) if(el.getCaption() == pTextItem)
{ {
pCrntItem = el.getThumbnail(); pCrntItem = el.getThumbnail();
break; break;
} }
} }
} }
} }
int index = 0; int index = 0;
for(int i = 0; i < mThumbsWithLabels.size(); i++) for(int i = 0; i < mThumbsWithLabels.size(); i++)
{ {
if (mThumbsWithLabels.at(i).getThumbnail() == pCrntItem) if (mThumbsWithLabels.at(i).getThumbnail() == pCrntItem)
{ {
index = i; index = i;
break; break;
} }
} }
UBApplication::boardController->setActiveDocumentScene(index); UBApplication::boardController->setActiveDocumentScene(index);
} }
QGraphicsView::mousePressEvent(event); QGraphicsView::mousePressEvent(event);
} }
void UBDocumentNavigator::mouseReleaseEvent(QMouseEvent *event) void UBDocumentNavigator::mouseReleaseEvent(QMouseEvent *event)
{ {
event->accept(); event->accept();
} }
...@@ -19,63 +19,63 @@ ...@@ -19,63 +19,63 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBDOCUMENTNAVIGATOR_H #ifndef UBDOCUMENTNAVIGATOR_H
#define UBDOCUMENTNAVIGATOR_H #define UBDOCUMENTNAVIGATOR_H
#include <QResizeEvent> #include <QResizeEvent>
#include <QGraphicsView> #include <QGraphicsView>
#include <QGraphicsScene> #include <QGraphicsScene>
#include <QMouseEvent> #include <QMouseEvent>
#include <QThread> #include <QThread>
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "document/UBDocumentContainer.h" #include "document/UBDocumentContainer.h"
#include "UBThumbnailWidget.h" #include "UBThumbnailWidget.h"
#define NO_PAGESELECTED -1 #define NO_PAGESELECTED -1
class UBDocumentNavigator : public QGraphicsView class UBDocumentNavigator : public QGraphicsView
{ {
Q_OBJECT Q_OBJECT
public: public:
UBDocumentNavigator(QWidget* parent=0, const char* name="documentNavigator"); UBDocumentNavigator(QWidget* parent=0, const char* name="documentNavigator");
~UBDocumentNavigator(); ~UBDocumentNavigator();
void setNbColumns(int nbColumns); void setNbColumns(int nbColumns);
int nbColumns(); int nbColumns();
void setThumbnailMinWidth(int width); void setThumbnailMinWidth(int width);
int thumbnailMinWidth(); int thumbnailMinWidth();
public slots: public slots:
void onScrollToSelectedPage(int index);// { if (mCrntItem) centerOn(mCrntItem); } void onScrollToSelectedPage(int index);// { if (mCrntItem) centerOn(mCrntItem); }
void generateThumbnails(UBDocumentContainer* source); void generateThumbnails(UBDocumentContainer* source);
void updateSpecificThumbnail(int iPage); void updateSpecificThumbnail(int iPage);
protected: protected:
virtual void resizeEvent(QResizeEvent *event); virtual void resizeEvent(QResizeEvent *event);
virtual void mousePressEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event);
private: private:
void refreshScene(); void refreshScene();
int border(); int border();
/** The scene */ /** The scene */
QGraphicsScene* mScene; QGraphicsScene* mScene;
/** The current selected item */ /** The current selected item */
//UBSceneThumbnailNavigPixmap* mCrntItem; //UBSceneThumbnailNavigPixmap* mCrntItem;
/** The list of current thumbnails with labels*/ /** The list of current thumbnails with labels*/
QList<UBImgTextThumbnailElement> mThumbsWithLabels; QList<UBImgTextThumbnailElement> mThumbsWithLabels;
/** The current number of columns */ /** The current number of columns */
int mNbColumns; int mNbColumns;
/** The current thumbnails width */ /** The current thumbnails width */
int mThumbnailWidth; int mThumbnailWidth;
/** The current thumbnails minimum width */ /** The current thumbnails minimum width */
int mThumbnailMinWidth; int mThumbnailMinWidth;
}; };
#endif // UBDOCUMENTNAVIGATOR_H #endif // UBDOCUMENTNAVIGATOR_H
...@@ -19,305 +19,305 @@ ...@@ -19,305 +19,305 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBDocumentThumbnailWidget.h" #include "UBDocumentThumbnailWidget.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBMimeData.h" #include "core/UBMimeData.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentThumbnailWidget::UBDocumentThumbnailWidget(QWidget* parent) UBDocumentThumbnailWidget::UBDocumentThumbnailWidget(QWidget* parent)
: UBThumbnailWidget(parent) : UBThumbnailWidget(parent)
, mDropCaretRectItem(0) , mDropCaretRectItem(0)
, mClosestDropItem(0) , mClosestDropItem(0)
, mDragEnabled(true) , mDragEnabled(true)
, mScrollMagnitude(0) , mScrollMagnitude(0)
{ {
bCanDrag = false; bCanDrag = false;
mScrollTimer = new QTimer(this); mScrollTimer = new QTimer(this);
connect(mScrollTimer, SIGNAL(timeout()), this, SLOT(autoScroll())); connect(mScrollTimer, SIGNAL(timeout()), this, SLOT(autoScroll()));
} }
UBDocumentThumbnailWidget::~UBDocumentThumbnailWidget() UBDocumentThumbnailWidget::~UBDocumentThumbnailWidget()
{ {
// NOOP // NOOP
} }
void UBDocumentThumbnailWidget::mouseMoveEvent(QMouseEvent *event) void UBDocumentThumbnailWidget::mouseMoveEvent(QMouseEvent *event)
{ {
if (!dragEnabled()) if (!dragEnabled())
{ {
event->ignore(); event->ignore();
return; return;
} }
if (!(event->buttons() & Qt::LeftButton)) if (!(event->buttons() & Qt::LeftButton))
return; return;
if ((event->pos() - mMousePressPos).manhattanLength() < QApplication::startDragDistance()) if ((event->pos() - mMousePressPos).manhattanLength() < QApplication::startDragDistance())
return; return;
QList<QGraphicsItem*> graphicsItems = items(mMousePressPos); QList<QGraphicsItem*> graphicsItems = items(mMousePressPos);
UBSceneThumbnailPixmap* sceneItem = 0; UBSceneThumbnailPixmap* sceneItem = 0;
while (!graphicsItems.isEmpty() && !sceneItem) while (!graphicsItems.isEmpty() && !sceneItem)
sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(graphicsItems.takeFirst()); sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(graphicsItems.takeFirst());
if (sceneItem) if (sceneItem)
{ {
int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneItem->sceneIndex()); int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneItem->sceneIndex());
if(pageIndex != 0){ if(pageIndex != 0){
QDrag *drag = new QDrag(this); QDrag *drag = new QDrag(this);
QList<UBMimeDataItem> mimeDataItems; QList<UBMimeDataItem> mimeDataItems;
foreach (QGraphicsItem *item, selectedItems()) foreach (QGraphicsItem *item, selectedItems())
mimeDataItems.append(UBMimeDataItem(sceneItem->proxy(), mGraphicItems.indexOf(item))); mimeDataItems.append(UBMimeDataItem(sceneItem->proxy(), mGraphicItems.indexOf(item)));
UBMimeData *mime = new UBMimeData(mimeDataItems); UBMimeData *mime = new UBMimeData(mimeDataItems);
drag->setMimeData(mime); drag->setMimeData(mime);
drag->setPixmap(sceneItem->pixmap().scaledToWidth(100)); drag->setPixmap(sceneItem->pixmap().scaledToWidth(100));
drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height() / 2)); drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height() / 2));
drag->exec(Qt::MoveAction); drag->exec(Qt::MoveAction);
} }
} }
UBThumbnailWidget::mouseMoveEvent(event); UBThumbnailWidget::mouseMoveEvent(event);
} }
void UBDocumentThumbnailWidget::dragEnterEvent(QDragEnterEvent *event) void UBDocumentThumbnailWidget::dragEnterEvent(QDragEnterEvent *event)
{ {
if (!event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage)) if (!event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage))
{ {
event->setDropAction(Qt::IgnoreAction); event->setDropAction(Qt::IgnoreAction);
event->ignore(); event->ignore();
return; return;
} }
UBThumbnailWidget::dragEnterEvent(event); UBThumbnailWidget::dragEnterEvent(event);
} }
void UBDocumentThumbnailWidget::dragLeaveEvent(QDragLeaveEvent *event) void UBDocumentThumbnailWidget::dragLeaveEvent(QDragLeaveEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
if (mScrollTimer->isActive()) if (mScrollTimer->isActive())
{ {
mScrollMagnitude = 0; mScrollMagnitude = 0;
mScrollTimer->stop(); mScrollTimer->stop();
} }
deleteDropCaret(); deleteDropCaret();
UBThumbnailWidget::dragLeaveEvent(event); UBThumbnailWidget::dragLeaveEvent(event);
} }
void UBDocumentThumbnailWidget::autoScroll() void UBDocumentThumbnailWidget::autoScroll()
{ {
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + mScrollMagnitude); this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + mScrollMagnitude);
} }
void UBDocumentThumbnailWidget::dragMoveEvent(QDragMoveEvent *event) void UBDocumentThumbnailWidget::dragMoveEvent(QDragMoveEvent *event)
{ {
QRect boundingFrame = frameRect(); QRect boundingFrame = frameRect();
//setting up automatic scrolling //setting up automatic scrolling
const int SCROLL_DISTANCE = 16; const int SCROLL_DISTANCE = 16;
int bottomDist = boundingFrame.bottom() - event->pos().y(), topDist = boundingFrame.top() - event->pos().y(); int bottomDist = boundingFrame.bottom() - event->pos().y(), topDist = boundingFrame.top() - event->pos().y();
if(qAbs(bottomDist) <= SCROLL_DISTANCE) if(qAbs(bottomDist) <= SCROLL_DISTANCE)
{ {
mScrollMagnitude = (SCROLL_DISTANCE - bottomDist)*4; mScrollMagnitude = (SCROLL_DISTANCE - bottomDist)*4;
if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100); if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100);
} }
else if(qAbs(topDist) <= SCROLL_DISTANCE) else if(qAbs(topDist) <= SCROLL_DISTANCE)
{ {
mScrollMagnitude = (- SCROLL_DISTANCE - topDist)*4; mScrollMagnitude = (- SCROLL_DISTANCE - topDist)*4;
if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100); if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100);
} }
else else
{ {
mScrollMagnitude = 0; mScrollMagnitude = 0;
mScrollTimer->stop(); mScrollTimer->stop();
} }
QList<UBSceneThumbnailPixmap*> pixmapItems; QList<UBSceneThumbnailPixmap*> pixmapItems;
foreach (QGraphicsItem *item, scene()->items(mapToScene(boundingFrame))) foreach (QGraphicsItem *item, scene()->items(mapToScene(boundingFrame)))
{ {
UBSceneThumbnailPixmap* sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(item); UBSceneThumbnailPixmap* sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(item);
if (sceneItem) if (sceneItem)
pixmapItems.append(sceneItem); pixmapItems.append(sceneItem);
} }
int minDistance = 0; int minDistance = 0;
QGraphicsItem *underlyingItem = itemAt(event->pos()); QGraphicsItem *underlyingItem = itemAt(event->pos());
mClosestDropItem = dynamic_cast<UBSceneThumbnailPixmap*>(underlyingItem); mClosestDropItem = dynamic_cast<UBSceneThumbnailPixmap*>(underlyingItem);
int pageIndex = -1; int pageIndex = -1;
if(mClosestDropItem){ if(mClosestDropItem){
pageIndex = UBDocumentContainer::pageFromSceneIndex(mClosestDropItem->sceneIndex()); pageIndex = UBDocumentContainer::pageFromSceneIndex(mClosestDropItem->sceneIndex());
if(pageIndex == 0){ if(pageIndex == 0){
event->acceptProposedAction(); event->acceptProposedAction();
return; return;
} }
} }
if (!mClosestDropItem) if (!mClosestDropItem)
{ {
foreach (UBSceneThumbnailPixmap *item, pixmapItems) foreach (UBSceneThumbnailPixmap *item, pixmapItems)
{ {
qreal scale = item->transform().m11(); qreal scale = item->transform().m11();
QPointF itemCenter( QPointF itemCenter(
item->pos().x() + item->boundingRect().width() * scale / 2, item->pos().x() + item->boundingRect().width() * scale / 2,
item->pos().y() + item->boundingRect().height() * scale / 2); item->pos().y() + item->boundingRect().height() * scale / 2);
int distance = (itemCenter.toPoint() - mapToScene(event->pos()).toPoint()).manhattanLength(); int distance = (itemCenter.toPoint() - mapToScene(event->pos()).toPoint()).manhattanLength();
if (!mClosestDropItem || distance < minDistance) if (!mClosestDropItem || distance < minDistance)
{ {
mClosestDropItem = item; mClosestDropItem = item;
minDistance = distance; minDistance = distance;
pageIndex = UBDocumentContainer::pageFromSceneIndex(mClosestDropItem->sceneIndex()); pageIndex = UBDocumentContainer::pageFromSceneIndex(mClosestDropItem->sceneIndex());
} }
} }
} }
if (mClosestDropItem && pageIndex != 0) if (mClosestDropItem && pageIndex != 0)
{ {
qreal scale = mClosestDropItem->transform().m11(); qreal scale = mClosestDropItem->transform().m11();
QPointF itemCenter( QPointF itemCenter(
mClosestDropItem->pos().x() + mClosestDropItem->boundingRect().width() * scale / 2, mClosestDropItem->pos().x() + mClosestDropItem->boundingRect().width() * scale / 2,
mClosestDropItem->pos().y() + mClosestDropItem->boundingRect().height() * scale / 2); mClosestDropItem->pos().y() + mClosestDropItem->boundingRect().height() * scale / 2);
mDropIsRight = mapToScene(event->pos()).x() > itemCenter.x(); mDropIsRight = mapToScene(event->pos()).x() > itemCenter.x();
if (!mDropCaretRectItem && selectedItems().count() < mGraphicItems.count()) if (!mDropCaretRectItem && selectedItems().count() < mGraphicItems.count())
{ {
mDropCaretRectItem = new QGraphicsRectItem(0, scene()); mDropCaretRectItem = new QGraphicsRectItem(0, scene());
mDropCaretRectItem->setPen(QPen(Qt::darkGray)); mDropCaretRectItem->setPen(QPen(Qt::darkGray));
mDropCaretRectItem->setBrush(QBrush(Qt::lightGray)); mDropCaretRectItem->setBrush(QBrush(Qt::lightGray));
} }
QRectF dropCaretRect( QRectF dropCaretRect(
mDropIsRight ? mClosestDropItem->pos().x() + mClosestDropItem->boundingRect().width() * scale + spacing() / 2 - 1 : mClosestDropItem->pos().x() - spacing() / 2 - 1, mDropIsRight ? mClosestDropItem->pos().x() + mClosestDropItem->boundingRect().width() * scale + spacing() / 2 - 1 : mClosestDropItem->pos().x() - spacing() / 2 - 1,
mClosestDropItem->pos().y(), mClosestDropItem->pos().y(),
3, 3,
mClosestDropItem->boundingRect().height() * scale); mClosestDropItem->boundingRect().height() * scale);
if (mDropCaretRectItem) if (mDropCaretRectItem)
mDropCaretRectItem->setRect(dropCaretRect); mDropCaretRectItem->setRect(dropCaretRect);
} }
event->acceptProposedAction(); event->acceptProposedAction();
} }
void UBDocumentThumbnailWidget::dropEvent(QDropEvent *event) void UBDocumentThumbnailWidget::dropEvent(QDropEvent *event)
{ {
if (mScrollTimer->isActive()) if (mScrollTimer->isActive())
{ {
mScrollMagnitude = 0; mScrollMagnitude = 0;
mScrollTimer->stop(); mScrollTimer->stop();
} }
deleteDropCaret(); deleteDropCaret();
if (mClosestDropItem) if (mClosestDropItem)
{ {
int targetIndex = mDropIsRight ? mGraphicItems.indexOf(mClosestDropItem) + 1 : mGraphicItems.indexOf(mClosestDropItem); int targetIndex = mDropIsRight ? mGraphicItems.indexOf(mClosestDropItem) + 1 : mGraphicItems.indexOf(mClosestDropItem);
if(UBDocumentContainer::pageFromSceneIndex(targetIndex) == 0){ if(UBDocumentContainer::pageFromSceneIndex(targetIndex) == 0){
event->ignore(); event->ignore();
return; return;
} }
QList<UBMimeDataItem> mimeDataItems; QList<UBMimeDataItem> mimeDataItems;
if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage)) if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage))
{ {
const UBMimeData* mimeData = qobject_cast<const UBMimeData*>(event->mimeData()); const UBMimeData* mimeData = qobject_cast<const UBMimeData*>(event->mimeData());
if (mimeData) if (mimeData)
mimeDataItems = mimeData->items(); mimeDataItems = mimeData->items();
} }
if (1 == mimeDataItems.count() && if (1 == mimeDataItems.count() &&
(mimeDataItems.at(0).sceneIndex() == mGraphicItems.indexOf(mClosestDropItem) || (mimeDataItems.at(0).sceneIndex() == mGraphicItems.indexOf(mClosestDropItem) ||
targetIndex == mimeDataItems.at(0).sceneIndex() || targetIndex == mimeDataItems.at(0).sceneIndex() ||
targetIndex == mimeDataItems.at(0).sceneIndex() + 1)) targetIndex == mimeDataItems.at(0).sceneIndex() + 1))
{ {
return; return;
} }
int sourceIndexOffset = 0; int sourceIndexOffset = 0;
int actualTargetIndex = targetIndex; int actualTargetIndex = targetIndex;
for (int i = mimeDataItems.count() - 1; i >= 0; i--) for (int i = mimeDataItems.count() - 1; i >= 0; i--)
{ {
UBMimeDataItem sourceItem = mimeDataItems.at(i); UBMimeDataItem sourceItem = mimeDataItems.at(i);
int actualSourceIndex = sourceItem.sceneIndex(); int actualSourceIndex = sourceItem.sceneIndex();
if (sourceItem.sceneIndex() >= targetIndex) if (sourceItem.sceneIndex() >= targetIndex)
actualSourceIndex += sourceIndexOffset; actualSourceIndex += sourceIndexOffset;
//event->acceptProposedAction(); //event->acceptProposedAction();
if (sourceItem.sceneIndex() < targetIndex) if (sourceItem.sceneIndex() < targetIndex)
{ {
if (actualSourceIndex != actualTargetIndex - 1) if (actualSourceIndex != actualTargetIndex - 1)
emit sceneDropped(sourceItem.documentProxy(), actualSourceIndex, actualTargetIndex - 1); emit sceneDropped(sourceItem.documentProxy(), actualSourceIndex, actualTargetIndex - 1);
actualTargetIndex -= 1; actualTargetIndex -= 1;
} }
else else
{ {
if (actualSourceIndex != actualTargetIndex) if (actualSourceIndex != actualTargetIndex)
emit sceneDropped(sourceItem.documentProxy(), actualSourceIndex, actualTargetIndex); emit sceneDropped(sourceItem.documentProxy(), actualSourceIndex, actualTargetIndex);
sourceIndexOffset += 1; sourceIndexOffset += 1;
} }
} }
} }
UBThumbnailWidget::dropEvent(event); UBThumbnailWidget::dropEvent(event);
} }
void UBDocumentThumbnailWidget::deleteDropCaret() void UBDocumentThumbnailWidget::deleteDropCaret()
{ {
if (mDropCaretRectItem && scene()) if (mDropCaretRectItem && scene())
{ {
scene()->removeItem(mDropCaretRectItem); scene()->removeItem(mDropCaretRectItem);
delete mDropCaretRectItem; delete mDropCaretRectItem;
mDropCaretRectItem = 0; mDropCaretRectItem = 0;
} }
} }
void UBDocumentThumbnailWidget::setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems, void UBDocumentThumbnailWidget::setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems,
const QList<QUrl>& pItemPaths, const QStringList pLabels, const QList<QUrl>& pItemPaths, const QStringList pLabels,
const QString& pMimeType) const QString& pMimeType)
{ {
deleteDropCaret(); deleteDropCaret();
UBThumbnailWidget::setGraphicsItems(pGraphicsItems, pItemPaths, pLabels, pMimeType); UBThumbnailWidget::setGraphicsItems(pGraphicsItems, pItemPaths, pLabels, pMimeType);
} }
void UBDocumentThumbnailWidget::setDragEnabled(bool enabled) void UBDocumentThumbnailWidget::setDragEnabled(bool enabled)
{ {
mDragEnabled = enabled; mDragEnabled = enabled;
} }
bool UBDocumentThumbnailWidget::dragEnabled() const bool UBDocumentThumbnailWidget::dragEnabled() const
{ {
return mDragEnabled; return mDragEnabled;
} }
void UBDocumentThumbnailWidget::hightlightItem(int index) void UBDocumentThumbnailWidget::hightlightItem(int index)
{ {
if (0 <= index && index < mLabelsItems.length()) if (0 <= index && index < mLabelsItems.length())
{ {
mLabelsItems.at(index)->highlight(); mLabelsItems.at(index)->highlight();
} }
if (0 <= index && index < mGraphicItems.length()) if (0 <= index && index < mGraphicItems.length())
{ {
UBSceneThumbnailPixmap *thumbnail = dynamic_cast<UBSceneThumbnailPixmap*>(mGraphicItems.at(index)); UBSceneThumbnailPixmap *thumbnail = dynamic_cast<UBSceneThumbnailPixmap*>(mGraphicItems.at(index));
if (thumbnail) if (thumbnail)
thumbnail->highlight(); thumbnail->highlight();
} }
selectItemAt(index); selectItemAt(index);
} }
...@@ -19,447 +19,447 @@ ...@@ -19,447 +19,447 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBDocumentTreeWidget.h" #include "UBDocumentTreeWidget.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "core/UBPersistenceManager.h" #include "core/UBPersistenceManager.h"
#include "core/UBMimeData.h" #include "core/UBMimeData.h"
#include "core/UBApplicationController.h" #include "core/UBApplicationController.h"
#include "core/UBDocumentManager.h" #include "core/UBDocumentManager.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentController.h"
#include "adaptors/UBThumbnailAdaptor.h" #include "adaptors/UBThumbnailAdaptor.h"
#include "adaptors/UBSvgSubsetAdaptor.h" #include "adaptors/UBSvgSubsetAdaptor.h"
#include "frameworks/UBFileSystemUtils.h" #include "frameworks/UBFileSystemUtils.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBDocumentTreeWidget::UBDocumentTreeWidget(QWidget * parent) UBDocumentTreeWidget::UBDocumentTreeWidget(QWidget * parent)
: QTreeWidget(parent) : QTreeWidget(parent)
, mSelectedProxyTi(0) , mSelectedProxyTi(0)
, mDropTargetProxyTi(0) , mDropTargetProxyTi(0)
{ {
setDragDropMode(QAbstractItemView::InternalMove); setDragDropMode(QAbstractItemView::InternalMove);
setAutoScroll(true); setAutoScroll(true);
mScrollTimer = new QTimer(this); mScrollTimer = new QTimer(this);
connect(UBDocumentManager::documentManager(), SIGNAL(documentUpdated(UBDocumentProxy*)) connect(UBDocumentManager::documentManager(), SIGNAL(documentUpdated(UBDocumentProxy*))
, this, SLOT(documentUpdated(UBDocumentProxy*))); , this, SLOT(documentUpdated(UBDocumentProxy*)));
connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)) connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int))
, this, SLOT(itemChangedValidation(QTreeWidgetItem *, int))); , this, SLOT(itemChangedValidation(QTreeWidgetItem *, int)));
connect(mScrollTimer, SIGNAL(timeout()) connect(mScrollTimer, SIGNAL(timeout())
, this, SLOT(autoScroll())); , this, SLOT(autoScroll()));
} }
UBDocumentTreeWidget::~UBDocumentTreeWidget() UBDocumentTreeWidget::~UBDocumentTreeWidget()
{ {
// NOOP // NOOP
} }
void UBDocumentTreeWidget::itemChangedValidation(QTreeWidgetItem * item, int column) void UBDocumentTreeWidget::itemChangedValidation(QTreeWidgetItem * item, int column)
{ {
if (column == 0) if (column == 0)
{ {
UBDocumentGroupTreeItem *group = dynamic_cast< UBDocumentGroupTreeItem *>(item); UBDocumentGroupTreeItem *group = dynamic_cast< UBDocumentGroupTreeItem *>(item);
if (group) if (group)
{ {
QString name = group->text(0); QString name = group->text(0);
for(int i = 0; i < topLevelItemCount (); i++) for(int i = 0; i < topLevelItemCount (); i++)
{ {
QTreeWidgetItem *someTopLevelItem = topLevelItem(i); QTreeWidgetItem *someTopLevelItem = topLevelItem(i);
if (someTopLevelItem != group && if (someTopLevelItem != group &&
someTopLevelItem->text(0) == name) someTopLevelItem->text(0) == name)
{ {
group->setText(0, tr("%1 (copy)").arg(name)); group->setText(0, tr("%1 (copy)").arg(name));
} }
} }
} }
} }
} }
Qt::DropActions UBDocumentTreeWidget::supportedDropActions() const Qt::DropActions UBDocumentTreeWidget::supportedDropActions() const
{ {
return Qt::MoveAction | Qt::CopyAction; return Qt::MoveAction | Qt::CopyAction;
} }
void UBDocumentTreeWidget::mousePressEvent(QMouseEvent *event) void UBDocumentTreeWidget::mousePressEvent(QMouseEvent *event)
{ {
QTreeWidgetItem* twItem = this->itemAt(event->pos()); QTreeWidgetItem* twItem = this->itemAt(event->pos());
mSelectedProxyTi = dynamic_cast<UBDocumentProxyTreeItem*>(twItem); mSelectedProxyTi = dynamic_cast<UBDocumentProxyTreeItem*>(twItem);
QTreeWidget::mousePressEvent(event); QTreeWidget::mousePressEvent(event);
} }
void UBDocumentTreeWidget::dragEnterEvent(QDragEnterEvent *event) void UBDocumentTreeWidget::dragEnterEvent(QDragEnterEvent *event)
{ {
event->acceptProposedAction(); event->acceptProposedAction();
} }
void UBDocumentTreeWidget::dragLeaveEvent(QDragLeaveEvent *event) void UBDocumentTreeWidget::dragLeaveEvent(QDragLeaveEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
if (mScrollTimer->isActive()) if (mScrollTimer->isActive())
{ {
mScrollMagnitude = 0; mScrollMagnitude = 0;
mScrollTimer->stop(); mScrollTimer->stop();
} }
if (mDropTargetProxyTi) if (mDropTargetProxyTi)
{ {
mDropTargetProxyTi->setBackground(0, mBackground); mDropTargetProxyTi->setBackground(0, mBackground);
mDropTargetProxyTi = 0; mDropTargetProxyTi = 0;
} }
} }
void UBDocumentTreeWidget::dragMoveEvent(QDragMoveEvent *event) void UBDocumentTreeWidget::dragMoveEvent(QDragMoveEvent *event)
{ {
QRect boundingFrame = frameRect(); QRect boundingFrame = frameRect();
//setting up automatic scrolling //setting up automatic scrolling
const int SCROLL_DISTANCE = 4; const int SCROLL_DISTANCE = 4;
int bottomDist = boundingFrame.bottom() - event->pos().y(), topDist = boundingFrame.top() - event->pos().y(); int bottomDist = boundingFrame.bottom() - event->pos().y(), topDist = boundingFrame.top() - event->pos().y();
if(qAbs(bottomDist) <= SCROLL_DISTANCE) if(qAbs(bottomDist) <= SCROLL_DISTANCE)
{ {
mScrollMagnitude = (SCROLL_DISTANCE - bottomDist)*4; mScrollMagnitude = (SCROLL_DISTANCE - bottomDist)*4;
if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100); if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100);
} }
else if(qAbs(topDist) <= SCROLL_DISTANCE) else if(qAbs(topDist) <= SCROLL_DISTANCE)
{ {
mScrollMagnitude = (- SCROLL_DISTANCE - topDist)*4; mScrollMagnitude = (- SCROLL_DISTANCE - topDist)*4;
if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100); if(verticalScrollBar()->isVisible() && !mScrollTimer->isActive()) mScrollTimer->start(100);
} }
else else
{ {
mScrollMagnitude = 0; mScrollMagnitude = 0;
mScrollTimer->stop(); mScrollTimer->stop();
} }
QTreeWidgetItem* underlyingItem = this->itemAt(event->pos()); QTreeWidgetItem* underlyingItem = this->itemAt(event->pos());
if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage)) if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage))
{ {
UBDocumentProxyTreeItem *targetProxyTreeItem = dynamic_cast<UBDocumentProxyTreeItem*>(underlyingItem); UBDocumentProxyTreeItem *targetProxyTreeItem = dynamic_cast<UBDocumentProxyTreeItem*>(underlyingItem);
if (targetProxyTreeItem && targetProxyTreeItem != mSelectedProxyTi) if (targetProxyTreeItem && targetProxyTreeItem != mSelectedProxyTi)
{ {
event->setDropAction(Qt::CopyAction); event->setDropAction(Qt::CopyAction);
event->accept(); event->accept();
} }
else else
{ {
event->ignore(); event->ignore();
} }
} }
else else
{ {
UBDocumentGroupTreeItem *groupItem = dynamic_cast<UBDocumentGroupTreeItem*>(underlyingItem); UBDocumentGroupTreeItem *groupItem = dynamic_cast<UBDocumentGroupTreeItem*>(underlyingItem);
if (groupItem && mSelectedProxyTi && groupItem != mSelectedProxyTi->parent()) if (groupItem && mSelectedProxyTi && groupItem != mSelectedProxyTi->parent())
event->acceptProposedAction(); event->acceptProposedAction();
else else
event->ignore(); event->ignore();
} }
if (event->isAccepted()) if (event->isAccepted())
{ {
if (mDropTargetProxyTi) if (mDropTargetProxyTi)
{ {
if (underlyingItem != mDropTargetProxyTi) if (underlyingItem != mDropTargetProxyTi)
{ {
mBackground = underlyingItem->background(0); mBackground = underlyingItem->background(0);
mDropTargetProxyTi->setBackground(0, mBackground); mDropTargetProxyTi->setBackground(0, mBackground);
mDropTargetProxyTi = underlyingItem; mDropTargetProxyTi = underlyingItem;
mDropTargetProxyTi->setBackground(0, QBrush(QColor("#6682b5"))); mDropTargetProxyTi->setBackground(0, QBrush(QColor("#6682b5")));
} }
} }
else else
{ {
mBackground = underlyingItem->background(0); mBackground = underlyingItem->background(0);
mDropTargetProxyTi = underlyingItem; mDropTargetProxyTi = underlyingItem;
mDropTargetProxyTi->setBackground(0, QBrush(QColor("#6682b5"))); mDropTargetProxyTi->setBackground(0, QBrush(QColor("#6682b5")));
} }
} }
else if (mDropTargetProxyTi) else if (mDropTargetProxyTi)
{ {
mDropTargetProxyTi->setBackground(0, mBackground); mDropTargetProxyTi->setBackground(0, mBackground);
mDropTargetProxyTi = 0; mDropTargetProxyTi = 0;
} }
} }
void UBDocumentTreeWidget::focusInEvent(QFocusEvent *event) void UBDocumentTreeWidget::focusInEvent(QFocusEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
// Tolik // Tolik
//itemSelectionChanged(); //itemSelectionChanged();
QTreeWidget::focusInEvent(event); QTreeWidget::focusInEvent(event);
} }
void UBDocumentTreeWidget::dropEvent(QDropEvent *event) void UBDocumentTreeWidget::dropEvent(QDropEvent *event)
{ {
if (mDropTargetProxyTi) if (mDropTargetProxyTi)
{ {
mDropTargetProxyTi->setBackground(0, mBackground); mDropTargetProxyTi->setBackground(0, mBackground);
mDropTargetProxyTi = 0; mDropTargetProxyTi = 0;
} }
QTreeWidgetItem* underlyingItem = this->itemAt(event->pos()); QTreeWidgetItem* underlyingItem = this->itemAt(event->pos());
UBDocumentGroupTreeItem *groupItem = dynamic_cast<UBDocumentGroupTreeItem*>(underlyingItem); UBDocumentGroupTreeItem *groupItem = dynamic_cast<UBDocumentGroupTreeItem*>(underlyingItem);
if (groupItem && mSelectedProxyTi && mSelectedProxyTi->proxy()) if (groupItem && mSelectedProxyTi && mSelectedProxyTi->proxy())
{ {
UBDocumentGroupTreeItem *sourceGroupItem = dynamic_cast<UBDocumentGroupTreeItem*>(mSelectedProxyTi->parent()); UBDocumentGroupTreeItem *sourceGroupItem = dynamic_cast<UBDocumentGroupTreeItem*>(mSelectedProxyTi->parent());
bool isTrashItem = sourceGroupItem && sourceGroupItem->isTrashFolder(); bool isTrashItem = sourceGroupItem && sourceGroupItem->isTrashFolder();
if ((isTrashItem && !groupItem->isTrashFolder()) || if ((isTrashItem && !groupItem->isTrashFolder()) ||
(!isTrashItem && mSelectedProxyTi->proxy()->groupName() != groupItem->groupName())) (!isTrashItem && mSelectedProxyTi->proxy()->groupName() != groupItem->groupName()))
{ {
QString groupName; QString groupName;
if (groupItem->isTrashFolder()) if (groupItem->isTrashFolder())
{ {
QString oldGroupName = mSelectedProxyTi->proxy()->metaData(UBSettings::documentGroupName).toString(); QString oldGroupName = mSelectedProxyTi->proxy()->metaData(UBSettings::documentGroupName).toString();
groupName = UBSettings::trashedDocumentGroupNamePrefix + oldGroupName; groupName = UBSettings::trashedDocumentGroupNamePrefix + oldGroupName;
} }
else else
{ {
if (groupItem->groupName() == UBApplication::app()->documentController->defaultDocumentGroupName()) if (groupItem->groupName() == UBApplication::app()->documentController->defaultDocumentGroupName())
groupName = ""; groupName = "";
else else
groupName = groupItem->groupName(); groupName = groupItem->groupName();
} }
mSelectedProxyTi->proxy()->setMetaData(UBSettings::documentGroupName, groupName); mSelectedProxyTi->proxy()->setMetaData(UBSettings::documentGroupName, groupName);
UBPersistenceManager::persistenceManager()->persistDocumentMetadata(mSelectedProxyTi->proxy()); UBPersistenceManager::persistenceManager()->persistDocumentMetadata(mSelectedProxyTi->proxy());
mSelectedProxyTi->parent()->removeChild(mSelectedProxyTi); mSelectedProxyTi->parent()->removeChild(mSelectedProxyTi);
int i = 0; int i = 0;
for (i = 0; i < groupItem->childCount(); i++) for (i = 0; i < groupItem->childCount(); i++)
{ {
QTreeWidgetItem *ti = groupItem->child(i); QTreeWidgetItem *ti = groupItem->child(i);
UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti); UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti);
if (pi) if (pi)
{ {
if (mSelectedProxyTi->proxy()->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString()) if (mSelectedProxyTi->proxy()->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString())
{ {
break; break;
} }
} }
} }
groupItem->insertChild(i, mSelectedProxyTi); groupItem->insertChild(i, mSelectedProxyTi);
if (isTrashItem) if (isTrashItem)
mSelectedProxyTi->setFlags(mSelectedProxyTi->flags() | Qt::ItemIsEditable); mSelectedProxyTi->setFlags(mSelectedProxyTi->flags() | Qt::ItemIsEditable);
if (groupItem->isTrashFolder()) if (groupItem->isTrashFolder())
mSelectedProxyTi->setFlags(mSelectedProxyTi->flags() ^ Qt::ItemIsEditable); mSelectedProxyTi->setFlags(mSelectedProxyTi->flags() ^ Qt::ItemIsEditable);
//clearSelection(); //clearSelection();
expandItem(groupItem); expandItem(groupItem);
scrollToItem(mSelectedProxyTi); scrollToItem(mSelectedProxyTi);
// disabled, as those 2 calls are buggy on windows, the item disappears if we selected them // disabled, as those 2 calls are buggy on windows, the item disappears if we selected them
// //
setCurrentItem(mSelectedProxyTi); setCurrentItem(mSelectedProxyTi);
mSelectedProxyTi->setSelected(true); mSelectedProxyTi->setSelected(true);
event->setDropAction(Qt::IgnoreAction); event->setDropAction(Qt::IgnoreAction);
event->accept(); event->accept();
} }
} }
else else
{ {
QTreeWidgetItem* underlyingTreeItem = this->itemAt(event->pos()); QTreeWidgetItem* underlyingTreeItem = this->itemAt(event->pos());
UBDocumentProxyTreeItem *targetProxyTreeItem = dynamic_cast<UBDocumentProxyTreeItem*>(underlyingTreeItem); UBDocumentProxyTreeItem *targetProxyTreeItem = dynamic_cast<UBDocumentProxyTreeItem*>(underlyingTreeItem);
if (targetProxyTreeItem && targetProxyTreeItem != mSelectedProxyTi) if (targetProxyTreeItem && targetProxyTreeItem != mSelectedProxyTi)
{ {
if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage)) if (event->mimeData()->hasFormat(UBApplication::mimeTypeUniboardPage))
{ {
event->setDropAction(Qt::CopyAction); event->setDropAction(Qt::CopyAction);
event->accept(); event->accept();
const UBMimeData *mimeData = qobject_cast <const UBMimeData*>(event->mimeData()); const UBMimeData *mimeData = qobject_cast <const UBMimeData*>(event->mimeData());
if (mimeData && mimeData->items().size() > 0) if (mimeData && mimeData->items().size() > 0)
{ {
int count = 0; int count = 0;
int total = mimeData->items().size(); int total = mimeData->items().size();
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
foreach (UBMimeDataItem sourceItem, mimeData->items()) foreach (UBMimeDataItem sourceItem, mimeData->items())
{ {
count++; count++;
UBApplication::applicationController->showMessage(tr("Copying page %1/%2").arg(count).arg(total), true); UBApplication::applicationController->showMessage(tr("Copying page %1/%2").arg(count).arg(total), true);
// TODO UB 4.x Move following code to some controller class // TODO UB 4.x Move following code to some controller class
UBGraphicsScene *scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(sourceItem.documentProxy(), sourceItem.sceneIndex()); UBGraphicsScene *scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(sourceItem.documentProxy(), sourceItem.sceneIndex());
if (scene) if (scene)
{ {
UBGraphicsScene* sceneClone = scene->sceneDeepCopy(); UBGraphicsScene* sceneClone = scene->sceneDeepCopy();
UBDocumentProxy *targetDocProxy = targetProxyTreeItem->proxy(); UBDocumentProxy *targetDocProxy = targetProxyTreeItem->proxy();
foreach (QUrl relativeFile, scene->relativeDependencies()) foreach (QUrl relativeFile, scene->relativeDependencies())
{ {
QString source = scene->document()->persistencePath() + "/" + relativeFile.toString(); QString source = scene->document()->persistencePath() + "/" + relativeFile.toString();
QString target = targetDocProxy->persistencePath() + "/" + relativeFile.toString(); QString target = targetDocProxy->persistencePath() + "/" + relativeFile.toString();
QFileInfo fi(target); QFileInfo fi(target);
QDir d = fi.dir(); QDir d = fi.dir();
d.mkpath(d.absolutePath()); d.mkpath(d.absolutePath());
QFile::copy(source, target); QFile::copy(source, target);
} }
UBPersistenceManager::persistenceManager()->insertDocumentSceneAt(targetDocProxy, sceneClone, targetDocProxy->pageCount()); UBPersistenceManager::persistenceManager()->insertDocumentSceneAt(targetDocProxy, sceneClone, targetDocProxy->pageCount());
//due to incorrect generation of thumbnails of invisible scene I've used direct copying of thumbnail files //due to incorrect generation of thumbnails of invisible scene I've used direct copying of thumbnail files
//it's not universal and good way but it's faster //it's not universal and good way but it's faster
QString from = sourceItem.documentProxy()->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", sourceItem.sceneIndex()); QString from = sourceItem.documentProxy()->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", sourceItem.sceneIndex());
QString to = targetDocProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", targetDocProxy->pageCount()); QString to = targetDocProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", targetDocProxy->pageCount());
QFile::remove(to); QFile::remove(to);
QFile::copy(from, to); QFile::copy(from, to);
} }
} }
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
UBApplication::applicationController->showMessage(tr("%1 pages copied", "", total).arg(total), false); UBApplication::applicationController->showMessage(tr("%1 pages copied", "", total).arg(total), false);
} }
} }
else else
{ {
event->setDropAction(Qt::IgnoreAction); event->setDropAction(Qt::IgnoreAction);
event->ignore(); event->ignore();
} }
} }
} }
} }
void UBDocumentTreeWidget::documentUpdated(UBDocumentProxy *pDocument) void UBDocumentTreeWidget::documentUpdated(UBDocumentProxy *pDocument)
{ {
UBDocumentProxyTreeItem *treeItem = UBApplication::documentController->findDocument(pDocument); UBDocumentProxyTreeItem *treeItem = UBApplication::documentController->findDocument(pDocument);
if (treeItem) if (treeItem)
{ {
QTreeWidgetItem * parent = treeItem->parent(); QTreeWidgetItem * parent = treeItem->parent();
if (parent) if (parent)
{ {
for (int i = 0; i < parent->indexOfChild(treeItem); i++) for (int i = 0; i < parent->indexOfChild(treeItem); i++)
{ {
QTreeWidgetItem *ti = parent->child(i); QTreeWidgetItem *ti = parent->child(i);
UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti); UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti);
if (pi) if (pi)
{ {
if (pDocument->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString()) if (pDocument->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString())
{ {
bool selected = treeItem->isSelected(); bool selected = treeItem->isSelected();
parent->removeChild(treeItem); parent->removeChild(treeItem);
parent->insertChild(i, treeItem); parent->insertChild(i, treeItem);
for (int j = 0; j < selectedItems().count(); j++) for (int j = 0; j < selectedItems().count(); j++)
selectedItems().at(j)->setSelected(false); selectedItems().at(j)->setSelected(false);
if (selected) if (selected)
treeItem->setSelected(true); treeItem->setSelected(true);
break; break;
} }
} }
} }
} }
} }
} }
UBDocumentProxyTreeItem::UBDocumentProxyTreeItem(QTreeWidgetItem * parent, UBDocumentProxy* proxy, bool isEditable) UBDocumentProxyTreeItem::UBDocumentProxyTreeItem(QTreeWidgetItem * parent, UBDocumentProxy* proxy, bool isEditable)
: QTreeWidgetItem() : QTreeWidgetItem()
, mProxy(proxy) , mProxy(proxy)
{ {
Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled; Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled;
if (isEditable) if (isEditable)
flags |= Qt::ItemIsEditable; flags |= Qt::ItemIsEditable;
setFlags(flags); setFlags(flags);
int i = 0; int i = 0;
for (i = 0; i < parent->childCount(); i++) for (i = 0; i < parent->childCount(); i++)
{ {
QTreeWidgetItem *ti = parent->child(i); QTreeWidgetItem *ti = parent->child(i);
UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti); UBDocumentProxyTreeItem* pi = dynamic_cast<UBDocumentProxyTreeItem*>(ti);
if (pi) if (pi)
{ {
if (proxy->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString()) if (proxy->metaData(UBSettings::documentUpdatedAt).toString() >= pi->proxy()->metaData(UBSettings::documentUpdatedAt).toString())
{ {
break; break;
} }
} }
} }
parent->insertChild(i, this); parent->insertChild(i, this);
} }
UBDocumentGroupTreeItem::UBDocumentGroupTreeItem(QTreeWidgetItem *parent, bool isEditable) UBDocumentGroupTreeItem::UBDocumentGroupTreeItem(QTreeWidgetItem *parent, bool isEditable)
: QTreeWidgetItem(parent) : QTreeWidgetItem(parent)
{ {
Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled; Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
if (isEditable) if (isEditable)
flags |= Qt::ItemIsEditable; flags |= Qt::ItemIsEditable;
setFlags(flags); setFlags(flags);
} }
UBDocumentGroupTreeItem::~UBDocumentGroupTreeItem() UBDocumentGroupTreeItem::~UBDocumentGroupTreeItem()
{ {
// NOOP // NOOP
} }
void UBDocumentGroupTreeItem::setGroupName(const QString& groupName) void UBDocumentGroupTreeItem::setGroupName(const QString& groupName)
{ {
setText(0, groupName); setText(0, groupName);
} }
QString UBDocumentGroupTreeItem::groupName() const QString UBDocumentGroupTreeItem::groupName() const
{ {
return text(0); return text(0);
} }
bool UBDocumentGroupTreeItem::isTrashFolder() const bool UBDocumentGroupTreeItem::isTrashFolder() const
{ {
return (0 == (flags() & Qt::ItemIsEditable)) && UBApplication::app()->documentController && (groupName() == UBApplication::app()->documentController->documentTrashGroupName()); return (0 == (flags() & Qt::ItemIsEditable)) && UBApplication::app()->documentController && (groupName() == UBApplication::app()->documentController->documentTrashGroupName());
} }
bool UBDocumentGroupTreeItem::isDefaultFolder() const bool UBDocumentGroupTreeItem::isDefaultFolder() const
{ {
return (0 == (flags() & Qt::ItemIsEditable)) && UBApplication::app()->documentController && (groupName() == UBApplication::app()->documentController->defaultDocumentGroupName()); return (0 == (flags() & Qt::ItemIsEditable)) && UBApplication::app()->documentController && (groupName() == UBApplication::app()->documentController->defaultDocumentGroupName());
} }
void UBDocumentTreeWidget::autoScroll() void UBDocumentTreeWidget::autoScroll()
{ {
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + mScrollMagnitude); this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + mScrollMagnitude);
} }
...@@ -19,726 +19,726 @@ ...@@ -19,726 +19,726 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QtGui> #include <QtGui>
#include <QList> #include <QList>
#include <QSize> #include <QSize>
#include "UBKeyboardPalette.h" #include "UBKeyboardPalette.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "gui/UBMainWindow.h" #include "gui/UBMainWindow.h"
#include "core/memcheck.h" #include "core/memcheck.h"
/* /*
UBKeyboardPalette UBKeyboardPalette
*/ */
UBKeyboardPalette::UBKeyboardPalette(QWidget *parent) UBKeyboardPalette::UBKeyboardPalette(QWidget *parent)
: UBActionPalette(Qt::TopRightCorner, parent) : UBActionPalette(Qt::TopRightCorner, parent)
{ {
// setWindowFlags(/*Qt::CustomizeWindowHint|*/Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint); // setWindowFlags(/*Qt::CustomizeWindowHint|*/Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);
setCustomCloseProcessing(true); setCustomCloseProcessing(true);
setCustomPosition(true); setCustomPosition(true);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setFocusPolicy(Qt::NoFocus); setFocusPolicy(Qt::NoFocus);
setClosable(true); setClosable(true);
setGrip(false); setGrip(false);
capsLock = false; capsLock = false;
shift = false; shift = false;
languagePopupActive = false; languagePopupActive = false;
keyboardActive = false; keyboardActive = false;
nSpecialModifierIndex = 0; nSpecialModifierIndex = 0;
specialModifier = 0; specialModifier = 0;
btnWidth = btnHeight = 16; btnWidth = btnHeight = 16;
strSize = "16x16"; strSize = "16x16";
currBtnImages = new BTNImages("16", btnWidth, btnHeight); currBtnImages = new BTNImages("16", btnWidth, btnHeight);
storage = NULL; storage = NULL;
buttons = new UBKeyButton*[47]; buttons = new UBKeyButton*[47];
for (int i=0; i<47; i++) for (int i=0; i<47; i++)
{ {
buttons[i] = new UBKeyButton(this); buttons[i] = new UBKeyButton(this);
} }
locales = UBPlatformUtils::getKeyboardLayouts(this->nLocalesCount); locales = UBPlatformUtils::getKeyboardLayouts(this->nLocalesCount);
createCtrlButtons(); createCtrlButtons();
nCurrentLocale = UBSettings::settings()->KeyboardLocale->get().toInt(); nCurrentLocale = UBSettings::settings()->KeyboardLocale->get().toInt();
if (nCurrentLocale < 0 || nCurrentLocale >= nLocalesCount) if (nCurrentLocale < 0 || nCurrentLocale >= nLocalesCount)
nCurrentLocale = 0; nCurrentLocale = 0;
if (locales!=NULL) if (locales!=NULL)
setInput(locales[nCurrentLocale]); setInput(locales[nCurrentLocale]);
setContentsMargins( 22, 22, 22, 22 ); setContentsMargins( 22, 22, 22, 22 );
init(); init();
} }
//QList<UBKeyboardPalette*> UBKeyboardPalette::instances; //QList<UBKeyboardPalette*> UBKeyboardPalette::instances;
void UBKeyboardPalette::init() void UBKeyboardPalette::init()
{ {
m_isVisible = false; m_isVisible = false;
setVisible(false); setVisible(false);
setKeyButtonSize(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize->get().toString()); setKeyButtonSize(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize->get().toString());
connect(this, SIGNAL(keyboardActivated(bool)), this, SLOT(onActivated(bool))); connect(this, SIGNAL(keyboardActivated(bool)), this, SLOT(onActivated(bool)));
connect(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize, SIGNAL(changed(QVariant)), this, SLOT(keyboardPaletteButtonSizeChanged(QVariant))); connect(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize, SIGNAL(changed(QVariant)), this, SLOT(keyboardPaletteButtonSizeChanged(QVariant)));
connect(UBApplication::mainWindow->actionVirtualKeyboard, SIGNAL(triggered(bool)), this, SLOT(showKeyboard(bool))); connect(UBApplication::mainWindow->actionVirtualKeyboard, SIGNAL(triggered(bool)), this, SLOT(showKeyboard(bool)));
connect(this, SIGNAL(closed()), this, SLOT(hideKeyboard())); connect(this, SIGNAL(closed()), this, SLOT(hideKeyboard()));
//------------------------------// //------------------------------//
UBPlatformUtils::setWindowNonActivableFlag(this, true); UBPlatformUtils::setWindowNonActivableFlag(this, true);
} }
void UBKeyboardPalette::showKeyboard(bool show) void UBKeyboardPalette::showKeyboard(bool show)
{ {
m_isVisible = show; m_isVisible = show;
} }
void UBKeyboardPalette::hideKeyboard() void UBKeyboardPalette::hideKeyboard()
{ {
UBApplication::mainWindow->actionVirtualKeyboard->activate(QAction::Trigger); UBApplication::mainWindow->actionVirtualKeyboard->activate(QAction::Trigger);
} }
void UBKeyboardPalette::syncPosition(const QPoint & pos) void UBKeyboardPalette::syncPosition(const QPoint & pos)
{ {
m_pos = pos; m_pos = pos;
move(pos); move(pos);
} }
void UBKeyboardPalette::syncLocale(int nLocale) void UBKeyboardPalette::syncLocale(int nLocale)
{ {
nCurrentLocale = nLocale; nCurrentLocale = nLocale;
setInput(locales[nCurrentLocale]); setInput(locales[nCurrentLocale]);
} }
void UBKeyboardPalette::keyboardPaletteButtonSizeChanged(QVariant size) void UBKeyboardPalette::keyboardPaletteButtonSizeChanged(QVariant size)
{ {
setKeyButtonSize(size.toString()); setKeyButtonSize(size.toString());
} }
void UBKeyboardPalette::setInput(const UBKeyboardLocale* locale) void UBKeyboardPalette::setInput(const UBKeyboardLocale* locale)
{ {
if (locale!=NULL) if (locale!=NULL)
{ {
for (int i=0; i<47; i++) for (int i=0; i<47; i++)
buttons[i]->setKeyBt((*locale)[i]); buttons[i]->setKeyBt((*locale)[i]);
} }
else else
{ {
this->hide(); this->hide();
} }
} }
UBKeyboardPalette::~UBKeyboardPalette() UBKeyboardPalette::~UBKeyboardPalette()
{ {
//for (int i=0; i<47; i++) //for (int i=0; i<47; i++)
// delete buttons[i]; // delete buttons[i];
delete [] buttons; delete [] buttons;
//for (int i=0; i<8; i++) //for (int i=0; i<8; i++)
// delete ctrlButtons[i]; // delete ctrlButtons[i];
delete [] ctrlButtons; delete [] ctrlButtons;
//if (locales!=NULL) //if (locales!=NULL)
//{ //{
// for (int i=0; i<nLocalesCount; i++) // for (int i=0; i<nLocalesCount; i++)
// delete locales[i]; // delete locales[i];
// delete [] locales; // delete [] locales;
//} //}
if(currBtnImages != NULL) if(currBtnImages != NULL)
{ {
delete currBtnImages; delete currBtnImages;
currBtnImages = NULL; currBtnImages = NULL;
} }
onActivated(false); onActivated(false);
} }
QSize UBKeyboardPalette::sizeHint () const QSize UBKeyboardPalette::sizeHint () const
{ {
int w = contentsMargins().left() + 15 * btnWidth + contentsMargins().right(); int w = contentsMargins().left() + 15 * btnWidth + contentsMargins().right();
int h = contentsMargins().top() + 5 * btnHeight + contentsMargins().bottom(); int h = contentsMargins().top() + 5 * btnHeight + contentsMargins().bottom();
return QSize(w, h); return QSize(w, h);
} }
const QString* UBKeyboardPalette::getLocaleName() const QString* UBKeyboardPalette::getLocaleName()
{ {
return locales == NULL ? NULL : &(locales[nCurrentLocale]->name); return locales == NULL ? NULL : &(locales[nCurrentLocale]->name);
} }
void UBKeyboardPalette::setLocale(int nLocale) void UBKeyboardPalette::setLocale(int nLocale)
{ {
if (locales != NULL) if (locales != NULL)
{ {
nCurrentLocale = nLocale; nCurrentLocale = nLocale;
setInput(locales[nCurrentLocale]); setInput(locales[nCurrentLocale]);
onLocaleChanged(locales[nCurrentLocale]); onLocaleChanged(locales[nCurrentLocale]);
update(); update();
UBSettings::settings()->KeyboardLocale->set(nCurrentLocale); UBSettings::settings()->KeyboardLocale->set(nCurrentLocale);
} }
emit localeChanged(nLocale); emit localeChanged(nLocale);
} }
void UBKeyboardPalette::setKeyButtonSize(const QString& _strSize) void UBKeyboardPalette::setKeyButtonSize(const QString& _strSize)
{ {
QStringList strs = _strSize.split('x'); QStringList strs = _strSize.split('x');
if (strs.size()==2) if (strs.size()==2)
{ {
strSize = _strSize; strSize = _strSize;
btnWidth = strs[0].toInt(); btnWidth = strs[0].toInt();
btnHeight = strs[1].toInt(); btnHeight = strs[1].toInt();
if(currBtnImages != NULL) if(currBtnImages != NULL)
delete currBtnImages; delete currBtnImages;
currBtnImages = new BTNImages(strs[1], btnWidth, btnHeight); currBtnImages = new BTNImages(strs[1], btnWidth, btnHeight);
adjustSizeAndPosition(); adjustSizeAndPosition();
} }
} }
void UBKeyboardPalette::enterEvent ( QEvent * ) void UBKeyboardPalette::enterEvent ( QEvent * )
{ {
if (keyboardActive) if (keyboardActive)
return; return;
keyboardActive = true; keyboardActive = true;
adjustSizeAndPosition(); adjustSizeAndPosition();
emit keyboardActivated(true); emit keyboardActivated(true);
} }
void UBKeyboardPalette::leaveEvent ( QEvent * ) void UBKeyboardPalette::leaveEvent ( QEvent * )
{ {
if (languagePopupActive || !keyboardActive || mIsMoving) if (languagePopupActive || !keyboardActive || mIsMoving)
return; return;
keyboardActive = false; keyboardActive = false;
adjustSizeAndPosition(); adjustSizeAndPosition();
emit keyboardActivated(false); emit keyboardActivated(false);
} }
void UBKeyboardPalette::moveEvent ( QMoveEvent * event ) void UBKeyboardPalette::moveEvent ( QMoveEvent * event )
{ {
UBActionPalette::moveEvent(event); UBActionPalette::moveEvent(event);
emit moved(event->pos()); emit moved(event->pos());
} }
void UBKeyboardPalette::adjustSizeAndPosition(bool pUp) void UBKeyboardPalette::adjustSizeAndPosition(bool pUp)
{ {
QSize rSize = sizeHint(); QSize rSize = sizeHint();
if (rSize != size()) if (rSize != size())
{ {
int dx = (rSize.width() - size().width()) /2; int dx = (rSize.width() - size().width()) /2;
int dy = rSize.height() - size().height(); int dy = rSize.height() - size().height();
this->move(x()-dx, y() - dy); this->move(x()-dx, y() - dy);
this->resize(rSize.width(), rSize.height()); this->resize(rSize.width(), rSize.height());
} }
UBActionPalette::adjustSizeAndPosition(pUp); UBActionPalette::adjustSizeAndPosition(pUp);
} }
void UBKeyboardPalette::paintEvent( QPaintEvent* event) void UBKeyboardPalette::paintEvent( QPaintEvent* event)
{ {
checkLayout(); checkLayout();
UBActionPalette::paintEvent(event); UBActionPalette::paintEvent(event);
QRect r = this->geometry(); QRect r = this->geometry();
int lleft, ltop, lright, lbottom; int lleft, ltop, lright, lbottom;
getContentsMargins ( &lleft, &ltop, &lright, &lbottom ) ; getContentsMargins ( &lleft, &ltop, &lright, &lbottom ) ;
//------------------------------------------------ //------------------------------------------------
// calculate start offset from left, and from top // calculate start offset from left, and from top
int ctrlButtonsId = 0; int ctrlButtonsId = 0;
lleft = ( r.width() - btnWidth * 15 ) / 2; lleft = ( r.width() - btnWidth * 15 ) / 2;
ltop = ( r.height() - btnHeight * 5 ) / 2; ltop = ( r.height() - btnHeight * 5 ) / 2;
//------------------------------------------------ //------------------------------------------------
// set geometry (position) for row 1 // set geometry (position) for row 1
int offX = lleft; int offX = lleft;
int offY = ltop; int offY = ltop;
//------------------- //-------------------
// buttons [`]..[+] // buttons [`]..[+]
for (int i = 0; i<13; i++) for (int i = 0; i<13; i++)
{ {
buttons[i]->setGeometry(offX, offY, btnWidth, btnHeight); buttons[i]->setGeometry(offX, offY, btnWidth, btnHeight);
offX += btnWidth; offX += btnWidth;
} }
// button Backspace // button Backspace
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight);
offX += btnWidth * 2; offX += btnWidth * 2;
//------------------------------------------------ //------------------------------------------------
// set geometry (position) for row 2 // set geometry (position) for row 2
offX = lleft; offX = lleft;
offY += btnHeight; offY += btnHeight;
offX += btnWidth / 2; offX += btnWidth / 2;
//------------------- //-------------------
// button Tab // button Tab
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight);
offX += btnWidth * 2; offX += btnWidth * 2;
// buttons [q]..[]] // buttons [q]..[]]
for (int i = 0; i<12; i++) for (int i = 0; i<12; i++)
{ {
buttons[i + 13]->setGeometry(offX, offY, btnWidth, btnHeight); buttons[i + 13]->setGeometry(offX, offY, btnWidth, btnHeight);
offX += btnWidth; offX += btnWidth;
} }
// // Row 2 Stub // // Row 2 Stub
// ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1.5, btnHeight); // ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1.5, btnHeight);
// offX += btnWidth * 1.5; // offX += btnWidth * 1.5;
//------------------------------------------------ //------------------------------------------------
// set geometry (position) for row 3 // set geometry (position) for row 3
offX = lleft; offX = lleft;
offY += btnHeight; offY += btnHeight;
//------------------- //-------------------
// // Row 3 Stub // // Row 3 Stub
// button Enter // button Enter
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1, btnHeight);
offX += btnWidth*1; offX += btnWidth*1;
// buttons [a]..[\] // buttons [a]..[\]
for (int i = 0; i < 12; i++) for (int i = 0; i < 12; i++)
{ {
buttons[i + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight); buttons[i + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight);
offX += btnWidth; offX += btnWidth;
} }
// button Enter // button Enter
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight);
offX += btnWidth*2; offX += btnWidth*2;
//------------------------------------------------ //------------------------------------------------
// set geometry (position) for row 4 // set geometry (position) for row 4
offX = lleft; offX = lleft;
offY += btnHeight; offY += btnHeight;
//------------------- //-------------------
// button LCapsLock // button LCapsLock
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight);
offX += btnWidth*2.5; offX += btnWidth*2.5;
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
buttons[i + 12 + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight); buttons[i + 12 + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight);
offX += btnWidth; offX += btnWidth;
} }
// button RCapsLock // button RCapsLock
ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight);
offX += btnWidth*2.5; offX += btnWidth*2.5;
//------------------------------------------------ //------------------------------------------------
// set geometry (position) for row 5 // set geometry (position) for row 5
offX = lleft; offX = lleft;
offY += btnHeight; offY += btnHeight;
//------------------- //-------------------
ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 1 , offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 1 , offY, btnWidth * 2, btnHeight);
ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 3 , offY, btnWidth * 9, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 3 , offY, btnWidth * 9, btnHeight);
ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 12, offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 12, offY, btnWidth * 2, btnHeight);
//------------------------------------------------ //------------------------------------------------
} }
void UBKeyboardPalette::onDeactivated() void UBKeyboardPalette::onDeactivated()
{ {
onActivated(false); onActivated(false);
} }
//-----------------------------------------------------------------------// //-----------------------------------------------------------------------//
// BTNImages Class // BTNImages Class
//-----------------------------------------------------------------------// //-----------------------------------------------------------------------//
BTNImages::BTNImages(QString strHeight, int width, int height) BTNImages::BTNImages(QString strHeight, int width, int height)
{ {
m_strHeight = strHeight; m_strHeight = strHeight;
m_width = width; m_width = width;
m_height = height; m_height = height;
m_strLeftPassive = ":/images/virtual.keyboard/" + strHeight + "/left-passive.png"; m_strLeftPassive = ":/images/virtual.keyboard/" + strHeight + "/left-passive.png";
m_strCenterPassive = ":/images/virtual.keyboard/" + strHeight + "/centre-passive.png"; m_strCenterPassive = ":/images/virtual.keyboard/" + strHeight + "/centre-passive.png";
m_strRightPassive = ":/images/virtual.keyboard/" + strHeight + "/right-passive.png"; m_strRightPassive = ":/images/virtual.keyboard/" + strHeight + "/right-passive.png";
m_strLeftActive = ":/images/virtual.keyboard/" + strHeight + "/left-active.png"; m_strLeftActive = ":/images/virtual.keyboard/" + strHeight + "/left-active.png";
m_strCenterActive = ":/images/virtual.keyboard/" + strHeight + "/centre-active.png"; m_strCenterActive = ":/images/virtual.keyboard/" + strHeight + "/centre-active.png";
m_strRightActive = ":/images/virtual.keyboard/" + strHeight + "/right-active.png"; m_strRightActive = ":/images/virtual.keyboard/" + strHeight + "/right-active.png";
m_btnLeftPassive = QImage(m_strLeftPassive); m_btnLeftPassive = QImage(m_strLeftPassive);
m_btnCenterPassive = QImage(m_strCenterPassive); m_btnCenterPassive = QImage(m_strCenterPassive);
m_btnRightPassive = QImage(m_strRightPassive); m_btnRightPassive = QImage(m_strRightPassive);
m_btnLeftActive = QImage(m_strLeftActive); m_btnLeftActive = QImage(m_strLeftActive);
m_btnCenterActive = QImage(m_strCenterActive); m_btnCenterActive = QImage(m_strCenterActive);
m_btnRightActive = QImage(m_strRightActive); m_btnRightActive = QImage(m_strRightActive);
} }
ContentImage::ContentImage(QString strHeight, int height, QString strContentName) ContentImage::ContentImage(QString strHeight, int height, QString strContentName)
{ {
m_strHeight = strHeight; m_strHeight = strHeight;
m_height = height; m_height = height;
m_strContent = ":/images/virtual.keyboard/" + strHeight + "/" + strContentName + ".png"; m_strContent = ":/images/virtual.keyboard/" + strHeight + "/" + strContentName + ".png";
m_btnContent = QImage(m_strContent); m_btnContent = QImage(m_strContent);
} }
//-----------------------------------------------------------------------// //-----------------------------------------------------------------------//
// UBKeyboardButton Class // UBKeyboardButton Class
//-----------------------------------------------------------------------// //-----------------------------------------------------------------------//
UBKeyboardButton::UBKeyboardButton(UBKeyboardPalette* parent, QString contentImagePath = "") UBKeyboardButton::UBKeyboardButton(UBKeyboardPalette* parent, QString contentImagePath = "")
:QWidget(parent), :QWidget(parent),
keyboard(parent), keyboard(parent),
bFocused(false), bFocused(false),
bPressed(false) bPressed(false)
{ {
m_parent = parent; m_parent = parent;
m_contentImagePath = contentImagePath; m_contentImagePath = contentImagePath;
imgContent = NULL; imgContent = NULL;
setCursor(Qt::PointingHandCursor); setCursor(Qt::PointingHandCursor);
} }
UBKeyboardButton::~UBKeyboardButton() UBKeyboardButton::~UBKeyboardButton()
{ {
if(imgContent != NULL) if(imgContent != NULL)
{ {
delete imgContent; delete imgContent;
imgContent = NULL; imgContent = NULL;
} }
} }
bool UBKeyboardButton::isPressed() bool UBKeyboardButton::isPressed()
{ {
return bPressed; return bPressed;
} }
void UBKeyboardButton::paintEvent(QPaintEvent*) void UBKeyboardButton::paintEvent(QPaintEvent*)
{ {
QPainter painter(this); QPainter painter(this);
//-------------------------- //--------------------------
if(imgContent != NULL) if(imgContent != NULL)
{ {
if(imgContent->m_height != m_parent->currBtnImages->m_height) if(imgContent->m_height != m_parent->currBtnImages->m_height)
{ {
delete imgContent; delete imgContent;
if(!m_contentImagePath.isEmpty()) if(!m_contentImagePath.isEmpty())
imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath); imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath);
} }
} }
else else
if(!m_contentImagePath.isEmpty()) if(!m_contentImagePath.isEmpty())
imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath); imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath);
//-------------------------- //--------------------------
if (isPressed()) if (isPressed())
{ {
painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftActive, 0,0, m_parent->currBtnImages->m_btnLeftActive.width(), m_parent->currBtnImages->m_btnLeftActive.height() ); painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftActive, 0,0, m_parent->currBtnImages->m_btnLeftActive.width(), m_parent->currBtnImages->m_btnLeftActive.height() );
painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftActive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftActive.width() - m_parent->currBtnImages->m_btnRightActive.width(), height()), m_parent->currBtnImages->m_btnCenterActive ); painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftActive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftActive.width() - m_parent->currBtnImages->m_btnRightActive.width(), height()), m_parent->currBtnImages->m_btnCenterActive );
painter.drawImage( width() - m_parent->currBtnImages->m_btnRightActive.width(), 0, m_parent->currBtnImages->m_btnRightActive, 0,0, m_parent->currBtnImages->m_btnRightActive.width(), m_parent->currBtnImages->m_btnRightActive.height() ); painter.drawImage( width() - m_parent->currBtnImages->m_btnRightActive.width(), 0, m_parent->currBtnImages->m_btnRightActive, 0,0, m_parent->currBtnImages->m_btnRightActive.width(), m_parent->currBtnImages->m_btnRightActive.height() );
} }
else else
{ {
painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftPassive, 0,0, m_parent->currBtnImages->m_btnLeftPassive.width(), m_parent->currBtnImages->m_btnLeftPassive.height() ); painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftPassive, 0,0, m_parent->currBtnImages->m_btnLeftPassive.width(), m_parent->currBtnImages->m_btnLeftPassive.height() );
painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftPassive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftPassive.width() - m_parent->currBtnImages->m_btnRightPassive.width(), height()), m_parent->currBtnImages->m_btnCenterPassive ); painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftPassive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftPassive.width() - m_parent->currBtnImages->m_btnRightPassive.width(), height()), m_parent->currBtnImages->m_btnCenterPassive );
painter.drawImage( width() - m_parent->currBtnImages->m_btnRightPassive.width(), 0, m_parent->currBtnImages->m_btnRightPassive, 0,0, m_parent->currBtnImages->m_btnRightPassive.width(), m_parent->currBtnImages->m_btnRightPassive.height() ); painter.drawImage( width() - m_parent->currBtnImages->m_btnRightPassive.width(), 0, m_parent->currBtnImages->m_btnRightPassive, 0,0, m_parent->currBtnImages->m_btnRightPassive.width(), m_parent->currBtnImages->m_btnRightPassive.height() );
} }
//-------------------------- //--------------------------
this->paintContent(painter); this->paintContent(painter);
//-------------------------- //--------------------------
} }
void UBKeyboardButton::enterEvent ( QEvent*) void UBKeyboardButton::enterEvent ( QEvent*)
{ {
bFocused = true; bFocused = true;
update(); update();
} }
void UBKeyboardButton::leaveEvent ( QEvent*) void UBKeyboardButton::leaveEvent ( QEvent*)
{ {
bFocused = false; bFocused = false;
update(); update();
} }
void UBKeyboardButton::mousePressEvent ( QMouseEvent * event) void UBKeyboardButton::mousePressEvent ( QMouseEvent * event)
{ {
event->accept(); event->accept();
bPressed = true; bPressed = true;
update(); update();
this->onPress(); this->onPress();
} }
void UBKeyboardButton::mouseReleaseEvent ( QMouseEvent * ) void UBKeyboardButton::mouseReleaseEvent ( QMouseEvent * )
{ {
bPressed = false; bPressed = false;
update(); update();
this->onRelease(); this->onRelease();
} }
UBKeyButton::UBKeyButton(UBKeyboardPalette* parent) UBKeyButton::UBKeyButton(UBKeyboardPalette* parent)
:UBKeyboardButton(parent), :UBKeyboardButton(parent),
keybt(0) keybt(0)
{} {}
UBKeyButton::~UBKeyButton() UBKeyButton::~UBKeyButton()
{} {}
bool UBKeyButton::shifted() bool UBKeyButton::shifted()
{ {
bool b = keyboard->shift; bool b = keyboard->shift;
if (keybt->capsLockSwitch && keyboard->capsLock) if (keybt->capsLockSwitch && keyboard->capsLock)
b = !b; b = !b;
return b; return b;
} }
void UBKeyButton::onPress() void UBKeyButton::onPress()
{ {
if (keybt!=NULL) if (keybt!=NULL)
{ {
int codeIndex = keyboard->nSpecialModifierIndex * 2 + shifted(); int codeIndex = keyboard->nSpecialModifierIndex * 2 + shifted();
if (keyboard->nSpecialModifierIndex) if (keyboard->nSpecialModifierIndex)
{ {
if (keybt->codes[codeIndex].empty()) if (keybt->codes[codeIndex].empty())
{ {
sendUnicodeSymbol(keyboard->specialModifier); sendUnicodeSymbol(keyboard->specialModifier);
sendUnicodeSymbol(keybt->codes[shifted()]); sendUnicodeSymbol(keybt->codes[shifted()]);
} }
else else
{ {
sendUnicodeSymbol(keybt->codes[codeIndex]); sendUnicodeSymbol(keybt->codes[codeIndex]);
} }
keyboard->nSpecialModifierIndex = 0; keyboard->nSpecialModifierIndex = 0;
} }
else else
{ {
int nSpecialModifierIndex = shifted()? keybt->modifier2 : keybt->modifier1; int nSpecialModifierIndex = shifted()? keybt->modifier2 : keybt->modifier1;
if (nSpecialModifierIndex) if (nSpecialModifierIndex)
{ {
keyboard->nSpecialModifierIndex = nSpecialModifierIndex; keyboard->nSpecialModifierIndex = nSpecialModifierIndex;
keyboard->specialModifier = keybt->codes[codeIndex]; keyboard->specialModifier = keybt->codes[codeIndex];
} }
else else
{ {
sendUnicodeSymbol(keybt->codes[codeIndex]); sendUnicodeSymbol(keybt->codes[codeIndex]);
} }
} }
} }
if (keyboard->shift) if (keyboard->shift)
{ {
keyboard->shift = false; keyboard->shift = false;
keyboard->update(); keyboard->update();
} }
} }
void UBKeyButton::onRelease() void UBKeyButton::onRelease()
{} {}
void UBKeyButton::paintContent(QPainter& painter) void UBKeyButton::paintContent(QPainter& painter)
{ {
if (keybt) if (keybt)
{ {
QString text(QChar(shifted() ? keybt->symbol2 : keybt->symbol1)); QString text(QChar(shifted() ? keybt->symbol2 : keybt->symbol1));
QRect textRect(rect().x()+2, rect().y()+2, rect().width()-4, rect().height()-4); QRect textRect(rect().x()+2, rect().y()+2, rect().width()-4, rect().height()-4);
painter.drawText(textRect, Qt::AlignCenter, text); painter.drawText(textRect, Qt::AlignCenter, text);
} }
} }
UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, int _code, const QString& _contentImagePath ) UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, int _code, const QString& _contentImagePath )
:UBKeyboardButton(parent, _contentImagePath), :UBKeyboardButton(parent, _contentImagePath),
label(""), label(""),
code(_code) code(_code)
{} {}
UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, const QString& _label, int _code ) UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, const QString& _label, int _code )
:UBKeyboardButton(parent), :UBKeyboardButton(parent),
label(_label), label(_label),
code(_code) code(_code)
{} {}
UBCntrlButton::~UBCntrlButton() UBCntrlButton::~UBCntrlButton()
{} {}
void UBCntrlButton::onPress() void UBCntrlButton::onPress()
{ {
sendControlSymbol(code); sendControlSymbol(code);
} }
void UBCntrlButton::onRelease() void UBCntrlButton::onRelease()
{} {}
void UBCntrlButton::paintContent(QPainter& painter) void UBCntrlButton::paintContent(QPainter& painter)
{ {
if(!label.isEmpty()) if(!label.isEmpty())
{ {
painter.drawText(rect(), Qt::AlignCenter, label); painter.drawText(rect(), Qt::AlignCenter, label);
} }
else else
if(imgContent != NULL) if(imgContent != NULL)
{ {
painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2,
imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height());
} }
} }
UBCapsLockButton::UBCapsLockButton(UBKeyboardPalette* parent, const QString _contentImagePath) UBCapsLockButton::UBCapsLockButton(UBKeyboardPalette* parent, const QString _contentImagePath)
:UBKeyboardButton(parent, _contentImagePath) :UBKeyboardButton(parent, _contentImagePath)
{} {}
UBCapsLockButton::~UBCapsLockButton() UBCapsLockButton::~UBCapsLockButton()
{} {}
void UBCapsLockButton::onPress() void UBCapsLockButton::onPress()
{ {
keyboard->capsLock = !keyboard->capsLock; keyboard->capsLock = !keyboard->capsLock;
keyboard->update(); keyboard->update();
} }
void UBCapsLockButton::onRelease() void UBCapsLockButton::onRelease()
{} {}
bool UBCapsLockButton::isPressed() bool UBCapsLockButton::isPressed()
{ {
return keyboard->capsLock; return keyboard->capsLock;
} }
void UBCapsLockButton::paintContent(QPainter& painter) void UBCapsLockButton::paintContent(QPainter& painter)
{ {
if(imgContent != NULL) if(imgContent != NULL)
{ {
painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2,
imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height());
} }
else else
painter.drawText(rect(), Qt::AlignCenter, "^"); painter.drawText(rect(), Qt::AlignCenter, "^");
} }
UBShiftButton::UBShiftButton(UBKeyboardPalette* parent, const QString _contentImagePath) UBShiftButton::UBShiftButton(UBKeyboardPalette* parent, const QString _contentImagePath)
:UBKeyboardButton(parent, _contentImagePath) :UBKeyboardButton(parent, _contentImagePath)
{} {}
UBShiftButton::~UBShiftButton() UBShiftButton::~UBShiftButton()
{} {}
void UBShiftButton::onPress() void UBShiftButton::onPress()
{ {
keyboard->shift = !keyboard->shift; keyboard->shift = !keyboard->shift;
keyboard->update(); keyboard->update();
} }
void UBShiftButton::onRelease() void UBShiftButton::onRelease()
{} {}
bool UBShiftButton::isPressed() bool UBShiftButton::isPressed()
{ {
return keyboard->shift; return keyboard->shift;
} }
void UBShiftButton::paintContent(QPainter& painter) void UBShiftButton::paintContent(QPainter& painter)
{ {
if(imgContent != NULL) if(imgContent != NULL)
{ {
painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2,
imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height());
} }
else else
painter.drawText(rect(), Qt::AlignCenter, "^"); painter.drawText(rect(), Qt::AlignCenter, "^");
} }
UBLocaleButton::UBLocaleButton(UBKeyboardPalette* parent) UBLocaleButton::UBLocaleButton(UBKeyboardPalette* parent)
:UBKeyboardButton(parent) :UBKeyboardButton(parent)
{ {
localeMenu = new QMenu(this); localeMenu = new QMenu(this);
for (int i=0; i<parent->nLocalesCount; i++) for (int i=0; i<parent->nLocalesCount; i++)
{ {
QAction* action = (parent->locales[i]->icon!=NULL) ? QAction* action = (parent->locales[i]->icon!=NULL) ?
localeMenu->addAction(*parent->locales[i]->icon, parent->locales[i]->fullName) localeMenu->addAction(*parent->locales[i]->icon, parent->locales[i]->fullName)
: localeMenu->addAction(parent->locales[i]->fullName); : localeMenu->addAction(parent->locales[i]->fullName);
action->setData(QVariant(i)); action->setData(QVariant(i));
} }
} }
UBLocaleButton::~UBLocaleButton() UBLocaleButton::~UBLocaleButton()
{ {
delete localeMenu; delete localeMenu;
} }
void UBLocaleButton::onPress() void UBLocaleButton::onPress()
{ {
} }
void UBLocaleButton::onRelease() void UBLocaleButton::onRelease()
{ {
keyboard->languagePopupActive = true; keyboard->languagePopupActive = true;
QAction* action = localeMenu->exec(mapToGlobal(QPoint(0,0))); QAction* action = localeMenu->exec(mapToGlobal(QPoint(0,0)));
keyboard->languagePopupActive = false; keyboard->languagePopupActive = false;
if (action!=NULL) if (action!=NULL)
{ {
int nLocale = action->data().toInt(); int nLocale = action->data().toInt();
keyboard->setLocale(nLocale); keyboard->setLocale(nLocale);
} }
} }
void UBLocaleButton::paintContent(QPainter& painter) void UBLocaleButton::paintContent(QPainter& painter)
{ {
const QString* localeName = keyboard->getLocaleName(); const QString* localeName = keyboard->getLocaleName();
if (localeName!=NULL) if (localeName!=NULL)
painter.drawText(rect(), Qt::AlignCenter, *localeName); painter.drawText(rect(), Qt::AlignCenter, *localeName);
} }
...@@ -19,284 +19,284 @@ ...@@ -19,284 +19,284 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBKEYBOARDPALETTE_H #ifndef UBKEYBOARDPALETTE_H
#define UBKEYBOARDPALETTE_H #define UBKEYBOARDPALETTE_H
#include "UBActionPalette.h" #include "UBActionPalette.h"
#include <QLayout> #include <QLayout>
#include <QPainter> #include <QPainter>
#include <QMenu> #include <QMenu>
#include <QIcon> #include <QIcon>
#include "frameworks/UBPlatformUtils.h" #include "frameworks/UBPlatformUtils.h"
class UBKeyButton; class UBKeyButton;
class UBKeyboardButton; class UBKeyboardButton;
class UBApplication; class UBApplication;
class UBMainWindow; class UBMainWindow;
class BTNImages class BTNImages
{ {
public: public:
BTNImages(QString _strHeight, int _width, int _height); BTNImages(QString _strHeight, int _width, int _height);
QString m_strHeight; QString m_strHeight;
int m_width; int m_width;
int m_height; int m_height;
QImage m_btnLeftPassive; QImage m_btnLeftPassive;
QImage m_btnCenterPassive; QImage m_btnCenterPassive;
QImage m_btnRightPassive; QImage m_btnRightPassive;
QImage m_btnLeftActive; QImage m_btnLeftActive;
QImage m_btnCenterActive; QImage m_btnCenterActive;
QImage m_btnRightActive; QImage m_btnRightActive;
private: private:
QString m_strLeftPassive; QString m_strLeftPassive;
QString m_strCenterPassive; QString m_strCenterPassive;
QString m_strRightPassive; QString m_strRightPassive;
QString m_strLeftActive; QString m_strLeftActive;
QString m_strCenterActive; QString m_strCenterActive;
QString m_strRightActive; QString m_strRightActive;
}; };
class ContentImage class ContentImage
{ {
public: public:
ContentImage(QString strHeight, int m_height, QString strContentPath); ContentImage(QString strHeight, int m_height, QString strContentPath);
QString m_strHeight; QString m_strHeight;
int m_height; int m_height;
QImage m_btnContent; QImage m_btnContent;
private: private:
QString m_strContent; QString m_strContent;
}; };
class UBKeyboardPalette : public UBActionPalette class UBKeyboardPalette : public UBActionPalette
{ {
Q_OBJECT Q_OBJECT
friend class UBKeyboardButton; friend class UBKeyboardButton;
friend class UBCapsLockButton; friend class UBCapsLockButton;
friend class UBShiftButton; friend class UBShiftButton;
friend class UBLocaleButton; friend class UBLocaleButton;
friend class UBKeyButton; friend class UBKeyButton;
public: public:
UBKeyboardPalette(QWidget *parent); UBKeyboardPalette(QWidget *parent);
~UBKeyboardPalette(); ~UBKeyboardPalette();
BTNImages *currBtnImages; BTNImages *currBtnImages;
bool isEnabled(){return locales!= NULL;} bool isEnabled(){return locales!= NULL;}
virtual QSize sizeHint () const; virtual QSize sizeHint () const;
virtual void adjustSizeAndPosition(bool pUp = true); virtual void adjustSizeAndPosition(bool pUp = true);
QString getKeyButtonSize() const {QString res; res.sprintf("%dx%d", btnWidth, btnHeight); return res;} QString getKeyButtonSize() const {QString res; res.sprintf("%dx%d", btnWidth, btnHeight); return res;}
void setKeyButtonSize(const QString& strSize); void setKeyButtonSize(const QString& strSize);
bool m_isVisible; bool m_isVisible;
QPoint m_pos; QPoint m_pos;
signals: signals:
void moved(const QPoint&); void moved(const QPoint&);
void localeChanged(int); void localeChanged(int);
void keyboardActivated(bool); void keyboardActivated(bool);
private slots: private slots:
void syncPosition(const QPoint & pos); void syncPosition(const QPoint & pos);
void syncLocale(int nLocale); void syncLocale(int nLocale);
void keyboardPaletteButtonSizeChanged(QVariant size); void keyboardPaletteButtonSizeChanged(QVariant size);
void onActivated(bool b); void onActivated(bool b);
void onDeactivated(); void onDeactivated();
void showKeyboard(bool show); void showKeyboard(bool show);
void hideKeyboard(); void hideKeyboard();
protected: protected:
bool capsLock; bool capsLock;
bool shift; bool shift;
int nCurrentLocale; int nCurrentLocale;
int nLocalesCount; int nLocalesCount;
UBKeyboardLocale** locales; UBKeyboardLocale** locales;
int nSpecialModifierIndex; int nSpecialModifierIndex;
KEYCODE specialModifier; KEYCODE specialModifier;
QString strSize; QString strSize;
int btnWidth; int btnWidth;
int btnHeight; int btnHeight;
// //
bool languagePopupActive; bool languagePopupActive;
bool keyboardActive; bool keyboardActive;
// //
virtual void enterEvent ( QEvent * event ); virtual void enterEvent ( QEvent * event );
virtual void leaveEvent ( QEvent * event ); virtual void leaveEvent ( QEvent * event );
virtual void paintEvent(QPaintEvent *event); virtual void paintEvent(QPaintEvent *event);
virtual void moveEvent ( QMoveEvent * event ); virtual void moveEvent ( QMoveEvent * event );
void sendKeyEvent(KEYCODE keyCode); void sendKeyEvent(KEYCODE keyCode);
void setLocale(int nLocale); void setLocale(int nLocale);
const QString* getLocaleName(); const QString* getLocaleName();
void init(); void init();
private: private:
QRect originalRect; QRect originalRect;
UBKeyButton** buttons; UBKeyButton** buttons;
UBKeyboardButton** ctrlButtons; UBKeyboardButton** ctrlButtons;
/* /*
For MacOS: synchronization with system locale. For MacOS: synchronization with system locale.
*/ */
void checkLayout(); void checkLayout();
void createCtrlButtons(); void createCtrlButtons();
void setInput(const UBKeyboardLocale* locale); void setInput(const UBKeyboardLocale* locale);
// Can be redefined under each platform // Can be redefined under each platform
void onLocaleChanged(UBKeyboardLocale* locale); void onLocaleChanged(UBKeyboardLocale* locale);
// Storage for platform-dependent objects (linux) // Storage for platform-dependent objects (linux)
void* storage; void* storage;
// Linux-related parameters // Linux-related parameters
int min_keycodes, max_keycodes, byte_per_code; int min_keycodes, max_keycodes, byte_per_code;
}; };
class UBKeyboardButton : public QWidget class UBKeyboardButton : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
UBKeyboardButton(UBKeyboardPalette* parent, QString contentImagePath); UBKeyboardButton(UBKeyboardPalette* parent, QString contentImagePath);
~UBKeyboardButton(); ~UBKeyboardButton();
protected: protected:
UBKeyboardPalette* m_parent; UBKeyboardPalette* m_parent;
ContentImage *imgContent; ContentImage *imgContent;
QString m_contentImagePath; QString m_contentImagePath;
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent *event);
virtual void enterEvent ( QEvent * event ); virtual void enterEvent ( QEvent * event );
virtual void leaveEvent ( QEvent * event ); virtual void leaveEvent ( QEvent * event );
virtual void mousePressEvent ( QMouseEvent * event ); virtual void mousePressEvent ( QMouseEvent * event );
virtual void mouseReleaseEvent ( QMouseEvent * event ); virtual void mouseReleaseEvent ( QMouseEvent * event );
virtual void onPress() = 0; virtual void onPress() = 0;
virtual void onRelease() = 0; virtual void onRelease() = 0;
virtual void paintContent(QPainter& painter) = 0; virtual void paintContent(QPainter& painter) = 0;
virtual bool isPressed(); virtual bool isPressed();
UBKeyboardPalette* keyboard; UBKeyboardPalette* keyboard;
void sendUnicodeSymbol(KEYCODE keycode); void sendUnicodeSymbol(KEYCODE keycode);
void sendControlSymbol(int nSymbol); void sendControlSymbol(int nSymbol);
private: private:
bool bFocused; bool bFocused;
bool bPressed; bool bPressed;
}; };
class UBKeyButton : public UBKeyboardButton class UBKeyButton : public UBKeyboardButton
{ {
Q_OBJECT Q_OBJECT
public: public:
UBKeyButton(UBKeyboardPalette* parent); UBKeyButton(UBKeyboardPalette* parent);
~UBKeyButton(); ~UBKeyButton();
void setKeyBt(const KEYBT* keybt){this->keybt = keybt;} void setKeyBt(const KEYBT* keybt){this->keybt = keybt;}
virtual void onPress(); virtual void onPress();
virtual void onRelease(); virtual void onRelease();
virtual void paintContent(QPainter& painter); virtual void paintContent(QPainter& painter);
private: private:
bool shifted(); bool shifted();
const KEYBT* keybt; const KEYBT* keybt;
}; };
class UBCntrlButton : public UBKeyboardButton class UBCntrlButton : public UBKeyboardButton
{ {
Q_OBJECT Q_OBJECT
public: public:
UBCntrlButton(UBKeyboardPalette* parent, int _code, const QString& _contentImagePath ); UBCntrlButton(UBKeyboardPalette* parent, int _code, const QString& _contentImagePath );
UBCntrlButton(UBKeyboardPalette* parent, const QString& _label, int _code ); UBCntrlButton(UBKeyboardPalette* parent, const QString& _label, int _code );
~UBCntrlButton(); ~UBCntrlButton();
virtual void onPress(); virtual void onPress();
virtual void onRelease(); virtual void onRelease();
virtual void paintContent(QPainter& painter); virtual void paintContent(QPainter& painter);
private: private:
QString label; QString label;
int code; int code;
}; };
class UBCapsLockButton : public UBKeyboardButton class UBCapsLockButton : public UBKeyboardButton
{ {
Q_OBJECT Q_OBJECT
public: public:
UBCapsLockButton(UBKeyboardPalette* parent, const QString _contentImagePath); UBCapsLockButton(UBKeyboardPalette* parent, const QString _contentImagePath);
~UBCapsLockButton(); ~UBCapsLockButton();
virtual void onPress(); virtual void onPress();
virtual void onRelease(); virtual void onRelease();
virtual void paintContent(QPainter& painter); virtual void paintContent(QPainter& painter);
protected: protected:
virtual bool isPressed(); virtual bool isPressed();
}; };
class UBShiftButton : public UBKeyboardButton class UBShiftButton : public UBKeyboardButton
{ {
Q_OBJECT Q_OBJECT
public: public:
UBShiftButton(UBKeyboardPalette* parent, const QString _contentImagePath); UBShiftButton(UBKeyboardPalette* parent, const QString _contentImagePath);
~UBShiftButton(); ~UBShiftButton();
virtual void onPress(); virtual void onPress();
virtual void onRelease(); virtual void onRelease();
virtual void paintContent(QPainter& painter); virtual void paintContent(QPainter& painter);
protected: protected:
virtual bool isPressed(); virtual bool isPressed();
}; };
class UBLocaleButton : public UBKeyboardButton class UBLocaleButton : public UBKeyboardButton
{ {
Q_OBJECT Q_OBJECT
public: public:
UBLocaleButton(UBKeyboardPalette* parent); UBLocaleButton(UBKeyboardPalette* parent);
~UBLocaleButton(); ~UBLocaleButton();
virtual void onPress(); virtual void onPress();
virtual void onRelease(); virtual void onRelease();
virtual void paintContent(QPainter& painter); virtual void paintContent(QPainter& painter);
protected: protected:
QMenu* localeMenu; QMenu* localeMenu;
}; };
#endif // UBKEYBOARDPALETTE_H #endif // UBKEYBOARDPALETTE_H
...@@ -19,79 +19,79 @@ ...@@ -19,79 +19,79 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBKeyboardPalette.h" #include "UBKeyboardPalette.h"
#include <windows.h> #include <windows.h>
#include "../core/UBApplication.h" #include "../core/UBApplication.h"
#include "../gui/UBMainWindow.h" #include "../gui/UBMainWindow.h"
#include "core/memcheck.h" #include "core/memcheck.h"
void UBKeyboardButton::sendUnicodeSymbol(KEYCODE keycode) void UBKeyboardButton::sendUnicodeSymbol(KEYCODE keycode)
{ {
INPUT input[2]; INPUT input[2];
input[0].type = INPUT_KEYBOARD; input[0].type = INPUT_KEYBOARD;
input[0].ki.wVk = 0; input[0].ki.wVk = 0;
input[0].ki.wScan = keycode.symbol; input[0].ki.wScan = keycode.symbol;
input[0].ki.dwFlags = KEYEVENTF_UNICODE; input[0].ki.dwFlags = KEYEVENTF_UNICODE;
input[0].ki.time = 0; input[0].ki.time = 0;
input[0].ki.dwExtraInfo = 0; input[0].ki.dwExtraInfo = 0;
input[1].type = INPUT_KEYBOARD; input[1].type = INPUT_KEYBOARD;
input[1].ki.wVk = 0; input[1].ki.wVk = 0;
input[1].ki.wScan = keycode.symbol; input[1].ki.wScan = keycode.symbol;
input[1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP; input[1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
input[1].ki.time = 0; input[1].ki.time = 0;
input[1].ki.dwExtraInfo = 0; input[1].ki.dwExtraInfo = 0;
::SendInput(2, input, sizeof(input[0])); ::SendInput(2, input, sizeof(input[0]));
} }
void UBKeyboardButton::sendControlSymbol(int nSymbol) void UBKeyboardButton::sendControlSymbol(int nSymbol)
{ {
INPUT input[2]; INPUT input[2];
input[0].type = INPUT_KEYBOARD; input[0].type = INPUT_KEYBOARD;
input[0].ki.wVk = nSymbol; input[0].ki.wVk = nSymbol;
input[0].ki.wScan = 0; input[0].ki.wScan = 0;
input[0].ki.dwFlags = 0; input[0].ki.dwFlags = 0;
input[0].ki.time = 0; input[0].ki.time = 0;
input[0].ki.dwExtraInfo = 0; input[0].ki.dwExtraInfo = 0;
input[1].type = INPUT_KEYBOARD; input[1].type = INPUT_KEYBOARD;
input[1].ki.wVk = nSymbol; input[1].ki.wVk = nSymbol;
input[1].ki.wScan = 0; input[1].ki.wScan = 0;
input[1].ki.dwFlags = KEYEVENTF_KEYUP; input[1].ki.dwFlags = KEYEVENTF_KEYUP;
input[1].ki.time = 0; input[1].ki.time = 0;
input[1].ki.dwExtraInfo = 0; input[1].ki.dwExtraInfo = 0;
::SendInput(2, input, sizeof(input[0])); ::SendInput(2, input, sizeof(input[0]));
} }
void UBKeyboardPalette::createCtrlButtons() void UBKeyboardPalette::createCtrlButtons()
{ {
int ctrlID = 0; int ctrlID = 0;
ctrlButtons = new UBKeyboardButton*[9]; ctrlButtons = new UBKeyboardButton*[9];
ctrlButtons[ctrlID++] = new UBCntrlButton(this, 0x08, "backspace");// Backspace ctrlButtons[ctrlID++] = new UBCntrlButton(this, 0x08, "backspace");// Backspace
ctrlButtons[ctrlID++] = new UBCntrlButton(this, 0x09, "tab"); // Tab ctrlButtons[ctrlID++] = new UBCntrlButton(this, 0x09, "tab"); // Tab
ctrlButtons[ctrlID++] = new UBCapsLockButton(this, "capslock"); // Shift ctrlButtons[ctrlID++] = new UBCapsLockButton(this, "capslock"); // Shift
ctrlButtons[ctrlID++] = new UBCntrlButton(this, tr("Enter"), 0x0d); // Enter ctrlButtons[ctrlID++] = new UBCntrlButton(this, tr("Enter"), 0x0d); // Enter
ctrlButtons[ctrlID++] = new UBShiftButton(this, "shift"); // Shift ctrlButtons[ctrlID++] = new UBShiftButton(this, "shift"); // Shift
ctrlButtons[ctrlID++] = new UBShiftButton(this, "shift"); // Shift ctrlButtons[ctrlID++] = new UBShiftButton(this, "shift"); // Shift
ctrlButtons[ctrlID++] = new UBLocaleButton(this); // Language Switch ctrlButtons[ctrlID++] = new UBLocaleButton(this); // Language Switch
ctrlButtons[ctrlID++] = new UBCntrlButton(this, "", 0x20); // Space ctrlButtons[ctrlID++] = new UBCntrlButton(this, "", 0x20); // Space
ctrlButtons[ctrlID++] = new UBLocaleButton(this); // Language Switch ctrlButtons[ctrlID++] = new UBLocaleButton(this); // Language Switch
} }
void UBKeyboardPalette::checkLayout() void UBKeyboardPalette::checkLayout()
{} {}
void UBKeyboardPalette::onActivated(bool) void UBKeyboardPalette::onActivated(bool)
{} {}
void UBKeyboardPalette::onLocaleChanged(UBKeyboardLocale* ) void UBKeyboardPalette::onLocaleChanged(UBKeyboardLocale* )
{} {}
...@@ -19,386 +19,386 @@ ...@@ -19,386 +19,386 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QtGui> #include <QtGui>
#include "UBMagnifer.h" #include "UBMagnifer.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "domain/UBGraphicsScene.h" #include "domain/UBGraphicsScene.h"
#include "board/UBBoardView.h" #include "board/UBBoardView.h"
#include "core/memcheck.h" #include "core/memcheck.h"
UBMagnifier::UBMagnifier(QWidget *parent, bool isInteractive) UBMagnifier::UBMagnifier(QWidget *parent, bool isInteractive)
: QWidget(parent, parent ? Qt::Widget : Qt::Tool | (Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint)) : QWidget(parent, parent ? Qt::Widget : Qt::Tool | (Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint))
, mShouldMoveWidget(false) , mShouldMoveWidget(false)
, mShouldResizeWidget(false) , mShouldResizeWidget(false)
, borderPen(Qt::darkGray) , borderPen(Qt::darkGray)
, gView(0) , gView(0)
, mView(0) , mView(0)
{ {
isCusrsorAlreadyStored = false; isCusrsorAlreadyStored = false;
setMouseTracking(true); setMouseTracking(true);
//--------------------------------------------------// //--------------------------------------------------//
QPixmap pix(":/images/cursors/resize.png"); QPixmap pix(":/images/cursors/resize.png");
QTransform tr; QTransform tr;
tr.rotate(45); tr.rotate(45);
mResizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2); mResizeCursor = QCursor(pix.transformed(tr, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2);
//--------------------------------------------------// //--------------------------------------------------//
params.sizePercentFromScene = 20; params.sizePercentFromScene = 20;
m_isInteractive = isInteractive; m_isInteractive = isInteractive;
sClosePixmap = new QPixmap(":/images/close.svg"); sClosePixmap = new QPixmap(":/images/close.svg");
sIncreasePixmap = new QPixmap(":/images/increase.svg"); sIncreasePixmap = new QPixmap(":/images/increase.svg");
sDecreasePixmap = new QPixmap(":/images/decrease.svg"); sDecreasePixmap = new QPixmap(":/images/decrease.svg");
mResizeItem = new QPixmap(":/images/resize.svg"); mResizeItem = new QPixmap(":/images/resize.svg");
if (parent) if (parent)
{ {
setAttribute(Qt::WA_NoMousePropagation); setAttribute(Qt::WA_NoMousePropagation);
} }
else else
{ {
// standalone window // standalone window
// !!!! Should be included into Windows after QT recompilation // !!!! Should be included into Windows after QT recompilation
#ifndef Q_WS_WIN #ifndef Q_WS_WIN
// setAttribute(Qt::WA_TranslucentBackground); // setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_MacAlwaysShowToolWindow); setAttribute(Qt::WA_MacAlwaysShowToolWindow);
#endif #endif
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
setAttribute(Qt::WA_MacAlwaysShowToolWindow); setAttribute(Qt::WA_MacAlwaysShowToolWindow);
setAttribute(Qt::WA_MacNonActivatingToolWindow); setAttribute(Qt::WA_MacNonActivatingToolWindow);
setAttribute(Qt::WA_MacNoShadow); setAttribute(Qt::WA_MacNoShadow);
#endif #endif
} }
connect(&mRefreshTimer, SIGNAL(timeout()), this, SLOT(slot_refresh())); connect(&mRefreshTimer, SIGNAL(timeout()), this, SLOT(slot_refresh()));
} }
UBMagnifier::~UBMagnifier() UBMagnifier::~UBMagnifier()
{ {
if(sClosePixmap) if(sClosePixmap)
{ {
delete sClosePixmap; delete sClosePixmap;
sClosePixmap = NULL; sClosePixmap = NULL;
} }
if(sIncreasePixmap) if(sIncreasePixmap)
{ {
delete sIncreasePixmap; delete sIncreasePixmap;
sIncreasePixmap = NULL; sIncreasePixmap = NULL;
} }
if(sDecreasePixmap) if(sDecreasePixmap)
{ {
delete sDecreasePixmap; delete sDecreasePixmap;
sDecreasePixmap = NULL; sDecreasePixmap = NULL;
} }
} }
void UBMagnifier::setSize(qreal percentFromScene) void UBMagnifier::setSize(qreal percentFromScene)
{ {
if(gView == NULL || mView == NULL) return; if(gView == NULL || mView == NULL) return;
// calculate object size // calculate object size
params.sizePercentFromScene = percentFromScene; params.sizePercentFromScene = percentFromScene;
QSize sceneSize = mView->size(); QSize sceneSize = mView->size();
qreal size = params.sizePercentFromScene * sceneSize.width() / 100; qreal size = params.sizePercentFromScene * sceneSize.width() / 100;
QRect currGeom = geometry(); QRect currGeom = geometry();
if(currGeom.width() == currGeom.height()) if(currGeom.width() == currGeom.height())
{ {
QPoint newPos = mView->mapFromGlobal(updPointMove); QPoint newPos = mView->mapFromGlobal(updPointMove);
setGeometry(newPos.x() - size / 2, newPos.y() - size / 2, size, size); setGeometry(newPos.x() - size / 2, newPos.y() - size / 2, size, size);
} }
else else
setGeometry(0, 0, size, size); setGeometry(0, 0, size, size);
// prepare transparent bit mask // prepare transparent bit mask
QImage mask_img(width(), height(), QImage::Format_Mono); QImage mask_img(width(), height(), QImage::Format_Mono);
mask_img.fill(0xff); mask_img.fill(0xff);
QPainter mask_ptr(&mask_img); QPainter mask_ptr(&mask_img);
mask_ptr.setBrush( QBrush( QColor(0, 0, 0) ) ); mask_ptr.setBrush( QBrush( QColor(0, 0, 0) ) );
mask_ptr.drawEllipse(QPointF(size/2, size/2), size / 2 - sClosePixmap->width(), size / 2 - sClosePixmap->width()); mask_ptr.drawEllipse(QPointF(size/2, size/2), size / 2 - sClosePixmap->width(), size / 2 - sClosePixmap->width());
bmpMask = QBitmap::fromImage(mask_img); bmpMask = QBitmap::fromImage(mask_img);
// prepare general image // prepare general image
pMap = QPixmap(width(), height()); pMap = QPixmap(width(), height());
pMap.fill(Qt::transparent); pMap.fill(Qt::transparent);
pMap.setMask(bmpMask); pMap.setMask(bmpMask);
} }
void UBMagnifier::setZoom(qreal zoom) void UBMagnifier::setZoom(qreal zoom)
{ {
params.zoom = zoom; params.zoom = zoom;
} }
void UBMagnifier::paintEvent(QPaintEvent * event) void UBMagnifier::paintEvent(QPaintEvent * event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
QPainter painter(this); QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::NoPen); painter.setPen(Qt::NoPen);
if (m_isInteractive) if (m_isInteractive)
{ {
painter.setBrush(QColor(127, 127, 127, 127)); painter.setBrush(QColor(127, 127, 127, 127));
painter.drawRoundedRect(QRectF(size().width() / 2, size().height() / 2, ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->width() ) / 2), 15, 15); painter.drawRoundedRect(QRectF(size().width() / 2, size().height() / 2, ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->width() ) / 2), 15, 15);
painter.setBrush(QColor(190, 190, 190, 255)); painter.setBrush(QColor(190, 190, 190, 255));
painter.drawEllipse(QPoint( size().width() / 2, size().height() / 2), ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->height() ) / 2); painter.drawEllipse(QPoint( size().width() / 2, size().height() / 2), ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->height() ) / 2);
painter.drawPixmap(size().width() - sClosePixmap->width(), size().height() / 2 + sClosePixmap->height() * 1, *sClosePixmap); painter.drawPixmap(size().width() - sClosePixmap->width(), size().height() / 2 + sClosePixmap->height() * 1, *sClosePixmap);
painter.drawPixmap(size().width() - sIncreasePixmap->width(), size().height() / 2 + sIncreasePixmap->height() * 2.5, *sIncreasePixmap); painter.drawPixmap(size().width() - sIncreasePixmap->width(), size().height() / 2 + sIncreasePixmap->height() * 2.5, *sIncreasePixmap);
painter.drawPixmap(size().width() - sDecreasePixmap->width(), size().height() / 2 + sDecreasePixmap->height() * 3.6, *sDecreasePixmap); painter.drawPixmap(size().width() - sDecreasePixmap->width(), size().height() / 2 + sDecreasePixmap->height() * 3.6, *sDecreasePixmap);
painter.drawPixmap(size().width() - mResizeItem->width() - 20, size().height() - mResizeItem->height() - 20, *mResizeItem); painter.drawPixmap(size().width() - mResizeItem->width() - 20, size().height() - mResizeItem->height() - 20, *mResizeItem);
} }
else else
{ {
painter.setBrush(QColor(127, 127, 127, 127)); painter.setBrush(QColor(127, 127, 127, 127));
painter.drawEllipse(QPoint( size().width() / 2, size().height() / 2), ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->height() ) / 2); painter.drawEllipse(QPoint( size().width() / 2, size().height() / 2), ( size().width() - sClosePixmap->width() ) / 2, ( size().height() - sClosePixmap->height() ) / 2);
} }
painter.drawPixmap(0, 0, pMap); painter.drawPixmap(0, 0, pMap);
} }
void UBMagnifier::mousePressEvent ( QMouseEvent * event ) void UBMagnifier::mousePressEvent ( QMouseEvent * event )
{ {
if(m_isInteractive) if(m_isInteractive)
{ {
QWidget::mousePressEvent(event); QWidget::mousePressEvent(event);
if (event->pos().x() >= size().width() - mResizeItem->width() - 20 && if (event->pos().x() >= size().width() - mResizeItem->width() - 20 &&
event->pos().x() < size().width() - 20 && event->pos().x() < size().width() - 20 &&
event->pos().y() >= size().height() - mResizeItem->height() - 20 && event->pos().y() >= size().height() - mResizeItem->height() - 20 &&
event->pos().y() < size().height() - - 20) event->pos().y() < size().height() - - 20)
{ {
mShouldResizeWidget = true; mShouldResizeWidget = true;
} }
else else
{ {
mShouldMoveWidget = !event->isAccepted() && (event->buttons() & Qt::LeftButton); mShouldMoveWidget = !event->isAccepted() && (event->buttons() & Qt::LeftButton);
} }
mMousePressPos = event->pos(); mMousePressPos = event->pos();
mMousePressDelta = (qreal)updPointGrab.x() + (qreal)size().width() / 2 - (qreal)event->globalPos().x(); mMousePressDelta = (qreal)updPointGrab.x() + (qreal)size().width() / 2 - (qreal)event->globalPos().x();
event->accept(); event->accept();
update(); update();
} }
else else
event->ignore(); event->ignore();
} }
void UBMagnifier::mouseMoveEvent ( QMouseEvent * event ) void UBMagnifier::mouseMoveEvent ( QMouseEvent * event )
{ {
if(m_isInteractive) if(m_isInteractive)
{ {
if(mShouldMoveWidget && (event->buttons() & Qt::LeftButton)) if(mShouldMoveWidget && (event->buttons() & Qt::LeftButton))
{ {
move(pos() - mMousePressPos + event->pos()); move(pos() - mMousePressPos + event->pos());
event->accept(); event->accept();
QWidget::mouseMoveEvent(event); QWidget::mouseMoveEvent(event);
emit magnifierMoved_Signal(QPoint(this->pos().x() + size().width() / 2, this->pos().y() + size().height() / 2 )); emit magnifierMoved_Signal(QPoint(this->pos().x() + size().width() / 2, this->pos().y() + size().height() / 2 ));
return; return;
} }
if(mShouldResizeWidget && (event->buttons() & Qt::LeftButton)) if(mShouldResizeWidget && (event->buttons() & Qt::LeftButton))
{ {
QPoint currGlobalPos = event->globalPos(); QPoint currGlobalPos = event->globalPos();
qreal cvW = mView->width(); qreal cvW = mView->width();
qreal newXSize = ( currGlobalPos.x() + mMousePressDelta - updPointGrab.x() ) * 2; qreal newXSize = ( currGlobalPos.x() + mMousePressDelta - updPointGrab.x() ) * 2;
qreal newPercentSize = newXSize * 100 / cvW; qreal newPercentSize = newXSize * 100 / cvW;
emit magnifierResized_Signal(newPercentSize); emit magnifierResized_Signal(newPercentSize);
event->ignore(); event->ignore();
return; return;
} }
if (event->pos().x() >= size().width() - mResizeItem->width() - 20 && if (event->pos().x() >= size().width() - mResizeItem->width() - 20 &&
event->pos().x() < size().width() - 20 && event->pos().x() < size().width() - 20 &&
event->pos().y() >= size().height() - mResizeItem->height() - 20 && event->pos().y() >= size().height() - mResizeItem->height() - 20 &&
event->pos().y() < size().height() - - 20 && event->pos().y() < size().height() - - 20 &&
isCusrsorAlreadyStored == false isCusrsorAlreadyStored == false
) )
{ {
mOldCursor = cursor(); mOldCursor = cursor();
isCusrsorAlreadyStored = true; isCusrsorAlreadyStored = true;
setCursor(mResizeCursor); setCursor(mResizeCursor);
} }
} }
else else
event->ignore(); event->ignore();
} }
void UBMagnifier::mouseReleaseEvent(QMouseEvent * event) void UBMagnifier::mouseReleaseEvent(QMouseEvent * event)
{ {
if(m_isInteractive) if(m_isInteractive)
{ {
mShouldMoveWidget = false; mShouldMoveWidget = false;
mShouldResizeWidget = false; mShouldResizeWidget = false;
if (event->pos().x() >= size().width() - sClosePixmap->width() && if (event->pos().x() >= size().width() - sClosePixmap->width() &&
event->pos().x() < size().width()&& event->pos().x() < size().width()&&
event->pos().y() >= size().height() / 2 + sClosePixmap->height() * 1 && event->pos().y() >= size().height() / 2 + sClosePixmap->height() * 1 &&
event->pos().y() < size().height() / 2 + sClosePixmap->height() * 2) event->pos().y() < size().height() / 2 + sClosePixmap->height() * 2)
{ {
event->accept(); event->accept();
emit magnifierClose_Signal(); emit magnifierClose_Signal();
} }
else else
if (event->pos().x() >= size().width() - sIncreasePixmap->width() && if (event->pos().x() >= size().width() - sIncreasePixmap->width() &&
event->pos().x() < size().width()&& event->pos().x() < size().width()&&
event->pos().y() >= size().height() / 2 + sIncreasePixmap->height() * 2.5 && event->pos().y() >= size().height() / 2 + sIncreasePixmap->height() * 2.5 &&
event->pos().y() < size().height() / 2 + sIncreasePixmap->height() * 3.5) event->pos().y() < size().height() / 2 + sIncreasePixmap->height() * 3.5)
{ {
event->accept(); event->accept();
emit magnifierZoomIn_Signal(); emit magnifierZoomIn_Signal();
} }
else else
if (event->pos().x() >= size().width() - sDecreasePixmap->width() && if (event->pos().x() >= size().width() - sDecreasePixmap->width() &&
event->pos().x() < size().width()&& event->pos().x() < size().width()&&
event->pos().y() >= size().height() / 2 + sDecreasePixmap->height() * 3.6 && event->pos().y() >= size().height() / 2 + sDecreasePixmap->height() * 3.6 &&
event->pos().y() < size().height() / 2 + sDecreasePixmap->height() * 4.6) event->pos().y() < size().height() / 2 + sDecreasePixmap->height() * 4.6)
{ {
event->accept(); event->accept();
emit magnifierZoomOut_Signal(); emit magnifierZoomOut_Signal();
} }
else else
QWidget::mouseReleaseEvent(event); // don't propgate to parent, the widget is deleted in UBApplication::boardController->removeTool QWidget::mouseReleaseEvent(event); // don't propgate to parent, the widget is deleted in UBApplication::boardController->removeTool
} }
else else
event->ignore(); event->ignore();
} }
void UBMagnifier::slot_refresh() void UBMagnifier::slot_refresh()
{ {
if(!(updPointGrab.isNull())) if(!(updPointGrab.isNull()))
grabPoint(updPointGrab); grabPoint(updPointGrab);
if(isCusrsorAlreadyStored) if(isCusrsorAlreadyStored)
{ {
QPoint globalCursorPos = QCursor::pos(); QPoint globalCursorPos = QCursor::pos();
QPoint cursorPos = mapFromGlobal(globalCursorPos); QPoint cursorPos = mapFromGlobal(globalCursorPos);
if (cursorPos.x() < size().width() - mResizeItem->width() - 20 || if (cursorPos.x() < size().width() - mResizeItem->width() - 20 ||
cursorPos.x() > size().width() - 20 || cursorPos.x() > size().width() - 20 ||
cursorPos.y() < size().height() - mResizeItem->height() - 20 || cursorPos.y() < size().height() - mResizeItem->height() - 20 ||
cursorPos.y() > size().height() - - 20 cursorPos.y() > size().height() - - 20
) )
{ {
isCusrsorAlreadyStored = false; isCusrsorAlreadyStored = false;
setCursor(mOldCursor); setCursor(mOldCursor);
} }
} }
} }
void UBMagnifier::grabPoint() void UBMagnifier::grabPoint()
{ {
QMatrix transM = UBApplication::boardController->controlView()->matrix(); QMatrix transM = UBApplication::boardController->controlView()->matrix();
QPointF itemPos = gView->mapFromGlobal(updPointGrab); QPointF itemPos = gView->mapFromGlobal(updPointGrab);
qreal zWidth = width() / (params.zoom * transM.m11()); qreal zWidth = width() / (params.zoom * transM.m11());
qreal zWidthHalf = zWidth / 2; qreal zWidthHalf = zWidth / 2;
qreal zHeight = height() / (params.zoom * transM.m22()); qreal zHeight = height() / (params.zoom * transM.m22());
qreal zHeightHalf = zHeight / 2; qreal zHeightHalf = zHeight / 2;
QPointF pfScLtF(UBApplication::boardController->controlView()->mapToScene(QPoint(itemPos.x(), itemPos.y()))); QPointF pfScLtF(UBApplication::boardController->controlView()->mapToScene(QPoint(itemPos.x(), itemPos.y())));
float x = pfScLtF.x() - zWidthHalf; float x = pfScLtF.x() - zWidthHalf;
float y = pfScLtF.y() - zHeightHalf; float y = pfScLtF.y() - zHeightHalf;
QPointF leftTop(x,y); QPointF leftTop(x,y);
QPointF rightBottom(x + zWidth, y + zHeight); QPointF rightBottom(x + zWidth, y + zHeight);
QRectF srcRect(leftTop, rightBottom); QRectF srcRect(leftTop, rightBottom);
QPixmap newPixMap(QSize(width(), height())); QPixmap newPixMap(QSize(width(), height()));
QPainter painter(&newPixMap); QPainter painter(&newPixMap);
UBApplication::boardController->activeScene()->render(&painter, QRectF(0,0,width(),height()), srcRect); UBApplication::boardController->activeScene()->render(&painter, QRectF(0,0,width(),height()), srcRect);
painter.end(); painter.end();
pMap.fill(Qt::transparent); pMap.fill(Qt::transparent);
pMap = newPixMap.scaled(QSize(width(), height())); pMap = newPixMap.scaled(QSize(width(), height()));
pMap.setMask(bmpMask); pMap.setMask(bmpMask);
update(); update();
} }
void UBMagnifier::grabPoint(const QPoint &pGrab) void UBMagnifier::grabPoint(const QPoint &pGrab)
{ {
QMatrix transM = UBApplication::boardController->controlView()->matrix(); QMatrix transM = UBApplication::boardController->controlView()->matrix();
updPointGrab = pGrab; updPointGrab = pGrab;
QPointF itemPos = gView->mapFromGlobal(pGrab); QPointF itemPos = gView->mapFromGlobal(pGrab);
qreal zWidth = width() / (params.zoom * transM.m11()); qreal zWidth = width() / (params.zoom * transM.m11());
qreal zWidthHalf = zWidth / 2; qreal zWidthHalf = zWidth / 2;
qreal zHeight = height() / (params.zoom * transM.m22()); qreal zHeight = height() / (params.zoom * transM.m22());
qreal zHeightHalf = zHeight / 2; qreal zHeightHalf = zHeight / 2;
QPointF pfScLtF(UBApplication::boardController->controlView()->mapToScene(QPoint(itemPos.x(), itemPos.y()))); QPointF pfScLtF(UBApplication::boardController->controlView()->mapToScene(QPoint(itemPos.x(), itemPos.y())));
float x = pfScLtF.x() - zWidthHalf; float x = pfScLtF.x() - zWidthHalf;
float y = pfScLtF.y() - zHeightHalf; float y = pfScLtF.y() - zHeightHalf;
QPointF leftTop(x,y); QPointF leftTop(x,y);
QPointF rightBottom(x + zWidth, y + zHeight); QPointF rightBottom(x + zWidth, y + zHeight);
QRectF srcRect(leftTop, rightBottom); QRectF srcRect(leftTop, rightBottom);
QPixmap newPixMap(QSize(width(), height())); QPixmap newPixMap(QSize(width(), height()));
QPainter painter(&newPixMap); QPainter painter(&newPixMap);
UBApplication::boardController->activeScene()->render(&painter, QRectF(0,0,width(),height()), srcRect); UBApplication::boardController->activeScene()->render(&painter, QRectF(0,0,width(),height()), srcRect);
painter.end(); painter.end();
// pMap.fill(Qt::transparent); // pMap.fill(Qt::transparent);
pMap = newPixMap; pMap = newPixMap;
pMap.setMask(bmpMask); pMap.setMask(bmpMask);
update(); update();
} }
// from global // from global
void UBMagnifier::grabNMove(const QPoint &pGrab, const QPoint &pMove, bool needGrab, bool needMove) void UBMagnifier::grabNMove(const QPoint &pGrab, const QPoint &pMove, bool needGrab, bool needMove)
{ {
updPointGrab = pGrab; updPointGrab = pGrab;
updPointMove = pMove; updPointMove = pMove;
if(needGrab) if(needGrab)
grabPoint(pGrab); grabPoint(pGrab);
if(needMove) if(needMove)
{ {
QPoint movePos = mView->mapFromGlobal(pMove); QPoint movePos = mView->mapFromGlobal(pMove);
move(movePos.x() - width()/2, movePos.y() - height()/2); move(movePos.x() - width()/2, movePos.y() - height()/2);
// move(itemPos.x(), itemPos.y()); // move(itemPos.x(), itemPos.y());
} }
} }
void UBMagnifier::setGrabView(QWidget *view) void UBMagnifier::setGrabView(QWidget *view)
{ {
gView = view; gView = view;
mRefreshTimer.setInterval(40); mRefreshTimer.setInterval(40);
mRefreshTimer.start(); mRefreshTimer.start();
} }
...@@ -19,87 +19,87 @@ ...@@ -19,87 +19,87 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBMAGNIFIER_H #ifndef UBMAGNIFIER_H
#define UBMAGNIFIER_H #define UBMAGNIFIER_H
#include <QtGui> #include <QtGui>
class UBMagnifierParams class UBMagnifierParams
{ {
public : public :
int x; int x;
int y; int y;
qreal zoom; qreal zoom;
qreal sizePercentFromScene; qreal sizePercentFromScene;
}; };
class UBMagnifier : public QWidget class UBMagnifier : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
UBMagnifier(QWidget *parent = 0, bool isInteractive = false); UBMagnifier(QWidget *parent = 0, bool isInteractive = false);
~UBMagnifier(); ~UBMagnifier();
void setSize(qreal percentFromScene); void setSize(qreal percentFromScene);
void setZoom(qreal zoom); void setZoom(qreal zoom);
void setGrabView(QWidget *view); void setGrabView(QWidget *view);
void setMoveView(QWidget *view) {mView = view;} void setMoveView(QWidget *view) {mView = view;}
void grabPoint(); void grabPoint();
void grabPoint(const QPoint &point); void grabPoint(const QPoint &point);
void grabNMove(const QPoint &pGrab, const QPoint &pMove, bool needGrab = true, bool needMove = true); void grabNMove(const QPoint &pGrab, const QPoint &pMove, bool needGrab = true, bool needMove = true);
UBMagnifierParams params; UBMagnifierParams params;
signals: signals:
void magnifierMoved_Signal(QPoint newPos); void magnifierMoved_Signal(QPoint newPos);
void magnifierClose_Signal(); void magnifierClose_Signal();
void magnifierZoomIn_Signal(); void magnifierZoomIn_Signal();
void magnifierZoomOut_Signal(); void magnifierZoomOut_Signal();
void magnifierResized_Signal(qreal newPercentSize); void magnifierResized_Signal(qreal newPercentSize);
public slots: public slots:
void slot_refresh(); void slot_refresh();
protected: protected:
void paintEvent(QPaintEvent *); void paintEvent(QPaintEvent *);
virtual void mousePressEvent ( QMouseEvent * event ); virtual void mousePressEvent ( QMouseEvent * event );
virtual void mouseMoveEvent ( QMouseEvent * event ); virtual void mouseMoveEvent ( QMouseEvent * event );
virtual void mouseReleaseEvent ( QMouseEvent * event ); virtual void mouseReleaseEvent ( QMouseEvent * event );
QPoint mMousePressPos; QPoint mMousePressPos;
qreal mMousePressDelta; qreal mMousePressDelta;
bool mShouldMoveWidget; bool mShouldMoveWidget;
bool mShouldResizeWidget; bool mShouldResizeWidget;
QPixmap *sClosePixmap; QPixmap *sClosePixmap;
QPixmap *sIncreasePixmap; QPixmap *sIncreasePixmap;
QPixmap *sDecreasePixmap; QPixmap *sDecreasePixmap;
QPixmap *mResizeItem; QPixmap *mResizeItem;
bool isCusrsorAlreadyStored; bool isCusrsorAlreadyStored;
QCursor mOldCursor; QCursor mOldCursor;
QCursor mResizeCursor; QCursor mResizeCursor;
private: private:
QTimer mRefreshTimer; QTimer mRefreshTimer;
bool m_isInteractive; bool m_isInteractive;
QPoint updPointGrab; QPoint updPointGrab;
QPoint updPointMove; QPoint updPointMove;
QPixmap pMap; QPixmap pMap;
QBitmap bmpMask; QBitmap bmpMask;
QPen borderPen; QPen borderPen;
QWidget *gView; QWidget *gView;
QWidget *mView; QWidget *mView;
}; };
#endif // UBMAGNIFIER_H #endif // UBMAGNIFIER_H
...@@ -19,135 +19,135 @@ ...@@ -19,135 +19,135 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBNavigatorPalette.h" #include "UBNavigatorPalette.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "core/memcheck.h" #include "core/memcheck.h"
/** /**
* \brief Constructor * \brief Constructor
* @param parent as the parent widget * @param parent as the parent widget
* @param name as the object name * @param name as the object name
*/ */
UBNavigatorPalette::UBNavigatorPalette(QWidget *parent, const char *name): UBNavigatorPalette::UBNavigatorPalette(QWidget *parent, const char *name):
UBDockPalette(eUBDockPaletteType_LEFT, parent, name) UBDockPalette(eUBDockPaletteType_LEFT, parent, name)
, mNavigator(NULL) , mNavigator(NULL)
, mLayout(NULL) , mLayout(NULL)
, mHLayout(NULL) , mHLayout(NULL)
, mPageNbr(NULL) , mPageNbr(NULL)
, mClock(NULL) , mClock(NULL)
{ {
// Build the gui // Build the gui
mLayout = new QVBoxLayout(this); mLayout = new QVBoxLayout(this);
mLayout->setContentsMargins(customMargin(), customMargin(), 2*border() + customMargin(), customMargin()); mLayout->setContentsMargins(customMargin(), customMargin(), 2*border() + customMargin(), customMargin());
setLayout(mLayout); setLayout(mLayout);
mNavigator = new UBDocumentNavigator(this); mNavigator = new UBDocumentNavigator(this);
mNavigator->setStyleSheet(QString("background-color : transparent;")); mNavigator->setStyleSheet(QString("background-color : transparent;"));
mLayout->addWidget(mNavigator, 1); mLayout->addWidget(mNavigator, 1);
mHLayout = new QHBoxLayout(); mHLayout = new QHBoxLayout();
mLayout->addLayout(mHLayout, 0); mLayout->addLayout(mHLayout, 0);
mPageNbr = new QLabel(this); mPageNbr = new QLabel(this);
mClock = new QLabel(this); mClock = new QLabel(this);
mHLayout->addWidget(mPageNbr); mHLayout->addWidget(mPageNbr);
mHLayout->addWidget(mClock); mHLayout->addWidget(mClock);
// Configure the page number indicator // Configure the page number indicator
mPageNbr->setStyleSheet(QString("QLabel { color: white; background-color: transparent; border: none; font-family: Arial; font-weight: bold; font-size: 20px }")); mPageNbr->setStyleSheet(QString("QLabel { color: white; background-color: transparent; border: none; font-family: Arial; font-weight: bold; font-size: 20px }"));
setPageNumber(0, 0); setPageNumber(0, 0);
mPageNbr->setAlignment(Qt::AlignHCenter); mPageNbr->setAlignment(Qt::AlignHCenter);
// Configure the clock // Configure the clock
mClock->setStyleSheet(QString("QLabel {color: white; background-color: transparent; text-align: center; font-family: Arial; font-weight: bold; font-size: 20px}")); mClock->setStyleSheet(QString("QLabel {color: white; background-color: transparent; text-align: center; font-family: Arial; font-weight: bold; font-size: 20px}"));
mTimeFormat = QLocale::system().timeFormat(QLocale::ShortFormat); mTimeFormat = QLocale::system().timeFormat(QLocale::ShortFormat);
mClock->setAlignment(Qt::AlignHCenter); mClock->setAlignment(Qt::AlignHCenter);
//strip seconds //strip seconds
mTimeFormat = mTimeFormat.remove(":ss"); mTimeFormat = mTimeFormat.remove(":ss");
mTimeFormat = mTimeFormat.remove(":s"); mTimeFormat = mTimeFormat.remove(":s");
mTimerID = startTimer(1000); mTimerID = startTimer(1000);
} }
/** /**
* \brief Destructor * \brief Destructor
*/ */
UBNavigatorPalette::~UBNavigatorPalette() UBNavigatorPalette::~UBNavigatorPalette()
{ {
killTimer(mTimerID); killTimer(mTimerID);
if(NULL != mClock) if(NULL != mClock)
{ {
delete mClock; delete mClock;
mClock = NULL; mClock = NULL;
} }
if(NULL != mPageNbr) if(NULL != mPageNbr)
{ {
delete mPageNbr; delete mPageNbr;
mPageNbr = NULL; mPageNbr = NULL;
} }
if(NULL != mHLayout) if(NULL != mHLayout)
{ {
delete mHLayout; delete mHLayout;
mHLayout = NULL; mHLayout = NULL;
} }
if(NULL != mLayout) if(NULL != mLayout)
{ {
delete mLayout; delete mLayout;
mLayout = NULL; mLayout = NULL;
} }
if(NULL != mNavigator) if(NULL != mNavigator)
{ {
delete mNavigator; delete mNavigator;
mNavigator = NULL; mNavigator = NULL;
} }
} }
/** /**
* \brief Set the current document in the navigator * \brief Set the current document in the navigator
* @param document as the given document * @param document as the given document
*/ */
/** /**
* \brief Refresh the thumbnails widget * \brief Refresh the thumbnails widget
*/ */
void UBNavigatorPalette::refresh() void UBNavigatorPalette::refresh()
{ {
} }
/** /**
* \brief Handle the resize event * \brief Handle the resize event
* @param event as the resize event * @param event as the resize event
*/ */
void UBNavigatorPalette::resizeEvent(QResizeEvent *event) void UBNavigatorPalette::resizeEvent(QResizeEvent *event)
{ {
UBDockPalette::resizeEvent(event); UBDockPalette::resizeEvent(event);
if(NULL != mNavigator) if(NULL != mNavigator)
{ {
mNavigator->setMinimumHeight(height() - 2*border()); mNavigator->setMinimumHeight(height() - 2*border());
} }
} }
void UBNavigatorPalette::timerEvent(QTimerEvent *event) void UBNavigatorPalette::timerEvent(QTimerEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
updateTime(); updateTime();
} }
void UBNavigatorPalette::updateTime() void UBNavigatorPalette::updateTime()
{ {
if (mClock) if (mClock)
{ {
mClock->setText(QLocale::system().toString (QTime::currentTime(), mTimeFormat)); mClock->setText(QLocale::system().toString (QTime::currentTime(), mTimeFormat));
} }
} }
void UBNavigatorPalette::setPageNumber(int current, int total) void UBNavigatorPalette::setPageNumber(int current, int total)
{ {
mPageNbr->setText(QString("%1 / %2").arg(current).arg(total)); mPageNbr->setText(QString("%1 / %2").arg(current).arg(total));
} }
...@@ -19,55 +19,55 @@ ...@@ -19,55 +19,55 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBNAVIGATORPALETTE_H #ifndef UBNAVIGATORPALETTE_H
#define UBNAVIGATORPALETTE_H #define UBNAVIGATORPALETTE_H
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QMouseEvent> #include <QMouseEvent>
#include <QResizeEvent> #include <QResizeEvent>
#include <QTimerEvent> #include <QTimerEvent>
#include <QLabel> #include <QLabel>
#include <QString> #include <QString>
#include "UBDockPalette.h" #include "UBDockPalette.h"
#include "UBDocumentNavigator.h" #include "UBDocumentNavigator.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
class UBNavigatorPalette : public UBDockPalette class UBNavigatorPalette : public UBDockPalette
{ {
Q_OBJECT Q_OBJECT
public: public:
UBNavigatorPalette(QWidget* parent=0, const char* name="navigatorPalette"); UBNavigatorPalette(QWidget* parent=0, const char* name="navigatorPalette");
~UBNavigatorPalette(); ~UBNavigatorPalette();
void setDocument(UBDocumentProxy* document); void setDocument(UBDocumentProxy* document);
void refresh(); void refresh();
public slots: public slots:
void setPageNumber(int current, int total); void setPageNumber(int current, int total);
protected: protected:
virtual void resizeEvent(QResizeEvent *event); virtual void resizeEvent(QResizeEvent *event);
virtual void timerEvent(QTimerEvent *event); virtual void timerEvent(QTimerEvent *event);
private: private:
void updateTime(); void updateTime();
/** The thumbnails navigator widget */ /** The thumbnails navigator widget */
UBDocumentNavigator* mNavigator; UBDocumentNavigator* mNavigator;
/** The layout */ /** The layout */
QVBoxLayout* mLayout; QVBoxLayout* mLayout;
QHBoxLayout* mHLayout; QHBoxLayout* mHLayout;
QLabel* mPageNbr; QLabel* mPageNbr;
QLabel* mClock; QLabel* mClock;
QString mTimeFormat; QString mTimeFormat;
int mTimerID; int mTimerID;
}; };
#endif // UBNAVIGATORPALETTE_H #endif // UBNAVIGATORPALETTE_H
...@@ -19,162 +19,162 @@ ...@@ -19,162 +19,162 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "UBPageNavigationWidget.h" #include "UBPageNavigationWidget.h"
#include "core/UBApplication.h" #include "core/UBApplication.h"
#include "board/UBBoardController.h" #include "board/UBBoardController.h"
#include "document/UBDocumentContainer.h" #include "document/UBDocumentContainer.h"
#include "globals/UBGlobals.h" #include "globals/UBGlobals.h"
#include "core/memcheck.h" #include "core/memcheck.h"
/** /**
* \brief Constructor * \brief Constructor
* @param parent as the parent widget * @param parent as the parent widget
* @param name as the object name * @param name as the object name
*/ */
UBPageNavigationWidget::UBPageNavigationWidget(QWidget *parent, const char *name):UBDockPaletteWidget(parent) UBPageNavigationWidget::UBPageNavigationWidget(QWidget *parent, const char *name):UBDockPaletteWidget(parent)
, mNavigator(NULL) , mNavigator(NULL)
, mLayout(NULL) , mLayout(NULL)
, mHLayout(NULL) , mHLayout(NULL)
, mPageNbr(NULL) , mPageNbr(NULL)
, mClock(NULL) , mClock(NULL)
{ {
setObjectName(name); setObjectName(name);
mName = "PageNavigator"; mName = "PageNavigator";
mVisibleState = true; mVisibleState = true;
SET_STYLE_SHEET(); SET_STYLE_SHEET();
mIconToRight = QPixmap(":images/pages_open.png"); mIconToRight = QPixmap(":images/pages_open.png");
mIconToLeft = QPixmap(":images/pages_close.png"); mIconToLeft = QPixmap(":images/pages_close.png");
// Build the gui // Build the gui
mLayout = new QVBoxLayout(this); mLayout = new QVBoxLayout(this);
setLayout(mLayout); setLayout(mLayout);
mNavigator = new UBDocumentNavigator(this); mNavigator = new UBDocumentNavigator(this);
mLayout->addWidget(mNavigator, 1); mLayout->addWidget(mNavigator, 1);
mHLayout = new QHBoxLayout(); mHLayout = new QHBoxLayout();
mLayout->addLayout(mHLayout, 0); mLayout->addLayout(mHLayout, 0);
mPageNbr = new QLabel(this); mPageNbr = new QLabel(this);
mClock = new QLabel(this); mClock = new QLabel(this);
mHLayout->addWidget(mPageNbr); mHLayout->addWidget(mPageNbr);
mHLayout->addWidget(mClock); mHLayout->addWidget(mClock);
// Configure the page number indicator // Configure the page number indicator
mPageNbr->setStyleSheet(QString("QLabel { color: white; background-color: transparent; border: none; font-family: Arial; font-weight: bold; font-size: 20px }")); mPageNbr->setStyleSheet(QString("QLabel { color: white; background-color: transparent; border: none; font-family: Arial; font-weight: bold; font-size: 20px }"));
setPageNumber(0, 0); setPageNumber(0, 0);
mPageNbr->setAlignment(Qt::AlignHCenter); mPageNbr->setAlignment(Qt::AlignHCenter);
// Configure the clock // Configure the clock
mClock->setStyleSheet(QString("QLabel {color: white; background-color: transparent; text-align: center; font-family: Arial; font-weight: bold; font-size: 20px}")); mClock->setStyleSheet(QString("QLabel {color: white; background-color: transparent; text-align: center; font-family: Arial; font-weight: bold; font-size: 20px}"));
mTimeFormat = QLocale::system().timeFormat(QLocale::ShortFormat); mTimeFormat = QLocale::system().timeFormat(QLocale::ShortFormat);
mClock->setAlignment(Qt::AlignHCenter); mClock->setAlignment(Qt::AlignHCenter);
//strip seconds //strip seconds
mTimeFormat = mTimeFormat.remove(":ss"); mTimeFormat = mTimeFormat.remove(":ss");
mTimeFormat = mTimeFormat.remove(":s"); mTimeFormat = mTimeFormat.remove(":s");
mTimerID = startTimer(1000); mTimerID = startTimer(1000);
} }
/** /**
* \brief Destructor * \brief Destructor
*/ */
UBPageNavigationWidget::~UBPageNavigationWidget() UBPageNavigationWidget::~UBPageNavigationWidget()
{ {
killTimer(mTimerID); killTimer(mTimerID);
if(NULL != mClock) if(NULL != mClock)
{ {
delete mClock; delete mClock;
mClock = NULL; mClock = NULL;
} }
if(NULL != mPageNbr) if(NULL != mPageNbr)
{ {
delete mPageNbr; delete mPageNbr;
mPageNbr = NULL; mPageNbr = NULL;
} }
if(NULL != mHLayout) if(NULL != mHLayout)
{ {
delete mHLayout; delete mHLayout;
mHLayout = NULL; mHLayout = NULL;
} }
if(NULL != mLayout) if(NULL != mLayout)
{ {
delete mLayout; delete mLayout;
mLayout = NULL; mLayout = NULL;
} }
if(NULL != mNavigator) if(NULL != mNavigator)
{ {
delete mNavigator; delete mNavigator;
mNavigator = NULL; mNavigator = NULL;
} }
} }
/** /**
* \brief Refresh the thumbnails widget * \brief Refresh the thumbnails widget
*/ */
void UBPageNavigationWidget::refresh() void UBPageNavigationWidget::refresh()
{ {
// TOLIK!!! // TOLIK!!!
// mNavigator->setDocument(UBApplication::boardController->activeDocument()); // mNavigator->setDocument(UBApplication::boardController->activeDocument());
} }
/** /**
* \brief Notify a timer event * \brief Notify a timer event
* @param event as the timer event * @param event as the timer event
*/ */
void UBPageNavigationWidget::timerEvent(QTimerEvent *event) void UBPageNavigationWidget::timerEvent(QTimerEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
updateTime(); updateTime();
} }
/** /**
* \brief Update the current time * \brief Update the current time
*/ */
void UBPageNavigationWidget::updateTime() void UBPageNavigationWidget::updateTime()
{ {
if (mClock) if (mClock)
{ {
mClock->setText(QLocale::system().toString (QTime::currentTime(), mTimeFormat)); mClock->setText(QLocale::system().toString (QTime::currentTime(), mTimeFormat));
} }
} }
/** /**
* \brief Set the page number * \brief Set the page number
* @param current as the current page * @param current as the current page
* @param total as the total number of pages * @param total as the total number of pages
*/ */
void UBPageNavigationWidget::setPageNumber(int current, int total) void UBPageNavigationWidget::setPageNumber(int current, int total)
{ {
mPageNbr->setText(QString("%1 / %2").arg(current).arg(UBDocumentContainer::sceneIndexFromPage(total))); mPageNbr->setText(QString("%1 / %2").arg(current).arg(UBDocumentContainer::sceneIndexFromPage(total)));
} }
/** /**
* \brief Get the custom margin value * \brief Get the custom margin value
* @return the custom margin value * @return the custom margin value
*/ */
int UBPageNavigationWidget::customMargin() int UBPageNavigationWidget::customMargin()
{ {
return 5; return 5;
} }
/** /**
* \brief Get the border value * \brief Get the border value
* @return the border value * @return the border value
*/ */
int UBPageNavigationWidget::border() int UBPageNavigationWidget::border()
{ {
return 15; return 15;
} }
...@@ -19,62 +19,62 @@ ...@@ -19,62 +19,62 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBPAGENAVIGATIONWIDGET_H #ifndef UBPAGENAVIGATIONWIDGET_H
#define UBPAGENAVIGATIONWIDGET_H #define UBPAGENAVIGATIONWIDGET_H
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QMouseEvent> #include <QMouseEvent>
#include <QResizeEvent> #include <QResizeEvent>
#include <QTimerEvent> #include <QTimerEvent>
#include <QLabel> #include <QLabel>
#include <QString> #include <QString>
#include "UBDocumentNavigator.h" #include "UBDocumentNavigator.h"
#include "UBDockPaletteWidget.h" #include "UBDockPaletteWidget.h"
#include "document/UBDocumentProxy.h" #include "document/UBDocumentProxy.h"
class UBPageNavigationWidget : public UBDockPaletteWidget class UBPageNavigationWidget : public UBDockPaletteWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
UBPageNavigationWidget(QWidget* parent=0, const char* name="UBPageNavigationWidget"); UBPageNavigationWidget(QWidget* parent=0, const char* name="UBPageNavigationWidget");
~UBPageNavigationWidget(); ~UBPageNavigationWidget();
//void setDocument(UBDocumentProxy* document); //void setDocument(UBDocumentProxy* document);
void refresh(); void refresh();
bool visibleInMode(eUBDockPaletteWidgetMode mode) bool visibleInMode(eUBDockPaletteWidgetMode mode)
{ {
return mode == eUBDockPaletteWidget_BOARD; return mode == eUBDockPaletteWidget_BOARD;
} }
signals: signals:
void resizeRequest(QResizeEvent* event); void resizeRequest(QResizeEvent* event);
public slots: public slots:
void setPageNumber(int current, int total); void setPageNumber(int current, int total);
protected: protected:
virtual void timerEvent(QTimerEvent *event); virtual void timerEvent(QTimerEvent *event);
private: private:
void updateTime(); void updateTime();
int customMargin(); int customMargin();
int border(); int border();
/** The thumbnails navigator widget */ /** The thumbnails navigator widget */
UBDocumentNavigator* mNavigator; UBDocumentNavigator* mNavigator;
/** The layout */ /** The layout */
QVBoxLayout* mLayout; QVBoxLayout* mLayout;
QHBoxLayout* mHLayout; QHBoxLayout* mHLayout;
QLabel* mPageNbr; QLabel* mPageNbr;
QLabel* mClock; QLabel* mClock;
QString mTimeFormat; QString mTimeFormat;
int mTimerID; int mTimerID;
}; };
#endif // UBPAGENAVIGATIONWIDGET_H #endif // UBPAGENAVIGATIONWIDGET_H
...@@ -19,922 +19,923 @@ ...@@ -19,922 +19,923 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QString>
#include <QCursor> #include <QString>
#include <QCursor>
#include "UBThumbnailWidget.h"
#include "UBRubberBand.h" #include "UBThumbnailWidget.h"
#include "UBMainWindow.h" #include "UBRubberBand.h"
#include "UBMainWindow.h"
#include "board/UBBoardController.h"
#include "board/UBBoardController.h"
#include "core/UBSettings.h"
#include "core/UBApplication.h" #include "core/UBSettings.h"
#include "core/UBApplication.h"
#include "document/UBDocumentProxy.h"
#include "document/UBDocumentController.h" #include "document/UBDocumentProxy.h"
#include "document/UBDocumentController.h"
#include "core/memcheck.h"
#include "core/memcheck.h"
UBThumbnailWidget::UBThumbnailWidget(QWidget* parent)
: QGraphicsView(parent) UBThumbnailWidget::UBThumbnailWidget(QWidget* parent)
, mThumbnailWidth(UBSettings::defaultThumbnailWidth) : QGraphicsView(parent)
, mSpacing(UBSettings::thumbnailSpacing) , mThumbnailWidth(UBSettings::defaultThumbnailWidth)
, mLastSelectedThumbnail(0) , mSpacing(UBSettings::thumbnailSpacing)
, mSelectionSpan(0) , mLastSelectedThumbnail(0)
, mPrevLassoRect(QRect()) , mSelectionSpan(0)
, mLassoRectItem(0) , mPrevLassoRect(QRect())
, mLassoRectItem(0)
{
// By default, the drag is possible {
bCanDrag = true; // By default, the drag is possible
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); bCanDrag = true;
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setFrameShape(QFrame::NoFrame); setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
setScene(&mThumbnailsScene); setFrameShape(QFrame::NoFrame);
setScene(&mThumbnailsScene);
setAlignment(Qt::AlignLeft | Qt::AlignTop);
setAlignment(Qt::AlignLeft | Qt::AlignTop);
connect(&mThumbnailsScene, SIGNAL(selectionChanged()), this, SLOT(sceneSelectionChanged()));
} connect(&mThumbnailsScene, SIGNAL(selectionChanged()), this, SLOT(sceneSelectionChanged()));
}
UBThumbnailWidget::~UBThumbnailWidget()
{ UBThumbnailWidget::~UBThumbnailWidget()
disconnect(&mThumbnailsScene, SIGNAL(selectionChanged())); {
} disconnect(&mThumbnailsScene, SIGNAL(selectionChanged()));
}
void UBThumbnailWidget::setThumbnailWidth(qreal pThumbnailWidth)
{ void UBThumbnailWidget::setThumbnailWidth(qreal pThumbnailWidth)
mThumbnailWidth = pThumbnailWidth; {
mThumbnailWidth = pThumbnailWidth;
refreshScene();
} refreshScene();
}
void UBThumbnailWidget::setSpacing(qreal pSpacing)
{ void UBThumbnailWidget::setSpacing(qreal pSpacing)
mSpacing = pSpacing; {
mSpacing = pSpacing;
refreshScene();
} refreshScene();
}
void UBThumbnailWidget::setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems
, const QList<QUrl>& pItemsPaths void UBThumbnailWidget::setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems
, const QStringList pLabels , const QList<QUrl>& pItemsPaths
, const QString& pMimeType) , const QStringList pLabels
{ , const QString& pMimeType)
mGraphicItems = pGraphicsItems; {
mItemsPaths = pItemsPaths; mGraphicItems = pGraphicsItems;
mMimeType = pMimeType; mItemsPaths = pItemsPaths;
mLabels = pLabels; mMimeType = pMimeType;
mLabels = pLabels;
foreach(QGraphicsItem* it, mThumbnailsScene.items())
{ foreach(QGraphicsItem* it, mThumbnailsScene.items())
mThumbnailsScene.removeItem(it, true); {
} mThumbnailsScene.removeItem(it, true);
}
// set lasso to 0 as it has been cleared as well
mLassoRectItem = 0; // set lasso to 0 as it has been cleared as well
mLassoRectItem = 0;
foreach (QGraphicsItem* item, pGraphicsItems)
{ foreach (QGraphicsItem* item, pGraphicsItems)
if (item->scene() != &mThumbnailsScene) {
{ if (item->scene() != &mThumbnailsScene)
mThumbnailsScene.addItem(item); {
} mThumbnailsScene.addItem(item);
} }
}
mLabelsItems.clear();
mLabelsItems.clear();
foreach (const QString label, pLabels)
{ foreach (const QString label, pLabels)
QFontMetrics fm(font()); {
UBThumbnailTextItem *labelItem = QFontMetrics fm(font());
new UBThumbnailTextItem(label); // deleted while replace or by the scene destruction UBThumbnailTextItem *labelItem =
new UBThumbnailTextItem(label); // deleted while replace or by the scene destruction
mThumbnailsScene.addItem(labelItem);
mLabelsItems << labelItem; mThumbnailsScene.addItem(labelItem);
} mLabelsItems << labelItem;
}
refreshScene();
refreshScene();
mLastSelectedThumbnail = 0;
} mLastSelectedThumbnail = 0;
}
void UBThumbnailWidget::refreshScene()
{ void UBThumbnailWidget::refreshScene()
int nbColumns = (geometry().width() - mSpacing) / (mThumbnailWidth + mSpacing); {
int nbColumns = (geometry().width() - mSpacing) / (mThumbnailWidth + mSpacing);
int labelSpacing = 0;
int labelSpacing = 0;
if (mLabelsItems.size() > 0)
{ if (mLabelsItems.size() > 0)
QFontMetrics fm(mLabelsItems.at(0)->font()); {
labelSpacing = UBSettings::thumbnailSpacing + fm.height(); // TODO UB 4.x where is 20 from ??? configure ?? compute based on mSpacing ?? JBA Is it the font height? QFontMetrics fm(mLabelsItems.at(0)->font());
} labelSpacing = UBSettings::thumbnailSpacing + fm.height(); // TODO UB 4.x where is 20 from ??? configure ?? compute based on mSpacing ?? JBA Is it the font height?
nbColumns = qMax(nbColumns, 1); }
nbColumns = qMax(nbColumns, 1);
qreal thumbnailHeight = mThumbnailWidth / UBSettings::minScreenRatio;
qreal thumbnailHeight = mThumbnailWidth / UBSettings::minScreenRatio;
for (int i = 0; i < mGraphicItems.size(); i++)
{ for (int i = 0; i < mGraphicItems.size(); i++)
QGraphicsItem* item = mGraphicItems.at(i); {
QGraphicsItem* item = mGraphicItems.at(i);
qreal scaleWidth = mThumbnailWidth / item->boundingRect().width();
qreal scaleHeight = thumbnailHeight / item->boundingRect().height(); qreal scaleWidth = mThumbnailWidth / item->boundingRect().width();
qreal scaleHeight = thumbnailHeight / item->boundingRect().height();
qreal scaleFactor = qMin(scaleWidth, scaleHeight);
qreal scaleFactor = qMin(scaleWidth, scaleHeight);
//bitmap should not be stretched
UBThumbnail* pix = dynamic_cast<UBThumbnail*>(item); //bitmap should not be stretched
if (pix) UBThumbnail* pix = dynamic_cast<UBThumbnail*>(item);
scaleFactor = qMin(scaleFactor, 1.0); if (pix)
scaleFactor = qMin(scaleFactor, 1.0);
QTransform transform;
transform.scale(scaleFactor, scaleFactor); QTransform transform;
transform.scale(scaleFactor, scaleFactor);
item->setTransform(transform);
item->setTransform(transform);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
int columnIndex = i % nbColumns;
int rowIndex = i / nbColumns; int columnIndex = i % nbColumns;
int rowIndex = i / nbColumns;
if (pix)
{ if (pix)
pix->setColumn(columnIndex); {
pix->setRow(rowIndex); pix->setColumn(columnIndex);
} pix->setRow(rowIndex);
}
int w = item->boundingRect().width();
int h = item->boundingRect().height(); int w = item->boundingRect().width();
QPointF pos( int h = item->boundingRect().height();
mSpacing + (mThumbnailWidth - w * scaleFactor) / 2 + columnIndex * (mThumbnailWidth + mSpacing), QPointF pos(
mSpacing + rowIndex * (thumbnailHeight + mSpacing + labelSpacing) + (thumbnailHeight - h * scaleFactor) / 2); mSpacing + (mThumbnailWidth - w * scaleFactor) / 2 + columnIndex * (mThumbnailWidth + mSpacing),
mSpacing + rowIndex * (thumbnailHeight + mSpacing + labelSpacing) + (thumbnailHeight - h * scaleFactor) / 2);
item->setPos(pos);
item->setPos(pos);
if (mLabelsItems.size() > i)
{ if (mLabelsItems.size() > i)
QFontMetrics fm(mLabelsItems.at(i)->font(), this); {
QString elidedText = fm.elidedText(mLabels.at(i), Qt::ElideRight, mThumbnailWidth); QFontMetrics fm(mLabelsItems.at(i)->font(), this);
QString elidedText = fm.elidedText(mLabels.at(i), Qt::ElideRight, mThumbnailWidth);
mLabelsItems.at(i)->setPlainText(elidedText);
mLabelsItems.at(i)->setWidth(fm.width(elidedText) + 2 * mLabelsItems.at(i)->document()->documentMargin()); mLabelsItems.at(i)->setPlainText(elidedText);
mLabelsItems.at(i)->setWidth(fm.width(elidedText) + 2 * mLabelsItems.at(i)->document()->documentMargin());
pos.setY(pos.y() + (thumbnailHeight + h * scaleFactor) / 2 + 5);
qreal labelWidth = fm.width(elidedText); pos.setY(pos.y() + (thumbnailHeight + h * scaleFactor) / 2 + 5);
pos.setX(mSpacing + (mThumbnailWidth - labelWidth) / 2 + columnIndex * (mThumbnailWidth + mSpacing)); qreal labelWidth = fm.width(elidedText);
mLabelsItems.at(i)->setPos(pos); pos.setX(mSpacing + (mThumbnailWidth - labelWidth) / 2 + columnIndex * (mThumbnailWidth + mSpacing));
} mLabelsItems.at(i)->setPos(pos);
} }
}
QScrollBar *vertScrollBar = verticalScrollBar();
int scrollBarThickness = 0; QScrollBar *vertScrollBar = verticalScrollBar();
if (vertScrollBar && vertScrollBar->isVisible()) int scrollBarThickness = 0;
scrollBarThickness = vertScrollBar->width(); if (vertScrollBar && vertScrollBar->isVisible())
scrollBarThickness = vertScrollBar->width();
setSceneRect(0, 0,
geometry().width() - scrollBarThickness, setSceneRect(0, 0,
mSpacing + ((((mGraphicItems.size() - 1) / nbColumns) + 1) * (thumbnailHeight + mSpacing + labelSpacing))); geometry().width() - scrollBarThickness,
} mSpacing + ((((mGraphicItems.size() - 1) / nbColumns) + 1) * (thumbnailHeight + mSpacing + labelSpacing)));
}
QList<QGraphicsItem*> UBThumbnailWidget::selectedItems()
{ QList<QGraphicsItem*> UBThumbnailWidget::selectedItems()
QList<QGraphicsItem*> sortedSelectedItems = mThumbnailsScene.selectedItems(); {
qSort(sortedSelectedItems.begin(), sortedSelectedItems.end(), thumbnailLessThan); QList<QGraphicsItem*> sortedSelectedItems = mThumbnailsScene.selectedItems();
return sortedSelectedItems; qSort(sortedSelectedItems.begin(), sortedSelectedItems.end(), thumbnailLessThan);
} return sortedSelectedItems;
}
void UBThumbnailWidget::mousePressEvent(QMouseEvent *event)
{ void UBThumbnailWidget::mousePressEvent(QMouseEvent *event)
mClickTime = QTime::currentTime(); {
mMousePressPos = event->pos(); mClickTime = QTime::currentTime();
mMousePressPos = event->pos();
UBSceneThumbnailPixmap* sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(itemAt(mMousePressPos));
if(sceneItem==NULL) UBSceneThumbnailPixmap* sceneItem = dynamic_cast<UBSceneThumbnailPixmap*>(itemAt(mMousePressPos));
{ if(sceneItem==NULL)
event->ignore(); {
return; event->ignore();
} return;
//if(sceneItem){ }
// int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneItem->sceneIndex()); //if(sceneItem){
// if(pageIndex == 0){ // int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneItem->sceneIndex());
// event->ignore(); // if(pageIndex == 0){
// return; // event->ignore();
// } // return;
//} // }
//}
mMousePressScenePos = mapToScene(mMousePressPos);
QGraphicsItem* underlyingItem = itemAt(mMousePressPos); mMousePressScenePos = mapToScene(mMousePressPos);
UBThumbnail *previousSelectedThumbnail = mLastSelectedThumbnail; QGraphicsItem* underlyingItem = itemAt(mMousePressPos);
UBThumbnail *previousSelectedThumbnail = mLastSelectedThumbnail;
if (!dynamic_cast<UBThumbnail*>(underlyingItem))
{ if (!dynamic_cast<UBThumbnail*>(underlyingItem))
deleteLasso(); {
deleteLasso();
UBRubberBand rubberBand(QRubberBand::Rectangle);
QStyleOption option; UBRubberBand rubberBand(QRubberBand::Rectangle);
option.initFrom(&rubberBand); QStyleOption option;
option.initFrom(&rubberBand);
mPrevLassoRect = QRect();
mLassoRectItem = new QGraphicsRectItem(0, scene()); mPrevLassoRect = QRect();
mLassoRectItem = new QGraphicsRectItem(0, scene());
#ifdef Q_WS_MAC
// The following code must stay in synch with <Qt installation folder>\src\gui\styles\qmacstyle_mac.mm #ifdef Q_WS_MAC
QColor strokeColor; // The following code must stay in synch with <Qt installation folder>\src\gui\styles\qmacstyle_mac.mm
strokeColor.setHsvF(0, 0, 0.86, 1.0); QColor strokeColor;
mLassoRectItem->setPen(QPen(strokeColor)); strokeColor.setHsvF(0, 0, 0.86, 1.0);
QColor fillColor(option.palette.color(QPalette::Disabled, QPalette::Highlight)); mLassoRectItem->setPen(QPen(strokeColor));
fillColor.setHsvF(0, 0, 0.53, 0.25); QColor fillColor(option.palette.color(QPalette::Disabled, QPalette::Highlight));
mLassoRectItem->setBrush(fillColor); fillColor.setHsvF(0, 0, 0.53, 0.25);
#else mLassoRectItem->setBrush(fillColor);
// The following code must stay in synch with <Qt installation folder>\src\gui\styles\qwindowsxpstyle.cpp #else
QColor highlight = option.palette.color(QPalette::Active, QPalette::Highlight); // The following code must stay in synch with <Qt installation folder>\src\gui\styles\qwindowsxpstyle.cpp
mLassoRectItem->setPen(highlight.darker(120)); QColor highlight = option.palette.color(QPalette::Active, QPalette::Highlight);
QColor dimHighlight(qMin(highlight.red() / 2 + 110, 255), mLassoRectItem->setPen(highlight.darker(120));
qMin(highlight.green() / 2 + 110, 255), QColor dimHighlight(qMin(highlight.red() / 2 + 110, 255),
qMin(highlight.blue() / 2 + 110, 255), qMin(highlight.green() / 2 + 110, 255),
127); qMin(highlight.blue() / 2 + 110, 255),
mLassoRectItem->setBrush(dimHighlight); 127);
#endif mLassoRectItem->setBrush(dimHighlight);
#endif
mLassoRectItem->setZValue(10000);
mLassoRectItem->setRect(QRectF(mMousePressScenePos, QSizeF())); mLassoRectItem->setZValue(10000);
mLassoRectItem->setRect(QRectF(mMousePressScenePos, QSizeF()));
if (Qt::ControlModifier & event->modifiers() || Qt::ShiftModifier & event->modifiers())
{ if (Qt::ControlModifier & event->modifiers() || Qt::ShiftModifier & event->modifiers())
// mSelectedThumbnailItems = selectedItems().toSet(); {
return; // mSelectedThumbnailItems = selectedItems().toSet();
} return;
}
mSelectedThumbnailItems.clear();
mPreviouslyIncrementalSelectedItemsX.clear(); mSelectedThumbnailItems.clear();
mPreviouslyIncrementalSelectedItemsY.clear(); mPreviouslyIncrementalSelectedItemsX.clear();
QGraphicsView::mousePressEvent(event); mPreviouslyIncrementalSelectedItemsY.clear();
} QGraphicsView::mousePressEvent(event);
else if (Qt::ShiftModifier & event->modifiers()) }
{ else if (Qt::ShiftModifier & event->modifiers())
if (previousSelectedThumbnail) {
{ if (previousSelectedThumbnail)
QGraphicsItem* previousSelectedItem = dynamic_cast<QGraphicsItem*>(previousSelectedThumbnail); {
if (previousSelectedItem) QGraphicsItem* previousSelectedItem = dynamic_cast<QGraphicsItem*>(previousSelectedThumbnail);
{ if (previousSelectedItem)
int index1 = mGraphicItems.indexOf(previousSelectedItem); {
int index2 = mGraphicItems.indexOf(underlyingItem); int index1 = mGraphicItems.indexOf(previousSelectedItem);
if (-1 == index2) int index2 = mGraphicItems.indexOf(underlyingItem);
{ if (-1 == index2)
mSelectedThumbnailItems = selectedItems().toSet(); {
return; mSelectedThumbnailItems = selectedItems().toSet();
} return;
mSelectionSpan = index2 - index1; }
selectItems(qMin(index1, index2), mSelectionSpan < 0 ? - mSelectionSpan + 1 : mSelectionSpan + 1); mSelectionSpan = index2 - index1;
return; selectItems(qMin(index1, index2), mSelectionSpan < 0 ? - mSelectionSpan + 1 : mSelectionSpan + 1);
} return;
} }
} }
else }
{ else
mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(underlyingItem); {
if (!underlyingItem->isSelected()) mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(underlyingItem);
{ if (!underlyingItem->isSelected())
int index = mGraphicItems.indexOf(underlyingItem); {
selectItemAt(index, Qt::ControlModifier & event->modifiers()); int index = mGraphicItems.indexOf(underlyingItem);
} selectItemAt(index, Qt::ControlModifier & event->modifiers());
else }
{ else
QGraphicsView::mousePressEvent(event); {
} QGraphicsView::mousePressEvent(event);
if (!mLastSelectedThumbnail && mGraphicItems.count() > 0) }
mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.at(0)); if (!mLastSelectedThumbnail && mGraphicItems.count() > 0)
mSelectionSpan = 0; mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.at(0));
return; mSelectionSpan = 0;
} return;
} }
}
void UBThumbnailWidget::mouseMoveEvent(QMouseEvent *event)
{ void UBThumbnailWidget::mouseMoveEvent(QMouseEvent *event)
int distance = (mMousePressPos - event->pos()).manhattanLength(); {
int distance = (mMousePressPos - event->pos()).manhattanLength();
if (0 == (event->buttons() & Qt::LeftButton) || distance < QApplication::startDragDistance())
return; if (0 == (event->buttons() & Qt::LeftButton) || distance < QApplication::startDragDistance())
return;
if (mLassoRectItem)
{ if (mLassoRectItem)
bSelectionInProgress = true; {
int incrementLassoMinWidth = 2; bSelectionInProgress = true;
QPointF currentScenePos = mapToScene(event->pos()); int incrementLassoMinWidth = 2;
QRectF lassoRect( QPointF currentScenePos = mapToScene(event->pos());
qMin(mMousePressScenePos.x(), currentScenePos.x()), qMin(mMousePressScenePos.y(), currentScenePos.y()), QRectF lassoRect(
qAbs(mMousePressScenePos.x() - currentScenePos.x()), qAbs(mMousePressScenePos.y() - currentScenePos.y())); qMin(mMousePressScenePos.x(), currentScenePos.x()), qMin(mMousePressScenePos.y(), currentScenePos.y()),
if (QPoint() == prevMoveMousePos) qAbs(mMousePressScenePos.x() - currentScenePos.x()), qAbs(mMousePressScenePos.y() - currentScenePos.y()));
prevMoveMousePos = currentScenePos; if (QPoint() == prevMoveMousePos)
QRectF incrementXSelection( prevMoveMousePos = currentScenePos;
qMin(prevMoveMousePos.x(), currentScenePos.x()), qMin(mMousePressScenePos.y(), currentScenePos.y()), QRectF incrementXSelection(
qAbs(prevMoveMousePos.x() - currentScenePos.x())+incrementLassoMinWidth, qAbs(mMousePressScenePos.y() - currentScenePos.y())); qMin(prevMoveMousePos.x(), currentScenePos.x()), qMin(mMousePressScenePos.y(), currentScenePos.y()),
QRectF incrementYSelection( qAbs(prevMoveMousePos.x() - currentScenePos.x())+incrementLassoMinWidth, qAbs(mMousePressScenePos.y() - currentScenePos.y()));
qMin(mMousePressScenePos.x(), currentScenePos.x()), qMin(prevMoveMousePos.y(), currentScenePos.y()), QRectF incrementYSelection(
qAbs(mMousePressScenePos.x() - currentScenePos.x()), qAbs(prevMoveMousePos.y() - currentScenePos.y())+incrementLassoMinWidth); qMin(mMousePressScenePos.x(), currentScenePos.x()), qMin(prevMoveMousePos.y(), currentScenePos.y()),
qAbs(mMousePressScenePos.x() - currentScenePos.x()), qAbs(prevMoveMousePos.y() - currentScenePos.y())+incrementLassoMinWidth);
prevMoveMousePos = currentScenePos;
mLassoRectItem->setRect(lassoRect); prevMoveMousePos = currentScenePos;
mLassoRectItem->setRect(lassoRect);
QSet<QGraphicsItem*> lassoSelectedThumbnailItems;
QSet<QGraphicsItem*> lassoSelectedThumbnailItems;
QSet<QGraphicsItem*> toUnset;
QSet<QGraphicsItem*> toSet; QSet<QGraphicsItem*> toUnset;
QSet<QGraphicsItem*> toSet;
// for horizontal moving
QSet<QGraphicsItem*> incSelectedItemsX = scene()->items(incrementXSelection, Qt::IntersectsItemBoundingRect).toSet(); // for horizontal moving
foreach (QGraphicsItem *lassoSelectedItem, incSelectedItemsX) QSet<QGraphicsItem*> incSelectedItemsX = scene()->items(incrementXSelection, Qt::IntersectsItemBoundingRect).toSet();
{ foreach (QGraphicsItem *lassoSelectedItem, incSelectedItemsX)
if (lassoSelectedItem) {
{ if (lassoSelectedItem)
UBSceneThumbnailPixmap *thumbnailItem = dynamic_cast<UBSceneThumbnailPixmap*>(lassoSelectedItem); {
if (thumbnailItem) UBSceneThumbnailPixmap *thumbnailItem = dynamic_cast<UBSceneThumbnailPixmap*>(lassoSelectedItem);
lassoSelectedThumbnailItems += lassoSelectedItem; if (thumbnailItem)
} lassoSelectedThumbnailItems += lassoSelectedItem;
} }
}
if(lassoRect.width() < mPrevLassoRect.width())
{ if(lassoRect.width() < mPrevLassoRect.width())
if (!lassoSelectedThumbnailItems.contains(mPreviouslyIncrementalSelectedItemsX)) {
toUnset += mPreviouslyIncrementalSelectedItemsX - lassoSelectedThumbnailItems; if (!lassoSelectedThumbnailItems.contains(mPreviouslyIncrementalSelectedItemsX))
toUnset += mPreviouslyIncrementalSelectedItemsX - lassoSelectedThumbnailItems;
}
mPreviouslyIncrementalSelectedItemsX = lassoSelectedThumbnailItems; }
mPreviouslyIncrementalSelectedItemsX = lassoSelectedThumbnailItems;
toSet += lassoSelectedThumbnailItems + mPreviouslyIncrementalSelectedItemsX;
toSet += lassoSelectedThumbnailItems + mPreviouslyIncrementalSelectedItemsX;
lassoSelectedThumbnailItems.clear();
lassoSelectedThumbnailItems.clear();
// for vertical moving
// for vertical moving
QSet<QGraphicsItem*> incSelectedItemsY = scene()->items(incrementYSelection, Qt::IntersectsItemBoundingRect).toSet();
foreach (QGraphicsItem *lassoSelectedItem, incSelectedItemsY) QSet<QGraphicsItem*> incSelectedItemsY = scene()->items(incrementYSelection, Qt::IntersectsItemBoundingRect).toSet();
{ foreach (QGraphicsItem *lassoSelectedItem, incSelectedItemsY)
if (lassoSelectedItem) {
{ if (lassoSelectedItem)
UBSceneThumbnailPixmap *thumbnailItem = dynamic_cast<UBSceneThumbnailPixmap*>(lassoSelectedItem); {
UBSceneThumbnailPixmap *thumbnailItem = dynamic_cast<UBSceneThumbnailPixmap*>(lassoSelectedItem);
if (thumbnailItem)
lassoSelectedThumbnailItems += lassoSelectedItem; if (thumbnailItem)
} lassoSelectedThumbnailItems += lassoSelectedItem;
} }
}
if(lassoRect.height() < mPrevLassoRect.height())
{ if(lassoRect.height() < mPrevLassoRect.height())
if (!lassoSelectedThumbnailItems.contains(mPreviouslyIncrementalSelectedItemsY)) {
toUnset += mPreviouslyIncrementalSelectedItemsY - lassoSelectedThumbnailItems; if (!lassoSelectedThumbnailItems.contains(mPreviouslyIncrementalSelectedItemsY))
toUnset += mPreviouslyIncrementalSelectedItemsY - lassoSelectedThumbnailItems;
}
mPreviouslyIncrementalSelectedItemsY = lassoSelectedThumbnailItems; }
mPreviouslyIncrementalSelectedItemsY = lassoSelectedThumbnailItems;
toSet += lassoSelectedThumbnailItems + mPreviouslyIncrementalSelectedItemsY;
toSet += lassoSelectedThumbnailItems + mPreviouslyIncrementalSelectedItemsY;
toSet -= toUnset;
toSet -= toUnset;
foreach (QGraphicsItem *item, toSet)
{ foreach (QGraphicsItem *item, toSet)
item->setSelected(true); {
} item->setSelected(true);
}
foreach (QGraphicsItem *item, toUnset)
{ foreach (QGraphicsItem *item, toUnset)
item->setSelected(false); {
} item->setSelected(false);
}
mSelectedThumbnailItems += lassoSelectedThumbnailItems;
mPrevLassoRect = lassoRect; mSelectedThumbnailItems += lassoSelectedThumbnailItems;
mPrevLassoRect = lassoRect;
if (Qt::ControlModifier & event->modifiers())
{ if (Qt::ControlModifier & event->modifiers())
for (int i = 0; i < mSelectedThumbnailItems.count()-1; i++) {
{ for (int i = 0; i < mSelectedThumbnailItems.count()-1; i++)
mSelectedThumbnailItems.values().at(i)->setSelected(true); {
} mSelectedThumbnailItems.values().at(i)->setSelected(true);
} }
} }
else }
{ else
bSelectionInProgress = false; {
if (0 == selectedItems().size()) bSelectionInProgress = false;
return; if (0 == selectedItems().size())
return;
if(bCanDrag)
{ if(bCanDrag)
QDrag *drag = new QDrag(this); {
QMimeData *mime = new QMimeData(); QDrag *drag = new QDrag(this);
QMimeData *mime = new QMimeData();
if (mMimeType.length() > 0)
mime->setData(mMimeType, QByteArray()); // trick the d&d system to register our own mime type if (mMimeType.length() > 0)
mime->setData(mMimeType, QByteArray()); // trick the d&d system to register our own mime type
drag->setMimeData(mime);
drag->setMimeData(mime);
QList<QUrl> qlElements;
QList<QUrl> qlElements;
foreach (QGraphicsItem* item, selectedItems())
{ foreach (QGraphicsItem* item, selectedItems())
if (mGraphicItems.contains(item)) {
{ if (mGraphicItems.contains(item))
if (mGraphicItems.indexOf(item) <= mItemsPaths.size()){ {
qlElements << mItemsPaths.at(mGraphicItems.indexOf(item)); if (mGraphicItems.indexOf(item) <= mItemsPaths.size()){
} qlElements << mItemsPaths.at(mGraphicItems.indexOf(item));
} }
} }
}
if (qlElements.size() > 0){
mime->setUrls(qlElements); if (qlElements.size() > 0){
drag->setMimeData(mime); mime->setUrls(qlElements);
drag->exec(Qt::CopyAction); drag->setMimeData(mime);
} drag->exec(Qt::CopyAction);
} }
} }
}
QGraphicsView::mouseMoveEvent(event);
} QGraphicsView::mouseMoveEvent(event);
}
void UBThumbnailWidget::mouseReleaseEvent(QMouseEvent *event)
{ void UBThumbnailWidget::mouseReleaseEvent(QMouseEvent *event)
int elapsedTimeSincePress = mClickTime.elapsed(); {
prevMoveMousePos = QPoint(); int elapsedTimeSincePress = mClickTime.elapsed();
deleteLasso(); prevMoveMousePos = QPoint();
QGraphicsView::mouseReleaseEvent(event); deleteLasso();
QGraphicsView::mouseReleaseEvent(event);
if(elapsedTimeSincePress < STARTDRAGTIME) {
emit mouseClick(itemAt(event->pos()), 0); if(elapsedTimeSincePress < STARTDRAGTIME) {
} emit mouseClick(itemAt(event->pos()), 0);
} }
}
void UBThumbnailWidget::keyPressEvent(QKeyEvent *event)
{ void UBThumbnailWidget::keyPressEvent(QKeyEvent *event)
if (mLastSelectedThumbnail) {
{ if (mLastSelectedThumbnail)
QGraphicsItem *lastSelectedGraphicsItem = dynamic_cast<QGraphicsItem*>(mLastSelectedThumbnail); {
if (!lastSelectedGraphicsItem) return; QGraphicsItem *lastSelectedGraphicsItem = dynamic_cast<QGraphicsItem*>(mLastSelectedThumbnail);
int startSelectionIndex = mGraphicItems.indexOf(lastSelectedGraphicsItem); if (!lastSelectedGraphicsItem) return;
int previousSelectedThumbnailIndex = startSelectionIndex + mSelectionSpan; int startSelectionIndex = mGraphicItems.indexOf(lastSelectedGraphicsItem);
int previousSelectedThumbnailIndex = startSelectionIndex + mSelectionSpan;
switch (event->key())
{ switch (event->key())
case Qt::Key_Down: {
case Qt::Key_Up: case Qt::Key_Down:
{ case Qt::Key_Up:
if (rowCount() <= 1) break; {
if (Qt::ShiftModifier & event->modifiers()) if (rowCount() <= 1) break;
{ if (Qt::ShiftModifier & event->modifiers())
int endSelectionIndex; {
if (Qt::Key_Down == event->key()) int endSelectionIndex;
{ if (Qt::Key_Down == event->key())
endSelectionIndex = previousSelectedThumbnailIndex + columnCount(); {
if (endSelectionIndex >= mGraphicItems.count()) break; endSelectionIndex = previousSelectedThumbnailIndex + columnCount();
} if (endSelectionIndex >= mGraphicItems.count()) break;
else }
{ else
endSelectionIndex = previousSelectedThumbnailIndex - columnCount(); {
if (endSelectionIndex < 0) break; endSelectionIndex = previousSelectedThumbnailIndex - columnCount();
} if (endSelectionIndex < 0) break;
}
int startIndex = startSelectionIndex < endSelectionIndex ? startSelectionIndex : endSelectionIndex;
int count = startSelectionIndex < endSelectionIndex ? endSelectionIndex - startSelectionIndex + 1 : startSelectionIndex - endSelectionIndex + 1; int startIndex = startSelectionIndex < endSelectionIndex ? startSelectionIndex : endSelectionIndex;
mSelectionSpan = startSelectionIndex < endSelectionIndex ? (count - 1) : - (count - 1); int count = startSelectionIndex < endSelectionIndex ? endSelectionIndex - startSelectionIndex + 1 : startSelectionIndex - endSelectionIndex + 1;
selectItems(startIndex, count); mSelectionSpan = startSelectionIndex < endSelectionIndex ? (count - 1) : - (count - 1);
} selectItems(startIndex, count);
else }
{ else
int toSelectIndex; {
if (Qt::Key_Down == event->key()) int toSelectIndex;
{ if (Qt::Key_Down == event->key())
toSelectIndex = previousSelectedThumbnailIndex + columnCount(); {
if (toSelectIndex >= mGraphicItems.count()) break; toSelectIndex = previousSelectedThumbnailIndex + columnCount();
} if (toSelectIndex >= mGraphicItems.count()) break;
else }
{ else
toSelectIndex = previousSelectedThumbnailIndex - columnCount(); {
if (toSelectIndex < 0) break; toSelectIndex = previousSelectedThumbnailIndex - columnCount();
} if (toSelectIndex < 0) break;
}
selectItemAt(toSelectIndex, Qt::ControlModifier & event->modifiers());
mSelectionSpan = 0; selectItemAt(toSelectIndex, Qt::ControlModifier & event->modifiers());
} mSelectionSpan = 0;
} }
break; }
break;
case Qt::Key_Left:
case Qt::Key_Right: case Qt::Key_Left:
{ case Qt::Key_Right:
QGraphicsItem *previousSelectedItem = mGraphicItems.at(previousSelectedThumbnailIndex); {
UBThumbnail *previousSelectedThumbnail = dynamic_cast<UBThumbnail*>(previousSelectedItem); QGraphicsItem *previousSelectedItem = mGraphicItems.at(previousSelectedThumbnailIndex);
if (!previousSelectedThumbnail) break; UBThumbnail *previousSelectedThumbnail = dynamic_cast<UBThumbnail*>(previousSelectedItem);
if (!previousSelectedThumbnail) break;
if (Qt::Key_Left == event->key())
{ if (Qt::Key_Left == event->key())
if (0 == previousSelectedThumbnail->column()) break; {
} if (0 == previousSelectedThumbnail->column()) break;
else }
{ else
if (previousSelectedThumbnail->column() == columnCount() - 1 || {
previousSelectedThumbnailIndex == mGraphicItems.count() - 1) break; if (previousSelectedThumbnail->column() == columnCount() - 1 ||
} previousSelectedThumbnailIndex == mGraphicItems.count() - 1) break;
}
if (Qt::ShiftModifier & event->modifiers())
{ if (Qt::ShiftModifier & event->modifiers())
int endSelectionIndex; {
if (Qt::Key_Left == event->key()) int endSelectionIndex;
{ if (Qt::Key_Left == event->key())
endSelectionIndex = previousSelectedThumbnailIndex - 1; {
if (endSelectionIndex < 0) break; endSelectionIndex = previousSelectedThumbnailIndex - 1;
} if (endSelectionIndex < 0) break;
else }
{ else
endSelectionIndex = previousSelectedThumbnailIndex + 1; {
if (endSelectionIndex >= mGraphicItems.count()) break; endSelectionIndex = previousSelectedThumbnailIndex + 1;
} if (endSelectionIndex >= mGraphicItems.count()) break;
}
int startIndex = startSelectionIndex < endSelectionIndex ? startSelectionIndex : endSelectionIndex;
int count = startSelectionIndex < endSelectionIndex ? endSelectionIndex - startSelectionIndex + 1 : startSelectionIndex - endSelectionIndex + 1; int startIndex = startSelectionIndex < endSelectionIndex ? startSelectionIndex : endSelectionIndex;
mSelectionSpan = startSelectionIndex < endSelectionIndex ? (count - 1) : - (count - 1); int count = startSelectionIndex < endSelectionIndex ? endSelectionIndex - startSelectionIndex + 1 : startSelectionIndex - endSelectionIndex + 1;
selectItems(startIndex, count); mSelectionSpan = startSelectionIndex < endSelectionIndex ? (count - 1) : - (count - 1);
} selectItems(startIndex, count);
else }
{ else
if (Qt::Key_Left == event->key()) {
selectItemAt(previousSelectedThumbnailIndex - 1, Qt::ControlModifier & event->modifiers()); if (Qt::Key_Left == event->key())
else selectItemAt(previousSelectedThumbnailIndex - 1, Qt::ControlModifier & event->modifiers());
selectItemAt(previousSelectedThumbnailIndex + 1, Qt::ControlModifier & event->modifiers()); else
selectItemAt(previousSelectedThumbnailIndex + 1, Qt::ControlModifier & event->modifiers());
mSelectionSpan = 0;
} mSelectionSpan = 0;
} }
break; }
break;
case Qt::Key_Home:
{ case Qt::Key_Home:
if (Qt::ShiftModifier & event->modifiers()) {
{ if (Qt::ShiftModifier & event->modifiers())
mSelectionSpan = - startSelectionIndex; {
selectItems(0, startSelectionIndex + 1); mSelectionSpan = - startSelectionIndex;
} selectItems(0, startSelectionIndex + 1);
else }
{ else
selectItemAt(0, Qt::ControlModifier & event->modifiers()); {
mSelectionSpan = 0; selectItemAt(0, Qt::ControlModifier & event->modifiers());
} mSelectionSpan = 0;
} }
break; }
break;
case Qt::Key_End:
{ case Qt::Key_End:
if (Qt::ShiftModifier & event->modifiers()) {
{ if (Qt::ShiftModifier & event->modifiers())
mSelectionSpan = mGraphicItems.count() - startSelectionIndex - 1; {
selectItems(startSelectionIndex, mSelectionSpan + 1); mSelectionSpan = mGraphicItems.count() - startSelectionIndex - 1;
} selectItems(startSelectionIndex, mSelectionSpan + 1);
else }
{ else
selectItemAt(mGraphicItems.count() - 1, Qt::ControlModifier & event->modifiers()); {
mSelectionSpan = 0; selectItemAt(mGraphicItems.count() - 1, Qt::ControlModifier & event->modifiers());
} mSelectionSpan = 0;
} }
break; }
case Qt::Key_A: break;
{ case Qt::Key_A:
if (Qt::ControlModifier & event->modifiers()) {
selectAll(); if (Qt::ControlModifier & event->modifiers())
} selectAll();
break; }
} break;
} }
QGraphicsView::keyPressEvent(event); }
} QGraphicsView::keyPressEvent(event);
}
void UBThumbnailWidget::focusInEvent(QFocusEvent *event)
{ void UBThumbnailWidget::focusInEvent(QFocusEvent *event)
Q_UNUSED(event); {
Q_UNUSED(event);
if (0 == selectedItems().count() && mGraphicItems.count() > 0 && Qt::TabFocusReason == event->reason())
{ if (0 == selectedItems().count() && mGraphicItems.count() > 0 && Qt::TabFocusReason == event->reason())
selectItemAt(0); {
mSelectionSpan = 0; selectItemAt(0);
} mSelectionSpan = 0;
} }
}
void UBThumbnailWidget::resizeEvent(QResizeEvent *event)
{ void UBThumbnailWidget::resizeEvent(QResizeEvent *event)
Q_UNUSED(event); {
Q_UNUSED(event);
refreshScene();
refreshScene();
emit resized();
} emit resized();
}
void UBThumbnailWidget::sceneSelectionChanged()
{ void UBThumbnailWidget::sceneSelectionChanged()
emit selectionChanged(); {
} emit selectionChanged();
}
void UBThumbnailWidget::selectItemAt(int pIndex, bool extend)
{ void UBThumbnailWidget::selectItemAt(int pIndex, bool extend)
QGraphicsItem* itemToSelect = 0; {
QGraphicsItem* itemToSelect = 0;
if (pIndex >= 0 && pIndex < mGraphicItems.size())
itemToSelect = mGraphicItems.at(pIndex); if (pIndex >= 0 && pIndex < mGraphicItems.size())
itemToSelect = mGraphicItems.at(pIndex);
foreach (QGraphicsItem* item, items())
{ foreach (QGraphicsItem* item, items())
if (item == itemToSelect) {
{ if (item == itemToSelect)
mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(item); {
item->setSelected(true); mLastSelectedThumbnail = dynamic_cast<UBThumbnail*>(item);
ensureVisible(item); item->setSelected(true);
} ensureVisible(item);
else if (!extend) }
{ else if (!extend)
item->setSelected(false); {
} item->setSelected(false);
} }
} }
}
void UBThumbnailWidget::unselectItemAt(int pIndex)
{ void UBThumbnailWidget::unselectItemAt(int pIndex)
if (pIndex >= 0 && pIndex < mGraphicItems.size()) {
{ if (pIndex >= 0 && pIndex < mGraphicItems.size())
QGraphicsItem *itemToUnselect = mGraphicItems.at(pIndex); {
itemToUnselect->setSelected(false); QGraphicsItem *itemToUnselect = mGraphicItems.at(pIndex);
} itemToUnselect->setSelected(false);
} }
}
void UBThumbnailWidget::selectItems(int startIndex, int count)
{ void UBThumbnailWidget::selectItems(int startIndex, int count)
for (int i = 0; i < mGraphicItems.count(); i++) {
{ for (int i = 0; i < mGraphicItems.count(); i++)
mGraphicItems.at(i)->setSelected(i >= startIndex && i < startIndex + count); {
} mGraphicItems.at(i)->setSelected(i >= startIndex && i < startIndex + count);
} }
}
void UBThumbnailWidget::selectAll()
{ void UBThumbnailWidget::selectAll()
foreach (QGraphicsItem* item, mGraphicItems) {
{ foreach (QGraphicsItem* item, mGraphicItems)
item->setSelected(true); {
} item->setSelected(true);
} }
}
int UBThumbnailWidget::rowCount() const
{ int UBThumbnailWidget::rowCount() const
UBThumbnail *lastThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.last()); {
return lastThumbnail ? lastThumbnail->row() + 1 : 0; UBThumbnail *lastThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.last());
} return lastThumbnail ? lastThumbnail->row() + 1 : 0;
}
int UBThumbnailWidget::columnCount() const
{ int UBThumbnailWidget::columnCount() const
UBThumbnail *lastThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.last()); {
if (!lastThumbnail) return 0; UBThumbnail *lastThumbnail = dynamic_cast<UBThumbnail*>(mGraphicItems.last());
int lastRow = lastThumbnail->row(); if (!lastThumbnail) return 0;
int lastColumn = lastThumbnail->column(); int lastRow = lastThumbnail->row();
return lastRow > 0 ? (mGraphicItems.count() - lastColumn - 1) / lastRow : mGraphicItems.count(); int lastColumn = lastThumbnail->column();
} return lastRow > 0 ? (mGraphicItems.count() - lastColumn - 1) / lastRow : mGraphicItems.count();
}
void UBThumbnailWidget::mouseDoubleClickEvent(QMouseEvent * event)
{ void UBThumbnailWidget::mouseDoubleClickEvent(QMouseEvent * event)
QGraphicsItem* item = itemAt(event->pos()); {
QGraphicsItem* item = itemAt(event->pos());
if (item)
{ if (item)
int index = mGraphicItems.indexOf(item); {
emit mouseDoubleClick(item, index); int index = mGraphicItems.indexOf(item);
} emit mouseDoubleClick(item, index);
} }
}
bool UBThumbnailWidget::thumbnailLessThan(QGraphicsItem* item1, QGraphicsItem* item2)
{ bool UBThumbnailWidget::thumbnailLessThan(QGraphicsItem* item1, QGraphicsItem* item2)
UBThumbnail *thumbnail1 = dynamic_cast<UBThumbnail*>(item1); {
UBThumbnail *thumbnail2 = dynamic_cast<UBThumbnail*>(item2); UBThumbnail *thumbnail1 = dynamic_cast<UBThumbnail*>(item1);
if (thumbnail1 && thumbnail2) UBThumbnail *thumbnail2 = dynamic_cast<UBThumbnail*>(item2);
{ if (thumbnail1 && thumbnail2)
if (thumbnail1->row() != thumbnail2->row()) {
return thumbnail1->row() < thumbnail2->row(); if (thumbnail1->row() != thumbnail2->row())
else return thumbnail1->row() < thumbnail2->row();
return thumbnail1->column() < thumbnail2->column(); else
} return thumbnail1->column() < thumbnail2->column();
return false; }
} return false;
}
void UBThumbnailWidget::deleteLasso()
{ void UBThumbnailWidget::deleteLasso()
if (mLassoRectItem && scene()) {
{ if (mLassoRectItem && scene())
scene()->removeItem(mLassoRectItem); {
delete mLassoRectItem; scene()->removeItem(mLassoRectItem);
mLassoRectItem = 0; delete mLassoRectItem;
} mLassoRectItem = 0;
} }
}
UBThumbnail::UBThumbnail()
: mAddedToScene(false) UBThumbnail::UBThumbnail()
{ : mAddedToScene(false)
mSelectionItem = new QGraphicsRectItem(0, 0, 0, 0); {
mSelectionItem->setPen(QPen(UBSettings::treeViewBackgroundColor, 8)); mSelectionItem = new QGraphicsRectItem(0, 0, 0, 0);
// TODO UB 4.x fix nasty dependencies : 8 is a bit less than half of UBThumbnailWidget.mSpacing mSelectionItem->setPen(QPen(UBSettings::treeViewBackgroundColor, 8));
} // TODO UB 4.x fix nasty dependencies : 8 is a bit less than half of UBThumbnailWidget.mSpacing
}
UBThumbnail::~UBThumbnail()
{ UBThumbnail::~UBThumbnail()
if (mSelectionItem && !mAddedToScene) {
delete mSelectionItem; if (mSelectionItem && !mAddedToScene)
} delete mSelectionItem;
}
UBSceneThumbnailNavigPixmap::UBSceneThumbnailNavigPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex)
: UBSceneThumbnailPixmap(pix, proxy, pSceneIndex) UBSceneThumbnailNavigPixmap::UBSceneThumbnailNavigPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex)
, bButtonsVisible(false) : UBSceneThumbnailPixmap(pix, proxy, pSceneIndex)
, bCanDelete(false) , bButtonsVisible(false)
, bCanMoveUp(false) , bCanDelete(false)
, bCanMoveDown(false) , bCanMoveUp(false)
, bCanDuplicate(false) , bCanMoveDown(false)
{ , bCanDuplicate(false)
if(0 <= UBDocumentContainer::pageFromSceneIndex(pSceneIndex)){ {
setAcceptsHoverEvents(true); if(0 <= UBDocumentContainer::pageFromSceneIndex(pSceneIndex)){
setFlag(QGraphicsItem::ItemIsSelectable, true); setAcceptsHoverEvents(true);
} setFlag(QGraphicsItem::ItemIsSelectable, true);
} }
}
UBSceneThumbnailNavigPixmap::~UBSceneThumbnailNavigPixmap()
{ UBSceneThumbnailNavigPixmap::~UBSceneThumbnailNavigPixmap()
{
}
}
void UBSceneThumbnailNavigPixmap::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{ void UBSceneThumbnailNavigPixmap::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
event->accept(); {
updateButtonsState(); event->accept();
update(); updateButtonsState();
} update();
}
void UBSceneThumbnailNavigPixmap::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{ void UBSceneThumbnailNavigPixmap::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
event->accept(); {
bButtonsVisible = false; event->accept();
update(); bButtonsVisible = false;
} update();
}
void UBSceneThumbnailNavigPixmap::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ void UBSceneThumbnailNavigPixmap::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
Q_UNUSED(option); {
Q_UNUSED(widget); Q_UNUSED(option);
Q_UNUSED(widget);
UBSceneThumbnailPixmap::paint(painter, option, widget);
if(bButtonsVisible) UBSceneThumbnailPixmap::paint(painter, option, widget);
{ if(bButtonsVisible)
if(bCanDelete) {
painter->drawPixmap(0, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/close.svg")); if(bCanDelete)
else painter->drawPixmap(0, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/close.svg"));
painter->drawPixmap(0, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/closeDisabled.svg")); else
if(bCanDuplicate) painter->drawPixmap(0, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/closeDisabled.svg"));
painter->drawPixmap(BUTTONSIZE + BUTTONSPACING, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/duplicate.svg")); if(bCanDuplicate)
else painter->drawPixmap(BUTTONSIZE + BUTTONSPACING, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/duplicate.svg"));
painter->drawPixmap(BUTTONSIZE + BUTTONSPACING, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/duplicateDisabled.svg")); else
if(bCanMoveUp) painter->drawPixmap(BUTTONSIZE + BUTTONSPACING, 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/duplicateDisabled.svg"));
painter->drawPixmap(2*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/moveUp.svg")); if(bCanMoveUp)
else painter->drawPixmap(2*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/moveUp.svg"));
painter->drawPixmap(2*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/moveUpDisabled.svg")); else
if(bCanMoveDown) painter->drawPixmap(2*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/moveUpDisabled.svg"));
painter->drawPixmap(3*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/menu.svg")); if(bCanMoveDown)
else painter->drawPixmap(3*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/menu.svg"));
painter->drawPixmap(3*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/menuDisabled.svg")); else
} painter->drawPixmap(3*(BUTTONSIZE + BUTTONSPACING), 0, BUTTONSIZE, BUTTONSIZE, QPixmap(":images/menuDisabled.svg"));
} }
}
void UBSceneThumbnailNavigPixmap::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ void UBSceneThumbnailNavigPixmap::mousePressEvent(QGraphicsSceneMouseEvent *event)
QPointF p = event->pos(); {
QPointF p = event->pos();
// Here we check the position of the click and verify if it has to trig an action or not.
if(bCanDelete && p.x() >= 0 && p.x() <= BUTTONSIZE && p.y() >= 0 && p.y() <= BUTTONSIZE) // Here we check the position of the click and verify if it has to trig an action or not.
deletePage(); if(bCanDelete && p.x() >= 0 && p.x() <= BUTTONSIZE && p.y() >= 0 && p.y() <= BUTTONSIZE)
if(bCanDuplicate && p.x() >= BUTTONSIZE + BUTTONSPACING && p.x() <= 2*BUTTONSIZE + BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE) deletePage();
duplicatePage(); if(bCanDuplicate && p.x() >= BUTTONSIZE + BUTTONSPACING && p.x() <= 2*BUTTONSIZE + BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE)
if(bCanMoveUp && p.x() >= 2*(BUTTONSIZE + BUTTONSPACING) && p.x() <= 3*BUTTONSIZE + 2*BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE) duplicatePage();
moveUpPage(); if(bCanMoveUp && p.x() >= 2*(BUTTONSIZE + BUTTONSPACING) && p.x() <= 3*BUTTONSIZE + 2*BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE)
if(bCanMoveDown && p.x() >= 3*(BUTTONSIZE + BUTTONSPACING) && p.x() <= 4*BUTTONSIZE + 3*BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE) moveUpPage();
moveDownPage(); if(bCanMoveDown && p.x() >= 3*(BUTTONSIZE + BUTTONSPACING) && p.x() <= 4*BUTTONSIZE + 3*BUTTONSPACING && p.y() >= 0 && p.y() <= BUTTONSIZE)
moveDownPage();
event->accept();
} event->accept();
}
void UBSceneThumbnailNavigPixmap::updateButtonsState()
{ void UBSceneThumbnailNavigPixmap::updateButtonsState()
{
bCanDelete = false;
bCanMoveUp = false; bCanDelete = false;
bCanMoveDown = false; bCanMoveUp = false;
bCanDuplicate = false; bCanMoveDown = false;
bCanDuplicate = false;
if(proxy()){
int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneIndex()); if(proxy()){
UBDocumentController* documentController = UBApplication::documentController; int pageIndex = UBDocumentContainer::pageFromSceneIndex(sceneIndex());
bCanDelete = documentController->pageCanBeDeleted(pageIndex); UBDocumentController* documentController = UBApplication::documentController;
bCanMoveUp = documentController->pageCanBeMovedUp(pageIndex); bCanDelete = documentController->pageCanBeDeleted(pageIndex);
bCanMoveDown = documentController->pageCanBeMovedDown(pageIndex); bCanMoveUp = documentController->pageCanBeMovedUp(pageIndex);
bCanDuplicate = documentController->pageCanBeDuplicated(pageIndex); bCanMoveDown = documentController->pageCanBeMovedDown(pageIndex);
} bCanDuplicate = documentController->pageCanBeDuplicated(pageIndex);
}
if(bCanDelete || bCanMoveUp || bCanMoveDown || bCanDuplicate)
bButtonsVisible = true; if(bCanDelete || bCanMoveUp || bCanMoveDown || bCanDuplicate)
} bButtonsVisible = true;
}
void UBSceneThumbnailNavigPixmap::deletePage()
{ void UBSceneThumbnailNavigPixmap::deletePage()
if(UBApplication::mainWindow->yesNoQuestion(QObject::tr("Remove Page"), QObject::tr("Are you sure you want to remove 1 page from the selected document '%0'?").arg(UBApplication::documentController->selectedDocument()->metaData(UBSettings::documentName).toString()))){ {
UBApplication::boardController->deleteScene(sceneIndex()); if(UBApplication::mainWindow->yesNoQuestion(QObject::tr("Remove Page"), QObject::tr("Are you sure you want to remove 1 page from the selected document '%0'?").arg(UBApplication::documentController->selectedDocument()->metaData(UBSettings::documentName).toString()))){
} UBApplication::boardController->deleteScene(sceneIndex());
} }
}
void UBSceneThumbnailNavigPixmap::duplicatePage()
{ void UBSceneThumbnailNavigPixmap::duplicatePage()
UBApplication::boardController->duplicateScene(sceneIndex()); {
} UBApplication::boardController->duplicateScene(sceneIndex());
}
void UBSceneThumbnailNavigPixmap::moveUpPage()
{ void UBSceneThumbnailNavigPixmap::moveUpPage()
if (sceneIndex()!=0) {
UBApplication::boardController->moveSceneToIndex(sceneIndex(), sceneIndex() - 1); if (sceneIndex()!=0)
} UBApplication::boardController->moveSceneToIndex(sceneIndex(), sceneIndex() - 1);
}
void UBSceneThumbnailNavigPixmap::moveDownPage()
{ void UBSceneThumbnailNavigPixmap::moveDownPage()
if (sceneIndex() < UBApplication::boardController->selectedDocument()->pageCount()-1) {
UBApplication::boardController->moveSceneToIndex(sceneIndex(), sceneIndex() + 1); if (sceneIndex() < UBApplication::boardController->selectedDocument()->pageCount()-1)
} UBApplication::boardController->moveSceneToIndex(sceneIndex(), sceneIndex() + 1);
}
void UBImgTextThumbnailElement::Place(int row, int col, qreal width, qreal height)
{ void UBImgTextThumbnailElement::Place(int row, int col, qreal width, qreal height)
int labelSpacing = 0; {
if(this->caption) int labelSpacing = 0;
{ if(this->caption)
QFontMetrics fm(this->caption->font()); {
labelSpacing = UBSettings::thumbnailSpacing + fm.height(); QFontMetrics fm(this->caption->font());
} labelSpacing = UBSettings::thumbnailSpacing + fm.height();
if(this->thumbnail) }
{ if(this->thumbnail)
int w = this->thumbnail->boundingRect().width(); {
int h = this->thumbnail->boundingRect().height(); int w = this->thumbnail->boundingRect().width();
int h = this->thumbnail->boundingRect().height();
qreal scaleWidth = width / w;
qreal scaleHeight = height / h; qreal scaleWidth = width / w;
qreal scaleFactor = qMin(scaleWidth, scaleHeight); qreal scaleHeight = height / h;
UBThumbnail* pix = dynamic_cast<UBThumbnail*>(this->thumbnail); qreal scaleFactor = qMin(scaleWidth, scaleHeight);
UBThumbnail* pix = dynamic_cast<UBThumbnail*>(this->thumbnail);
QTransform transform;
transform.scale(scaleFactor, scaleFactor); QTransform transform;
transform.scale(scaleFactor, scaleFactor);
// Apply the scaling
this->thumbnail->setTransform(transform); // Apply the scaling
this->thumbnail->setFlag(QGraphicsItem::ItemIsSelectable, true); this->thumbnail->setTransform(transform);
this->thumbnail->setFlag(QGraphicsItem::ItemIsSelectable, true);
if(pix)
{ if(pix)
pix->setColumn(col); {
pix->setRow(row); pix->setColumn(col);
} pix->setRow(row);
}
QPointF pos(border + (width - w * scaleFactor) / 2 + col * (width + border),
border + row * (height + border + labelSpacing) + (height - h * scaleFactor) / 2); QPointF pos(border + (width - w * scaleFactor) / 2 + col * (width + border),
border + row * (height + border + labelSpacing) + (height - h * scaleFactor) / 2);
this->thumbnail->setPos(pos);
this->thumbnail->setPos(pos);
if(this->caption)
{ if(this->caption)
QFontMetrics fm(this->caption->font()); {
QString elidedText = fm.elidedText(this->caption->toPlainText(), Qt::ElideRight, width); QFontMetrics fm(this->caption->font());
QString elidedText = fm.elidedText(this->caption->toPlainText(), Qt::ElideRight, width);
this->caption->setPlainText(elidedText);
this->caption->setWidth(fm.width(elidedText) + 2 * this->caption->document()->documentMargin()); this->caption->setPlainText(elidedText);
pos.setY(pos.y() + (height + h * scaleFactor) / 2 + 5); // What is this 5 ?? this->caption->setWidth(fm.width(elidedText) + 2 * this->caption->document()->documentMargin());
qreal labelWidth = fm.width(elidedText); pos.setY(pos.y() + (height + h * scaleFactor) / 2 + 5); // What is this 5 ??
pos.setX(border + (width - labelWidth) / 2 + col * (width + border)); qreal labelWidth = fm.width(elidedText);
this->caption->setPos(pos); pos.setX(border + (width - labelWidth) / 2 + col * (width + border));
} this->caption->setPos(pos);
} }
} }
}
...@@ -19,417 +19,417 @@ ...@@ -19,417 +19,417 @@
* along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef UBTHUMBNAILWIDGET_H_ #ifndef UBTHUMBNAILWIDGET_H_
#define UBTHUMBNAILWIDGET_H_ #define UBTHUMBNAILWIDGET_H_
#include <QtGui> #include <QtGui>
#include <QtSvg> #include <QtSvg>
#include <QTime> #include <QTime>
#include <QGraphicsSceneHoverEvent> #include <QGraphicsSceneHoverEvent>
#include "frameworks/UBCoreGraphicsScene.h" #include "frameworks/UBCoreGraphicsScene.h"
#include "core/UBSettings.h" #include "core/UBSettings.h"
#include "domain/UBItem.h" #include "domain/UBItem.h"
#define STARTDRAGTIME 1000000 #define STARTDRAGTIME 1000000
#define BUTTONSIZE 48 #define BUTTONSIZE 48
#define BUTTONSPACING 5 #define BUTTONSPACING 5
class UBDocumentProxy; class UBDocumentProxy;
class UBThumbnailTextItem; class UBThumbnailTextItem;
class UBThumbnail; class UBThumbnail;
class UBThumbnailWidget : public QGraphicsView class UBThumbnailWidget : public QGraphicsView
{ {
Q_OBJECT; Q_OBJECT;
public: public:
UBThumbnailWidget(QWidget* parent); UBThumbnailWidget(QWidget* parent);
virtual ~UBThumbnailWidget(); virtual ~UBThumbnailWidget();
QList<QGraphicsItem*> selectedItems(); QList<QGraphicsItem*> selectedItems();
void selectItemAt(int pIndex, bool extend = false); void selectItemAt(int pIndex, bool extend = false);
void unselectItemAt(int pIndex); void unselectItemAt(int pIndex);
qreal thumbnailWidth() qreal thumbnailWidth()
{ {
return mThumbnailWidth; return mThumbnailWidth;
} }
void setBackgroundBrush(const QBrush& brush) void setBackgroundBrush(const QBrush& brush)
{ {
mThumbnailsScene.setBackgroundBrush(brush); mThumbnailsScene.setBackgroundBrush(brush);
} }
public slots: public slots:
void setThumbnailWidth(qreal pThumbnailWidth); void setThumbnailWidth(qreal pThumbnailWidth);
void setSpacing(qreal pSpacing); void setSpacing(qreal pSpacing);
virtual void setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems, const QList<QUrl>& pItemPaths, const QStringList pLabels = QStringList(), const QString& pMimeType = QString("")); virtual void setGraphicsItems(const QList<QGraphicsItem*>& pGraphicsItems, const QList<QUrl>& pItemPaths, const QStringList pLabels = QStringList(), const QString& pMimeType = QString(""));
void refreshScene(); void refreshScene();
void sceneSelectionChanged(); void sceneSelectionChanged();
signals: signals:
void resized(); void resized();
void selectionChanged(); void selectionChanged();
void mouseDoubleClick(QGraphicsItem* item, int index); void mouseDoubleClick(QGraphicsItem* item, int index);
void mouseClick(QGraphicsItem* item, int index); void mouseClick(QGraphicsItem* item, int index);
protected: protected:
virtual void mousePressEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void resizeEvent(QResizeEvent * event); virtual void resizeEvent(QResizeEvent * event);
void mouseDoubleClickEvent(QMouseEvent * event); void mouseDoubleClickEvent(QMouseEvent * event);
virtual void keyPressEvent(QKeyEvent *event); virtual void keyPressEvent(QKeyEvent *event);
virtual void focusInEvent(QFocusEvent *event); virtual void focusInEvent(QFocusEvent *event);
QList<QGraphicsItem*> mGraphicItems; QList<QGraphicsItem*> mGraphicItems;
QList<UBThumbnailTextItem*> mLabelsItems; QList<UBThumbnailTextItem*> mLabelsItems;
QPointF mMousePressScenePos; QPointF mMousePressScenePos;
QPoint mMousePressPos; QPoint mMousePressPos;
protected: protected:
qreal spacing() { return mSpacing; } qreal spacing() { return mSpacing; }
QList<QUrl> mItemsPaths; QList<QUrl> mItemsPaths;
QStringList mLabels; QStringList mLabels;
bool bSelectionInProgress; bool bSelectionInProgress;
bool bCanDrag; bool bCanDrag;
private: private:
void selectAll(); void selectAll();
void selectItems(int startIndex, int count); void selectItems(int startIndex, int count);
int rowCount() const; int rowCount() const;
int columnCount() const; int columnCount() const;
static bool thumbnailLessThan(QGraphicsItem* item1, QGraphicsItem* item2); static bool thumbnailLessThan(QGraphicsItem* item1, QGraphicsItem* item2);
void deleteLasso(); void deleteLasso();
UBCoreGraphicsScene mThumbnailsScene; UBCoreGraphicsScene mThumbnailsScene;
QString mMimeType; QString mMimeType;
QPointF prevMoveMousePos; QPointF prevMoveMousePos;
qreal mThumbnailWidth; qreal mThumbnailWidth;
qreal mThumbnailHeight; qreal mThumbnailHeight;
qreal mSpacing; qreal mSpacing;
UBThumbnail *mLastSelectedThumbnail; UBThumbnail *mLastSelectedThumbnail;
int mSelectionSpan; int mSelectionSpan;
QRectF mPrevLassoRect; QRectF mPrevLassoRect;
QGraphicsRectItem *mLassoRectItem; QGraphicsRectItem *mLassoRectItem;
QSet<QGraphicsItem*> mSelectedThumbnailItems; QSet<QGraphicsItem*> mSelectedThumbnailItems;
QSet<QGraphicsItem*> mPreviouslyIncrementalSelectedItemsX; QSet<QGraphicsItem*> mPreviouslyIncrementalSelectedItemsX;
QSet<QGraphicsItem*> mPreviouslyIncrementalSelectedItemsY; QSet<QGraphicsItem*> mPreviouslyIncrementalSelectedItemsY;
QTime mClickTime; QTime mClickTime;
}; };
class UBThumbnail class UBThumbnail
{ {
public: public:
UBThumbnail(); UBThumbnail();
virtual ~UBThumbnail(); virtual ~UBThumbnail();
QStyleOptionGraphicsItem muteStyleOption(const QStyleOptionGraphicsItem *option) QStyleOptionGraphicsItem muteStyleOption(const QStyleOptionGraphicsItem *option)
{ {
// Never draw the rubber band, we draw our custom selection with the DelegateFrame // Never draw the rubber band, we draw our custom selection with the DelegateFrame
QStyleOptionGraphicsItem styleOption = QStyleOptionGraphicsItem(*option); QStyleOptionGraphicsItem styleOption = QStyleOptionGraphicsItem(*option);
styleOption.state &= ~QStyle::State_Selected; styleOption.state &= ~QStyle::State_Selected;
return styleOption; return styleOption;
} }
virtual void itemChange(QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value) virtual void itemChange(QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{ {
Q_UNUSED(value); Q_UNUSED(value);
if ((change == QGraphicsItem::ItemSelectedHasChanged if ((change == QGraphicsItem::ItemSelectedHasChanged
|| change == QGraphicsItem::ItemTransformHasChanged || change == QGraphicsItem::ItemTransformHasChanged
|| change == QGraphicsItem::ItemPositionHasChanged) || change == QGraphicsItem::ItemPositionHasChanged)
&& item->scene()) && item->scene())
{ {
if (item->isSelected()) if (item->isSelected())
{ {
if (!mSelectionItem->scene()) if (!mSelectionItem->scene())
{ {
item->scene()->addItem(mSelectionItem); item->scene()->addItem(mSelectionItem);
mSelectionItem->setZValue(item->zValue() - 1); mSelectionItem->setZValue(item->zValue() - 1);
// UBGraphicsItem::assignZValue(mSelectionItem, item->zValue() - 1); // UBGraphicsItem::assignZValue(mSelectionItem, item->zValue() - 1);
mAddedToScene = true; mAddedToScene = true;
} }
mSelectionItem->setRect( mSelectionItem->setRect(
item->sceneBoundingRect().x() - 5, item->sceneBoundingRect().x() - 5,
item->sceneBoundingRect().y() - 5, item->sceneBoundingRect().y() - 5,
item->sceneBoundingRect().width() + 10, item->sceneBoundingRect().width() + 10,
item->sceneBoundingRect().height() + 10); item->sceneBoundingRect().height() + 10);
mSelectionItem->show(); mSelectionItem->show();
} }
else else
{ {
mSelectionItem->hide(); mSelectionItem->hide();
} }
} }
} }
int column() { return mColumn; } int column() { return mColumn; }
void setColumn(int column) { mColumn = column; } void setColumn(int column) { mColumn = column; }
int row() { return mRow; } int row() { return mRow; }
void setRow(int row) { mRow = row; } void setRow(int row) { mRow = row; }
protected: protected:
QGraphicsRectItem *mSelectionItem; QGraphicsRectItem *mSelectionItem;
private: private:
bool mAddedToScene; bool mAddedToScene;
int mColumn; int mColumn;
int mRow; int mRow;
}; };
class UBThumbnailSvg : public QGraphicsSvgItem, public UBThumbnail class UBThumbnailSvg : public QGraphicsSvgItem, public UBThumbnail
{ {
public: public:
UBThumbnailSvg(const QString& path) UBThumbnailSvg(const QString& path)
: QGraphicsSvgItem(path) : QGraphicsSvgItem(path)
{ {
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
} }
virtual ~UBThumbnailSvg() virtual ~UBThumbnailSvg()
{ {
// NOOP // NOOP
} }
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ {
QStyleOptionGraphicsItem styleOption = UBThumbnail::muteStyleOption(option); QStyleOptionGraphicsItem styleOption = UBThumbnail::muteStyleOption(option);
QGraphicsSvgItem::paint(painter, &styleOption, widget); QGraphicsSvgItem::paint(painter, &styleOption, widget);
} }
virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value)
{ {
UBThumbnail::itemChange(this, change, value); UBThumbnail::itemChange(this, change, value);
return QGraphicsSvgItem::itemChange(change, value); return QGraphicsSvgItem::itemChange(change, value);
} }
}; };
class UBThumbnailPixmap : public QGraphicsPixmapItem, public UBThumbnail class UBThumbnailPixmap : public QGraphicsPixmapItem, public UBThumbnail
{ {
public: public:
UBThumbnailPixmap(const QPixmap& pix) UBThumbnailPixmap(const QPixmap& pix)
: QGraphicsPixmapItem(pix) : QGraphicsPixmapItem(pix)
{ {
setTransformationMode(Qt::SmoothTransformation); // UB 4.3 may be expensive -- make configurable setTransformationMode(Qt::SmoothTransformation); // UB 4.3 may be expensive -- make configurable
setShapeMode(QGraphicsPixmapItem::BoundingRectShape); setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
} }
virtual ~UBThumbnailPixmap() virtual ~UBThumbnailPixmap()
{ {
// NOOP // NOOP
} }
virtual QPainterPath shape () const virtual QPainterPath shape () const
{ {
QPainterPath path; QPainterPath path;
path.addRect(boundingRect()); path.addRect(boundingRect());
return path; return path;
} }
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ {
QStyleOptionGraphicsItem styleOption = UBThumbnail::muteStyleOption(option); QStyleOptionGraphicsItem styleOption = UBThumbnail::muteStyleOption(option);
QGraphicsPixmapItem::paint(painter, &styleOption, widget); QGraphicsPixmapItem::paint(painter, &styleOption, widget);
} }
virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value)
{ {
UBThumbnail::itemChange(this, change, value); UBThumbnail::itemChange(this, change, value);
return QGraphicsPixmapItem::itemChange(change, value); return QGraphicsPixmapItem::itemChange(change, value);
} }
}; };
class UBSceneThumbnailPixmap : public UBThumbnailPixmap class UBSceneThumbnailPixmap : public UBThumbnailPixmap
{ {
public: public:
UBSceneThumbnailPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex) UBSceneThumbnailPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex)
: UBThumbnailPixmap(pix) : UBThumbnailPixmap(pix)
, mProxy(proxy) , mProxy(proxy)
, mSceneIndex(pSceneIndex) , mSceneIndex(pSceneIndex)
{ {
// NOOP // NOOP
} }
virtual ~UBSceneThumbnailPixmap() virtual ~UBSceneThumbnailPixmap()
{ {
// NOOP // NOOP
} }
UBDocumentProxy* proxy() UBDocumentProxy* proxy()
{ {
return mProxy; return mProxy;
} }
int sceneIndex() int sceneIndex()
{ {
return mSceneIndex; return mSceneIndex;
} }
void highlight() void highlight()
{ {
//NOOP //NOOP
} }
private: private:
UBDocumentProxy* mProxy; UBDocumentProxy* mProxy;
int mSceneIndex; int mSceneIndex;
}; };
class UBSceneThumbnailNavigPixmap : public UBSceneThumbnailPixmap class UBSceneThumbnailNavigPixmap : public UBSceneThumbnailPixmap
{ {
public: public:
UBSceneThumbnailNavigPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex); UBSceneThumbnailNavigPixmap(const QPixmap& pix, UBDocumentProxy* proxy, int pSceneIndex);
~UBSceneThumbnailNavigPixmap(); ~UBSceneThumbnailNavigPixmap();
protected: protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);
private: private:
void updateButtonsState(); void updateButtonsState();
void deletePage(); void deletePage();
void duplicatePage(); void duplicatePage();
void moveUpPage(); void moveUpPage();
void moveDownPage(); void moveDownPage();
bool bButtonsVisible; bool bButtonsVisible;
bool bCanDelete; bool bCanDelete;
bool bCanMoveUp; bool bCanMoveUp;
bool bCanMoveDown; bool bCanMoveDown;
bool bCanDuplicate; bool bCanDuplicate;
}; };
class UBThumbnailVideo : public UBThumbnailPixmap class UBThumbnailVideo : public UBThumbnailPixmap
{ {
public: public:
UBThumbnailVideo(const QUrl &path) UBThumbnailVideo(const QUrl &path)
: UBThumbnailPixmap(QPixmap(":/images/movie.svg")) : UBThumbnailPixmap(QPixmap(":/images/movie.svg"))
, mPath(path) , mPath(path)
{ {
// NOOP // NOOP
} }
virtual ~UBThumbnailVideo() virtual ~UBThumbnailVideo()
{ {
// NOOP // NOOP
} }
QUrl path() QUrl path()
{ {
return mPath; return mPath;
} }
private: private:
QUrl mPath; QUrl mPath;
}; };
class UBThumbnailTextItem : public QGraphicsTextItem class UBThumbnailTextItem : public QGraphicsTextItem
{ {
public: public:
UBThumbnailTextItem(const QString& text) UBThumbnailTextItem(const QString& text)
: QGraphicsTextItem(text) : QGraphicsTextItem(text)
, mUnelidedText(text) , mUnelidedText(text)
, mIsHighlighted(false) , mIsHighlighted(false)
{ {
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
} }
QRectF boundingRect() const { return QRectF(QPointF(0.0, 0.0), QSize(mWidth, QFontMetricsF(font()).height() + 5));} QRectF boundingRect() const { return QRectF(QPointF(0.0, 0.0), QSize(mWidth, QFontMetricsF(font()).height() + 5));}
void setWidth(qreal pWidth) void setWidth(qreal pWidth)
{ {
if (mWidth != pWidth) if (mWidth != pWidth)
{ {
prepareGeometryChange(); prepareGeometryChange();
mWidth = pWidth; mWidth = pWidth;
computeText(); computeText();
} }
}; };
qreal width() {return mWidth;} qreal width() {return mWidth;}
void highlight() void highlight()
{ {
if (!mIsHighlighted) if (!mIsHighlighted)
{ {
mIsHighlighted = true; mIsHighlighted = true;
computeText(); computeText();
} }
} }
void computeText() void computeText()
{ {
QFontMetricsF fm(font()); QFontMetricsF fm(font());
QString elidedText = fm.elidedText(mUnelidedText, Qt::ElideRight, mWidth); QString elidedText = fm.elidedText(mUnelidedText, Qt::ElideRight, mWidth);
if (mIsHighlighted) if (mIsHighlighted)
{ {
setHtml("<span style=\"color: #6682b5\">" + elidedText + "</span>"); setHtml("<span style=\"color: #6682b5\">" + elidedText + "</span>");
} }
else else
{ {
setPlainText(elidedText); setPlainText(elidedText);
} }
} }
private: private:
qreal mWidth; qreal mWidth;
QString mUnelidedText; QString mUnelidedText;
bool mIsHighlighted; bool mIsHighlighted;
}; };
class UBImgTextThumbnailElement class UBImgTextThumbnailElement
{ {
private: private:
UBSceneThumbnailNavigPixmap* thumbnail; UBSceneThumbnailNavigPixmap* thumbnail;
UBThumbnailTextItem* caption; UBThumbnailTextItem* caption;
int border; int border;
public: public:
UBImgTextThumbnailElement(UBSceneThumbnailNavigPixmap* thumb, UBThumbnailTextItem* text): border(0) UBImgTextThumbnailElement(UBSceneThumbnailNavigPixmap* thumb, UBThumbnailTextItem* text): border(0)
{ {
this->thumbnail = thumb; this->thumbnail = thumb;
this->caption = text; this->caption = text;
} }
UBSceneThumbnailNavigPixmap* getThumbnail() const { return this->thumbnail; } UBSceneThumbnailNavigPixmap* getThumbnail() const { return this->thumbnail; }
void setThumbnail(UBSceneThumbnailNavigPixmap* newGItem) { this->thumbnail = newGItem; } void setThumbnail(UBSceneThumbnailNavigPixmap* newGItem) { this->thumbnail = newGItem; }
UBThumbnailTextItem* getCaption() const { return this->caption; } UBThumbnailTextItem* getCaption() const { return this->caption; }
void setCaption(UBThumbnailTextItem* newcaption) { this->caption = newcaption; } void setCaption(UBThumbnailTextItem* newcaption) { this->caption = newcaption; }
void Place(int row, int col, qreal width, qreal height); void Place(int row, int col, qreal width, qreal height);
int getBorder() const { return this->border; } int getBorder() const { return this->border; }
void setBorder(int newBorder) { this->border = newBorder; } void setBorder(int newBorder) { this->border = newBorder; }
}; };
#endif /* UBTHUMBNAILWIDGET_H_ */ #endif /* UBTHUMBNAILWIDGET_H_ */
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
...@@ -34,39 +33,39 @@ ...@@ -34,39 +33,39 @@
CrashReporterSymbolSupplier::CrashReporterSymbolSupplier(QString pUniboardSymFiles) { CrashReporterSymbolSupplier::CrashReporterSymbolSupplier(QString pUniboardSymFiles) {
mUniboardSymFile.setFileName(pUniboardSymFiles); mUniboardSymFile.setFileName(pUniboardSymFiles);
} }
// Returns the path to the symbol file for the given module. // Returns the path to the symbol file for the given module.
google_breakpad::SymbolSupplier::SymbolResult CrashReporterSymbolSupplier::GetSymbolFile(const google_breakpad::CodeModule *module, google_breakpad::SymbolSupplier::SymbolResult CrashReporterSymbolSupplier::GetSymbolFile(const google_breakpad::CodeModule *module,
const google_breakpad::SystemInfo *system_info, const google_breakpad::SystemInfo *system_info,
string *symbol_file) string *symbol_file)
{ {
QString moduleName = QString::fromStdString(module->code_file()); QString moduleName = QString::fromStdString(module->code_file());
if (moduleName.contains("Uniboard")) if (moduleName.contains("Uniboard"))
{ {
*symbol_file = mUniboardSymFile.fileName().toStdString(); *symbol_file = mUniboardSymFile.fileName().toStdString();
return FOUND; return FOUND;
} }
return NOT_FOUND; return NOT_FOUND;
} }
// Returns the path to the symbol file for the given module. // Returns the path to the symbol file for the given module.
google_breakpad::SymbolSupplier::SymbolResult CrashReporterSymbolSupplier::GetSymbolFile(const google_breakpad::CodeModule *module, google_breakpad::SymbolSupplier::SymbolResult CrashReporterSymbolSupplier::GetSymbolFile(const google_breakpad::CodeModule *module,
const google_breakpad::SystemInfo *system_info, const google_breakpad::SystemInfo *system_info,
string *symbol_file, string *symbol_file,
string *symbol_data) string *symbol_data)
{ {
SymbolSupplier::SymbolResult s = GetSymbolFile(module, SymbolSupplier::SymbolResult s = GetSymbolFile(module,
system_info, system_info,
symbol_file); symbol_file);
if (s == FOUND) { if (s == FOUND) {
std::ifstream in(symbol_file->c_str()); std::ifstream in(symbol_file->c_str());
getline(in, *symbol_data, std::string::traits_type::to_char_type( getline(in, *symbol_data, std::string::traits_type::to_char_type(
std::string::traits_type::eof())); std::string::traits_type::eof()));
in.close(); in.close();
} }
return s; return s;
} }
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
...@@ -32,22 +31,22 @@ using std::string; ...@@ -32,22 +31,22 @@ using std::string;
class CrashReporterSymbolSupplier : public google_breakpad::SymbolSupplier class CrashReporterSymbolSupplier : public google_breakpad::SymbolSupplier
{ {
public: public:
CrashReporterSymbolSupplier(QString pUniboardSymFiles); CrashReporterSymbolSupplier(QString pUniboardSymFiles);
virtual ~CrashReporterSymbolSupplier() {} virtual ~CrashReporterSymbolSupplier() {}
// Returns the path to the symbol file for the given module. // Returns the path to the symbol file for the given module.
SymbolResult GetSymbolFile(const google_breakpad::CodeModule *module, SymbolResult GetSymbolFile(const google_breakpad::CodeModule *module,
const google_breakpad::SystemInfo *system_info, const google_breakpad::SystemInfo *system_info,
string *symbol_file); string *symbol_file);
// Returns the path to the symbol file for the given module. // Returns the path to the symbol file for the given module.
SymbolResult GetSymbolFile(const google_breakpad::CodeModule *module, SymbolResult GetSymbolFile(const google_breakpad::CodeModule *module,
const google_breakpad::SystemInfo *system_info, const google_breakpad::SystemInfo *system_info,
string *symbol_file, string *symbol_file,
string *symbol_data); string *symbol_data);
private: private:
QFile mUniboardSymFile; QFile mUniboardSymFile;
}; };
#endif /* CRASHREPORTERSYMBOLSUPPLIER_H_ */ #endif /* CRASHREPORTERSYMBOLSUPPLIER_H_ */
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
...@@ -31,14 +30,14 @@ CrashWindow::CrashWindow(QWidget* parent) : QDialog(parent) ...@@ -31,14 +30,14 @@ CrashWindow::CrashWindow(QWidget* parent) : QDialog(parent)
mCrashReporterUi->setupUi(this); mCrashReporterUi->setupUi(this);
mCrashReporterUi->crashReportResult->setFont(QFont("Monaco", 11)); mCrashReporterUi->crashReportResult->setFont(QFont("Monaco", 11));
connect(mCrashReporterUi->viewReportButton, SIGNAL(clicked(bool)), this, SLOT(showReport())); connect(mCrashReporterUi->viewReportButton, SIGNAL(clicked(bool)), this, SLOT(showReport()));
connect(mCrashReporterUi->dumpFileButton, SIGNAL(clicked(bool)), this, SLOT(chooseDumpFile())); connect(mCrashReporterUi->dumpFileButton, SIGNAL(clicked(bool)), this, SLOT(chooseDumpFile()));
connect(mCrashReporterUi->symFileButton, SIGNAL(clicked(bool)), this, SLOT(chooseSymboleFile())); connect(mCrashReporterUi->symFileButton, SIGNAL(clicked(bool)), this, SLOT(chooseSymboleFile()));
} }
CrashWindow::~CrashWindow() CrashWindow::~CrashWindow()
{ {
// NOOP // NOOP
} }
void CrashWindow::setDumpFilePath(const QString &fileName) void CrashWindow::setDumpFilePath(const QString &fileName)
...@@ -48,47 +47,47 @@ void CrashWindow::setDumpFilePath(const QString &fileName) ...@@ -48,47 +47,47 @@ void CrashWindow::setDumpFilePath(const QString &fileName)
void CrashWindow::chooseDumpFile() void CrashWindow::chooseDumpFile()
{ {
QSettings settings("Mnemis", "CrashReporter"); QSettings settings("Mnemis", "CrashReporter");
QString dumpFileName = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); QString dumpFileName = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
if (settings.contains("DumpFileName")) if (settings.contains("DumpFileName"))
{ {
dumpFileName = settings.value("DumpFileName").toString(); dumpFileName = settings.value("DumpFileName").toString();
} }
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
dumpFileName, dumpFileName,
tr("Dump file (*.dmp)")); tr("Dump file (*.dmp)"));
settings.setValue("DumpFileName", QVariant(fileName)); settings.setValue("DumpFileName", QVariant(fileName));
setDumpFilePath(fileName); setDumpFilePath(fileName);
} }
void CrashWindow::chooseSymboleFile() void CrashWindow::chooseSymboleFile()
{ {
QSettings settings("Mnemis", "CrashReporter"); QSettings settings("Mnemis", "CrashReporter");
QString symFileName = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); QString symFileName = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
if (settings.contains("SymFileName")) if (settings.contains("SymFileName"))
{ {
symFileName = settings.value("SymFileName").toString(); symFileName = settings.value("SymFileName").toString();
} }
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
symFileName, symFileName,
tr("Symbol file (*.sym)")); tr("Symbol file (*.sym)"));
settings.setValue("SymFileName", QVariant(fileName)); settings.setValue("SymFileName", QVariant(fileName));
mCrashReporterUi->symFilePath->setText(fileName); mCrashReporterUi->symFilePath->setText(fileName);
} }
//============================================================================= //=============================================================================
int CrashWindow::PrintRegister(const char *name, u_int32_t value, int sequence) { int CrashWindow::PrintRegister(const char *name, u_int32_t value, int sequence) {
if (sequence % 4 == 0) { if (sequence % 4 == 0) {
mReport.append("\n"); mReport.append("\n");
} }
// string should not exceed 200 byte!!! // string should not exceed 200 byte!!!
size_t BufSize = 2000; size_t BufSize = 2000;
char buf[BufSize]; char buf[BufSize];
snprintf(buf, BufSize, "%6s = 0x%08x ", name, value); snprintf(buf, BufSize, "%6s = 0x%08x ", name, value);
QString str = QString::fromAscii(buf); QString str = QString::fromAscii(buf);
mReport.append(str); mReport.append(str);
return ++sequence; return ++sequence;
} }
//============================================================================= //=============================================================================
...@@ -101,9 +100,9 @@ void CrashWindow::PrintStack(const CallStack* stack, const string &cpu) { ...@@ -101,9 +100,9 @@ void CrashWindow::PrintStack(const CallStack* stack, const string &cpu) {
const CodeModule *module = frame->module; const CodeModule *module = frame->module;
// string should not exceed 200 byte!!! // string should not exceed 200 byte!!!
size_t BufSize = 2000; size_t BufSize = 2000;
char buf[BufSize]; char buf[BufSize];
snprintf(buf, BufSize, "%2d ", frame_index); snprintf(buf, BufSize, "%2d ", frame_index);
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
if (module) { if (module) {
// Module name (20 chars max) // Module name (20 chars max)
...@@ -229,98 +228,98 @@ void CrashWindow::PrintModules(const CodeModules *modules) { ...@@ -229,98 +228,98 @@ void CrashWindow::PrintModules(const CodeModules *modules) {
u_int64_t base_address = module->base_address(); u_int64_t base_address = module->base_address();
// string should not exceed 200 byte!!! // string should not exceed 200 byte!!!
size_t BufSize = 2000; size_t BufSize = 2000;
char buf[BufSize]; char buf[BufSize];
snprintf(buf, BufSize, "0x%08llx - 0x%08llx %s %s%s %s\n", snprintf(buf, BufSize, "0x%08llx - 0x%08llx %s %s%s %s\n",
base_address, base_address + module->size() - 1, base_address, base_address + module->size() - 1,
PathnameStripper::File(module->code_file()).c_str(), PathnameStripper::File(module->code_file()).c_str(),
module->version().empty() ? "???" : module->version().c_str(), module->version().empty() ? "???" : module->version().c_str(),
main_module != NULL && base_address == main_address ? main_module != NULL && base_address == main_address ?
" (main)" : "", " (main)" : "",
module->code_file().c_str()); module->code_file().c_str());
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
} }
} }
void CrashWindow::showReport() void CrashWindow::showReport()
{ {
qDebug() << "compute report"; qDebug() << "compute report";
mReport.clear(); mReport.clear();
QString minidump_file = mCrashReporterUi->dumpFilePath->text(); QString minidump_file = mCrashReporterUi->dumpFilePath->text();
BasicSourceLineResolver resolver; BasicSourceLineResolver resolver;
scoped_ptr<CrashReporterSymbolSupplier> symbol_supplier( scoped_ptr<CrashReporterSymbolSupplier> symbol_supplier(
new CrashReporterSymbolSupplier(mCrashReporterUi->symFilePath->text())); new CrashReporterSymbolSupplier(mCrashReporterUi->symFilePath->text()));
scoped_ptr<MinidumpProcessor> scoped_ptr<MinidumpProcessor>
minidump_processor(new MinidumpProcessor(symbol_supplier.get(), &resolver)); minidump_processor(new MinidumpProcessor(symbol_supplier.get(), &resolver));
ProcessState process_state; ProcessState process_state;
if (minidump_processor->Process(minidump_file.toStdString(), &process_state) != if (minidump_processor->Process(minidump_file.toStdString(), &process_state) !=
MinidumpProcessor::PROCESS_OK) { MinidumpProcessor::PROCESS_OK) {
mReport += "MinidumpProcessor::Process failed\n"; mReport += "MinidumpProcessor::Process failed\n";
return; return;
} }
const SystemInfo *system_info = process_state.system_info(); const SystemInfo *system_info = process_state.system_info();
string cpu = system_info->cpu; string cpu = system_info->cpu;
// Convert the time to a string // Convert the time to a string
u_int32_t time_date_stamp = process_state.time_date_stamp(); u_int32_t time_date_stamp = process_state.time_date_stamp();
struct tm timestruct; struct tm timestruct;
gmtime_r(reinterpret_cast<time_t*>(&time_date_stamp), &timestruct); gmtime_r(reinterpret_cast<time_t*>(&time_date_stamp), &timestruct);
char timestr[20]; char timestr[20];
// string should not exceed 200 byte!!! // string should not exceed 200 byte!!!
size_t BufSize = 2000; size_t BufSize = 2000;
char buf[BufSize]; char buf[BufSize];
strftime(timestr, 20, "%Y-%m-%d %H:%M:%S", &timestruct); strftime(timestr, 20, "%Y-%m-%d %H:%M:%S", &timestruct);
snprintf(buf, BufSize, "Date: %s GMT\n", timestr); snprintf(buf, BufSize, "Date: %s GMT\n", timestr);
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
snprintf(buf, BufSize, "Operating system: %s (%s)\n", system_info->os.c_str(), snprintf(buf, BufSize, "Operating system: %s (%s)\n", system_info->os.c_str(),
system_info->os_version.c_str()); system_info->os_version.c_str());
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
snprintf(buf, BufSize, "Architecture: %s\n", cpu.c_str()); snprintf(buf, BufSize, "Architecture: %s\n", cpu.c_str());
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
if (process_state.crashed()) { if (process_state.crashed()) {
snprintf(buf, BufSize, "Crash reason: %s\n", process_state.crash_reason().c_str()); snprintf(buf, BufSize, "Crash reason: %s\n", process_state.crash_reason().c_str());
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
snprintf(buf, BufSize, "Crash address: 0x%llx\n", process_state.crash_address()); snprintf(buf, BufSize, "Crash address: 0x%llx\n", process_state.crash_address());
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
} else { } else {
mReport.append("No crash\n"); mReport.append("No crash\n");
} }
int requesting_thread = process_state.requesting_thread(); int requesting_thread = process_state.requesting_thread();
if (requesting_thread != -1) { if (requesting_thread != -1) {
mReport.append("\n"); mReport.append("\n");
snprintf(buf, BufSize, "Thread %d (%s)\n", snprintf(buf, BufSize, "Thread %d (%s)\n",
requesting_thread, requesting_thread,
process_state.crashed() ? "crashed" : process_state.crashed() ? "crashed" :
"requested dump, did not crash"); "requested dump, did not crash");
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
PrintStack(process_state.threads()->at(requesting_thread), cpu); PrintStack(process_state.threads()->at(requesting_thread), cpu);
} }
// Print all of the threads in the dump. // Print all of the threads in the dump.
int thread_count = process_state.threads()->size(); int thread_count = process_state.threads()->size();
for (int thread_index = 0; thread_index < thread_count; ++thread_index) { for (int thread_index = 0; thread_index < thread_count; ++thread_index) {
if (thread_index != requesting_thread) { if (thread_index != requesting_thread) {
// Don't print the crash thread again, it was already printed. // Don't print the crash thread again, it was already printed.
mReport.append("\n"); mReport.append("\n");
snprintf(buf, BufSize,"Thread %d\n", thread_index); snprintf(buf, BufSize,"Thread %d\n", thread_index);
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
PrintStack(process_state.threads()->at(thread_index), cpu); PrintStack(process_state.threads()->at(thread_index), cpu);
} }
} }
// Print the crashed registers // Print the crashed registers
if (requesting_thread != -1) { if (requesting_thread != -1) {
snprintf(buf, BufSize,"\nThread %d:", requesting_thread); snprintf(buf, BufSize,"\nThread %d:", requesting_thread);
mReport.append(QString::fromAscii(buf)); mReport.append(QString::fromAscii(buf));
PrintRegisters(process_state.threads()->at(requesting_thread), cpu); PrintRegisters(process_state.threads()->at(requesting_thread), cpu);
} }
// Print information about modules // Print information about modules
PrintModules(process_state.modules()); PrintModules(process_state.modules());
mCrashReporterUi->crashReportResult->setPlainText(mReport); mCrashReporterUi->crashReportResult->setPlainText(mReport);
} }
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
...@@ -59,23 +58,23 @@ namespace Ui ...@@ -59,23 +58,23 @@ namespace Ui
class CrashWindow : public QDialog class CrashWindow : public QDialog
{ {
Q_OBJECT; Q_OBJECT;
public: public:
CrashWindow(QWidget* parent = 0); CrashWindow(QWidget* parent = 0);
virtual ~CrashWindow(); virtual ~CrashWindow();
void setDumpFilePath(const QString &fileName); void setDumpFilePath(const QString &fileName);
private slots: private slots:
void showReport(); void showReport();
void chooseDumpFile(); void chooseDumpFile();
void chooseSymboleFile(); void chooseSymboleFile();
private: private:
int PrintRegister(const char *name, u_int32_t value, int sequence); int PrintRegister(const char *name, u_int32_t value, int sequence);
void PrintStack(const CallStack* stack, const string &cpu); void PrintStack(const CallStack* stack, const string &cpu);
void PrintRegisters(const CallStack *stack, const string &cpu); void PrintRegisters(const CallStack *stack, const string &cpu);
void PrintModules(const CodeModules *modules); void PrintModules(const CodeModules *modules);
Ui::UniboardCrashreporter* mCrashReporterUi; Ui::UniboardCrashreporter* mCrashReporterUi;
QString mReport; QString mReport;
}; };
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
......
...@@ -3,21 +3,20 @@ ...@@ -3,21 +3,20 @@
* *
* This file is part of Open-Sankoré. * This file is part of Open-Sankoré.
* *
* Open-Sankoré is free software; you can redistribute it and/or * Open-Sankoré is free software: you can redistribute it and/or modify
* modify it under the terms of the GNU Library General Public * it under the terms of the GNU General Public License as published by
* License as published by the Free Software Foundation, version 2, * the Free Software Foundation, version 3 of the License,
* with a specific linking exception for the OpenSSL project's * with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the * "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library). * same license as the "OpenSSL" library).
* *
* Open-Sankoré is distributed in the hope that it will be useful, * Open-Sankoré is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Library General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Library General Public * You should have received a copy of the GNU General Public License
* License along with Open-Sankoré; if not, see * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
* <http://www.gnu.org/licenses/>.
*/ */
...@@ -79,7 +78,7 @@ int main(int argc, char *argv[]) ...@@ -79,7 +78,7 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
//qDebug() << "Converting" << pdfFile << "(" << pageNumber << ") into" << imageFormat; //qDebug() << "Converting" << pdfFile << "(" << pageNumber << ") into" << imageFormat;
QImage image(width, height, QImage::Format_ARGB32); QImage image(width, height, QImage::Format_ARGB32);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment