some missing headers

preferencesAboutTextFull
Claudio Valerio 12 years ago
parent 3988bc837f
commit 8511c7ac0e
  1. 16
      plugins/cffadaptor/src/UBCFFAdaptor.cpp
  2. 15
      plugins/cffadaptor/src/UBCFFAdaptor.h
  3. 15
      plugins/cffadaptor/src/UBCFFAdaptor_global.h
  4. 15
      plugins/cffadaptor/src/UBCFFConstants.h
  5. 15
      plugins/cffadaptor/src/UBGlobals.h
  6. 3056
      src/adaptors/UBCFFSubsetAdaptor.cpp
  7. 264
      src/adaptors/UBCFFSubsetAdaptor.h
  8. 534
      src/adaptors/UBImportCFF.cpp
  9. 58
      src/adaptors/UBImportCFF.h
  10. 492
      src/adaptors/UBSvgSubsetAdaptor.h
  11. 332
      src/adaptors/UBThumbnailAdaptor.cpp
  12. 62
      src/adaptors/UBThumbnailAdaptor.h
  13. 1620
      src/adaptors/publishing/UBDocumentPublisher.cpp
  14. 242
      src/adaptors/publishing/UBDocumentPublisher.h
  15. 4992
      src/board/UBBoardController.cpp
  16. 584
      src/board/UBBoardController.h
  17. 1962
      src/board/UBBoardPaletteManager.cpp
  18. 340
      src/board/UBBoardPaletteManager.h
  19. 322
      src/board/UBBoardView.h
  20. 304
      src/core/UBApplication.h
  21. 1634
      src/core/UBApplicationController.cpp
  22. 588
      src/core/UBDocumentManager.cpp
  23. 24
      src/desktop/UBWindowCapture_mac.mm
  24. 250
      src/document/UBDocumentContainer.cpp
  25. 102
      src/document/UBDocumentContainer.h
  26. 3388
      src/document/UBDocumentController.cpp
  27. 266
      src/document/UBDocumentController.h
  28. 438
      src/document/UBDocumentProxy.cpp
  29. 172
      src/document/UBDocumentProxy.h
  30. 1968
      src/domain/UBGraphicsDelegateFrame.cpp
  31. 436
      src/domain/UBGraphicsItemUndoCommand.cpp
  32. 206
      src/domain/UBGraphicsVideoItemDelegate.h
  33. 436
      src/frameworks/UBGeometryUtils.cpp
  34. 72
      src/frameworks/UBGeometryUtils.h
  35. 6
      src/frameworks/UBPlatformUtils_mac.mm
  36. 536
      src/gui/UBDocumentNavigator.cpp
  37. 120
      src/gui/UBDocumentNavigator.h
  38. 604
      src/gui/UBDocumentThumbnailWidget.cpp
  39. 888
      src/gui/UBDocumentTreeWidget.cpp
  40. 1446
      src/gui/UBKeyboardPalette.cpp
  41. 562
      src/gui/UBKeyboardPalette.h
  42. 152
      src/gui/UBKeyboardPalette_win.cpp
  43. 766
      src/gui/UBMagnifer.cpp
  44. 168
      src/gui/UBMagnifer.h
  45. 264
      src/gui/UBNavigatorPalette.cpp
  46. 104
      src/gui/UBNavigatorPalette.h
  47. 318
      src/gui/UBPageNavigationWidget.cpp
  48. 118
      src/gui/UBPageNavigationWidget.h
  49. 1839
      src/gui/UBThumbnailWidget.cpp
  50. 828
      src/gui/UBThumbnailWidget.h
  51. 59
      tools/CrashReportViewer/CrashReporterSymbolSupplier.cpp
  52. 39
      tools/CrashReportViewer/CrashReporterSymbolSupplier.h
  53. 261
      tools/CrashReportViewer/CrashWindow.cpp
  54. 35
      tools/CrashReportViewer/CrashWindow.h
  55. 15
      tools/CrashReportViewer/main.cpp
  56. 15
      tools/pdf2image/core/UBPlatformUtils.cpp
  57. 15
      tools/pdf2image/core/UBPlatformUtils.h
  58. 17
      tools/pdf2image/pdf2image.cpp

@ -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 @@
* *
* 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 @@
* *
* 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 @@
* *
* 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 @@
* *
* 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/>.
*/ */

File diff suppressed because it is too large Load Diff

@ -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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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

File diff suppressed because it is too large Load Diff

@ -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

File diff suppressed because it is too large Load Diff

@ -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_ */

File diff suppressed because it is too large Load Diff

@ -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 @@
* 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 @@
* 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_ */

File diff suppressed because it is too large Load Diff

@ -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 @@
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()
{ {
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 @@
* 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 @@
* 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_ */

File diff suppressed because it is too large Load Diff

@ -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 @@
* 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 @@
* 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_ */

File diff suppressed because it is too large Load Diff

@ -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 @@
* 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 @@
* 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 @@
* 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()
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()
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 @@
* 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 @@
* 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 @@
* 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 @@
* 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);
} }

File diff suppressed because it is too large Load Diff

@ -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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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 @@
* 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

File diff suppressed because it is too large Load Diff

@ -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 @@
* *
* 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 @@
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 @@
* *
* 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;
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 @@
* *
* 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)
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)
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) {
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) {
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 @@
* *
* 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
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 @@
* *
* 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 @@
* *
* 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 @@
* *
* 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 @@
* *
* 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[])
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);

Loading…
Cancel
Save