UBGraphicsScene.cpp 95.3 KB
Newer Older
1
/*
2
 * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
Craig Watson's avatar
Craig Watson committed
3
 *
Claudio Valerio's avatar
Claudio Valerio committed
4
 * Copyright (C) 2013 Open Education Foundation
5
 *
Claudio Valerio's avatar
Claudio Valerio committed
6 7
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
8
 *
Claudio Valerio's avatar
Claudio Valerio committed
9 10 11
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
14 15 16 17
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
Claudio Valerio's avatar
Claudio Valerio committed
18
 * OpenBoard is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Claudio Valerio's avatar
Claudio Valerio committed
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Claudio Valerio's avatar
Claudio Valerio committed
21
 * GNU General Public License for more details.
22
 *
Claudio Valerio's avatar
Claudio Valerio committed
23
 * You should have received a copy of the GNU General Public License
Claudio Valerio's avatar
Claudio Valerio committed
24
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
25 26
 */

27

Claudio Valerio's avatar
Claudio Valerio committed
28

Claudio Valerio's avatar
Claudio Valerio committed
29

30 31 32 33 34 35
#include "UBGraphicsScene.h"

#include <QtGui>
#include <QtWebKit>
#include <QtSvg>
#include <QGraphicsView>
Craig Watson's avatar
Craig Watson committed
36
#include <QGraphicsVideoItem>
37 38 39 40 41 42 43 44 45

#include "frameworks/UBGeometryUtils.h"
#include "frameworks/UBPlatformUtils.h"

#include "core/UBApplication.h"
#include "core/UBSettings.h"
#include "core/UBApplicationController.h"
#include "core/UBDisplayManager.h"
#include "core/UBPersistenceManager.h"
46
#include "core/UBTextTools.h"
47 48 49

#include "gui/UBMagnifer.h"
#include "gui/UBMainWindow.h"
Yimgo's avatar
Yimgo committed
50
#include "gui/UBToolWidget.h"
51
#include "gui/UBResources.h"
52 53 54 55 56 57 58 59 60 61 62 63

#include "tools/UBGraphicsRuler.h"
#include "tools/UBGraphicsProtractor.h"
#include "tools/UBGraphicsCompass.h"
#include "tools/UBGraphicsTriangle.h"
#include "tools/UBGraphicsCurtainItem.h"
#include "tools/UBGraphicsCache.h"

#include "document/UBDocumentProxy.h"

#include "board/UBBoardController.h"
#include "board/UBDrawingController.h"
64
#include "board/UBBoardView.h"
65 66

#include "UBGraphicsItemUndoCommand.h"
Ilia Ryabokon's avatar
Ilia Ryabokon committed
67
#include "UBGraphicsItemGroupUndoCommand.h"
68 69 70 71 72 73 74 75 76 77
#include "UBGraphicsTextItemUndoCommand.h"
#include "UBGraphicsProxyWidget.h"
#include "UBGraphicsPixmapItem.h"
#include "UBGraphicsSvgItem.h"
#include "UBGraphicsPolygonItem.h"
#include "UBGraphicsMediaItem.h"
#include "UBGraphicsWidgetItem.h"
#include "UBGraphicsPDFItem.h"
#include "UBGraphicsTextItem.h"
#include "UBGraphicsStrokesGroup.h"
Ilia Ryabokon's avatar
Ilia Ryabokon committed
78
#include "UBSelectionFrame.h"
79
#include "UBGraphicsItemZLevelUndoCommand.h"
80 81 82 83 84 85 86

#include "domain/UBGraphicsGroupContainerItem.h"

#include "UBGraphicsStroke.h"

#include "core/memcheck.h"

Claudio Valerio's avatar
Claudio Valerio committed
87 88 89

#define DEFAULT_Z_VALUE 0.0

90 91 92 93 94 95 96
qreal UBZLayerController::errorNumber = -20000001.0;

UBZLayerController::UBZLayerController(QGraphicsScene *scene) :
    mScene(scene)

{
    scopeMap.insert(itemLayerType::NoLayer,        ItemLayerTypeData( errorNumber, errorNumber));
97
    scopeMap.insert(itemLayerType::BackgroundItem, ItemLayerTypeData(-1000000.0, -1000000.0 ));
Claudio Valerio's avatar
Claudio Valerio committed
98 99 100
    // DEFAULT_Z_VALUE isn't used because it allows to easily identify new objects
    scopeMap.insert(itemLayerType::ObjectItem,     ItemLayerTypeData(-1000000.0,  DEFAULT_Z_VALUE - 1.0));
    scopeMap.insert(itemLayerType::DrawingItem,    ItemLayerTypeData( DEFAULT_Z_VALUE + 1.0, 1000000.0 ));
101 102 103 104 105 106
    scopeMap.insert(itemLayerType::ToolItem,       ItemLayerTypeData( 1000000.0,  1000100.0 ));
    scopeMap.insert(itemLayerType::CppTool,        ItemLayerTypeData( 1000100.0,  1000200.0 ));
    scopeMap.insert(itemLayerType::Curtain,        ItemLayerTypeData( 1000200.0,  1001000.0 ));
    scopeMap.insert(itemLayerType::Eraiser,        ItemLayerTypeData( 1001000.0,  1001100.0 ));
    scopeMap.insert(itemLayerType::Pointer,        ItemLayerTypeData( 1001100.0,  1001200.0 ));
    scopeMap.insert(itemLayerType::Cache,          ItemLayerTypeData( 1001300.0,  1001400.0 ));
107

108
    scopeMap.insert(itemLayerType::SelectedItem,   ItemLayerTypeData( 1001000.0,  1001000.0 ));
109
    scopeMap.insert(itemLayerType::SelectionFrame, ItemLayerTypeData( 1010000.0,  1010000.0 ));
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}

qreal UBZLayerController::generateZLevel(itemLayerType::Enum key)
{

    if (!scopeMap.contains(key)) {
        qDebug() << "Number is out of layer scope";
        return errorNumber;
    }

    qreal result = scopeMap.value(key).curValue;
    qreal top = scopeMap.value(key).topLimit;
    qreal incrementalStep = scopeMap.value(key).incStep;

    result += incrementalStep;
    if (result >= top) {
        // If not only one variable presents in the scope, notify that values for scope are over
        if (scopeMap.value(key).topLimit != scopeMap.value(key).bottomLimit) {
            qDebug() << "new values are over for the scope" << key;
        }
        result = top - incrementalStep;
    }

    scopeMap[key].curValue = result;

    return result;
}
qreal UBZLayerController::generateZLevel(QGraphicsItem *item)
{
    qreal result = errorNumber;
    itemLayerType::Enum type = static_cast<itemLayerType::Enum>(item->data(UBGraphicsItemData::itemLayerType).toInt());

    if (validLayerType(type)) {
        result =  generateZLevel(type);
    }

    return result;
}

qreal UBZLayerController::changeZLevelTo(QGraphicsItem *item, moveDestination dest)
{
    itemLayerType::Enum curItemLayerType = typeForData(item);
    if (curItemLayerType == itemLayerType::NoLayer) {
        qDebug() << "item's layer is out of the scope. Can't implement z-layer changing operation";
        return errorNum();
    }

    //select only items wiht the same z-level as item's one and push it to sortedItems QMultiMap
    QMultiMap<qreal, QGraphicsItem*> sortedItems;
    if (mScene->items().count()) {
        foreach (QGraphicsItem *tmpItem, mScene->items()) {
            if (typeForData(tmpItem) == curItemLayerType) {
                sortedItems.insert(tmpItem->data(UBGraphicsItemData::ItemOwnZValue).toReal(), tmpItem);
            }
        }
    }

    //If only one item itself - do nothing, return it's z-value
    if (sortedItems.count() == 1 && sortedItems.values().first() == item) {
        qDebug() << "only one item exists in layer. Have nothing to change";
        return item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
    }

    QMapIterator<qreal, QGraphicsItem*>iCurElement(sortedItems);

    if (dest == up) {
176
        qDebug() << "item data zvalue= " << item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        if (iCurElement.findNext(item)) {
            if (iCurElement.hasNext()) {
                qreal nextZ = iCurElement.peekNext().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal();
                UBGraphicsItem::assignZValue(iCurElement.peekNext().value(), item->data(UBGraphicsItemData::ItemOwnZValue).toReal());
                UBGraphicsItem::assignZValue(item, nextZ);

                iCurElement.next();

                while (iCurElement.hasNext() && iCurElement.peekNext().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal() == nextZ) {
                    UBGraphicsItem::assignZValue(iCurElement.next().value(), nextZ);
                }
            }
        }

    } else if (dest == top) {
        if (iCurElement.findNext(item)) {
            if (iCurElement.hasNext()) {
                UBGraphicsItem::assignZValue(item, generateZLevel(item));
            }
        }

    } else if (dest == down) {
        iCurElement.toBack();
        if (iCurElement.findPrevious(item)) {
            if (iCurElement.hasPrevious()) {
                qreal nextZ = iCurElement.peekPrevious().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal();
                UBGraphicsItem::assignZValue(iCurElement.peekPrevious().value(), item->data(UBGraphicsItemData::ItemOwnZValue).toReal());
                UBGraphicsItem::assignZValue(item, nextZ);

                while (iCurElement.hasNext() && iCurElement.peekNext().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal() == nextZ) {
                        UBGraphicsItem::assignZValue(iCurElement.next().value(), nextZ);
                }
            }
        }

    } else if (dest == bottom) {
        iCurElement.toBack();
        if (iCurElement.findPrevious(item)) {
            if (iCurElement.hasPrevious()) {
                qreal oldz = item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
                iCurElement.toFront();
                qreal nextZ = iCurElement.next().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal();

                ItemLayerTypeData curItemLayerTypeData = scopeMap.value(curItemLayerType);
221

222 223
                //if we have some free space between lowest graphics item and layer's bottom bound,
                //insert element close to first element in layer
224
                if (nextZ > curItemLayerTypeData.bottomLimit + curItemLayerTypeData.incStep) {
225 226 227 228
                    qreal result = nextZ - curItemLayerTypeData.incStep;
                    UBGraphicsItem::assignZValue(item, result);
                } else {
                    UBGraphicsItem::assignZValue(item, nextZ);
229

230 231 232 233 234 235 236 237 238 239
                    bool doubleGap = false; //to detect if we can finish rundown since we can insert item to the free space

                    while (iCurElement.peekNext().value() != item) {
                        qreal curZ = iCurElement.value()->data(UBGraphicsItemData::ItemOwnZValue).toReal();
                        qreal curNextZ = iCurElement.peekNext().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal();
                        if (curNextZ - curZ >= 2 * curItemLayerTypeData.incStep) {
                            UBGraphicsItem::assignZValue(iCurElement.value(), curZ + curItemLayerTypeData.incStep);
                            doubleGap = true;
                            break;
                        } else {
240 241
                            UBGraphicsItem::assignZValue(iCurElement.value(), curNextZ);
                            iCurElement.next();
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                        }
                    }
                    if (!doubleGap) {

                        UBGraphicsItem::assignZValue(iCurElement.value(), oldz);

                        while (iCurElement.hasNext() && (iCurElement.peekNext().value()->data(UBGraphicsItemData::ItemOwnZValue).toReal() == oldz)) {
                            UBGraphicsItem::assignZValue(iCurElement.next().value(), oldz);
                        }
                    }
                }
            }
        }
    }


    //clear selection of the item and then select it again to activate selectionChangeProcessing()
    item->scene()->clearSelection();
    item->setSelected(true);

Ilia Ryabokon's avatar
Ilia Ryabokon committed
262 263
    foreach (QGraphicsItem *iitem, sortedItems.values()) {
        if (iitem)
264
            iitem != item ? qDebug() <<  "current value" << iitem->zValue() : qDebug() << "marked value" << QString::number(iitem->zValue(), 'f');
Ilia Ryabokon's avatar
Ilia Ryabokon committed
265 266
    }

267
    //Return new z value assigned to item
268 269 270 271
    
    // experimental
    item->setZValue(item->data(UBGraphicsItemData::ItemOwnZValue).toReal());

272 273 274 275 276 277 278 279 280 281 282 283 284 285
    return item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
}

itemLayerType::Enum UBZLayerController::typeForData(QGraphicsItem *item) const
{
    itemLayerType::Enum result = static_cast<itemLayerType::Enum>(item->data(UBGraphicsItemData::itemLayerType).toInt());

    if (!scopeMap.contains(result)) {
        result = itemLayerType::NoLayer;
    }

    return result;
}

286 287 288 289 290
void UBZLayerController::setLayerType(QGraphicsItem *pItem, itemLayerType::Enum pNewType)
{
   pItem->setData(UBGraphicsItemData::itemLayerType, QVariant(pNewType));
}

291 292 293 294 295 296 297 298 299 300 301 302
void UBZLayerController::shiftStoredZValue(QGraphicsItem *item, qreal zValue)
{
    itemLayerType::Enum type = typeForData(item);

    if (validLayerType(type)) {
        ItemLayerTypeData typeData = scopeMap.value(type);
        if (typeData.curValue < zValue) {
            scopeMap[type].curValue = zValue;
        }
    }
}

303 304 305 306 307
/**
 * @brief Returns true if the zLevel is not used by any item on the scene, or false if so.
 */
bool UBZLayerController::zLevelAvailable(qreal z)
{
Craig Watson's avatar
Craig Watson committed
308
    foreach(QGraphicsItem* it, dynamic_cast<UBGraphicsScene*>(mScene)->getFastAccessItems()) {
309 310 311 312 313 314 315
        if (it->zValue() == z)
            return false;
    }

    return true;
}

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
316
UBGraphicsScene::UBGraphicsScene(UBDocumentProxy* parent, bool enableUndoRedoStack)
317 318 319
    : UBCoreGraphicsScene(parent)
    , mEraser(0)
    , mPointer(0)
320
    , mMarkerCircle(0)
321
    , mPenCircle(0)
322 323
    , mDocument(parent)
    , mDarkBackground(false)
Craig Watson's avatar
Craig Watson committed
324
    , mPageBackground(UBPageBackground::plain)
325
    , mIsDesktopMode(false)
326
    , mZoomFactor(1)
327 328
    , mBackgroundObject(0)
    , mPreviousWidth(0)
329
    , mDistanceFromLastStrokePoint(0)
330 331 332 333 334
    , mInputDeviceIsPressed(false)
    , mArcPolygonItem(0)
    , mRenderingContext(Screen)
    , mCurrentStroke(0)
    , mItemCount(0)
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
335
    , mUndoRedoStackEnabled(enableUndoRedoStack)
336 337 338 339
    , magniferControlViewWidget(0)
    , magniferDisplayViewWidget(0)
    , mZLayerController(new UBZLayerController(this))
    , mpLastPolygon(NULL)
340
    , mCurrentPolygon(0)
341
    , mTempPolygon(NULL)
Ilia Ryabokon's avatar
Ilia Ryabokon committed
342
    , mSelectionFrame(0)
343 344
{
    UBCoreGraphicsScene::setObjectName("BoardScene");
345
    setItemIndexMethod(BspTreeIndex);
346

347
    setUuid(QUuid::createUuid());
348 349 350
    setDocument(parent);
    createEraiser();
    createPointer();
351
    createMarkerCircle();
352
    createPenCircle();
353 354 355 356 357 358 359 360

    if (UBApplication::applicationController)
    {
        setViewState(SceneViewState(1,
            UBApplication::applicationController->initialHScroll(),
            UBApplication::applicationController->initialVScroll()));
    }

361 362
    mBackgroundGridSize = UBSettings::settings()->crossSize;

363
//    Just for debug. Do not delete please
Claudio Valerio's avatar
Claudio Valerio committed
364
//    connect(this, SIGNAL(selectionChanged()), this, SLOT(selectionChangedProcessing()));
365
    connect(UBApplication::undoStack.data(), SIGNAL(indexChanged(int)), this, SLOT(updateSelectionFrameWrapper(int)));
366 367 368 369
}

UBGraphicsScene::~UBGraphicsScene()
{
370 371 372 373
    if (mCurrentStroke && mCurrentStroke->polygons().empty()){
        delete mCurrentStroke;
        mCurrentStroke = NULL;
    }
374 375 376 377 378 379 380 381

    if (mZLayerController)
        delete mZLayerController;
}

void UBGraphicsScene::selectionChangedProcessing()
{
    if (selectedItems().count()){
382 383 384
        UBApplication::showMessage("ZValue is " + QString::number(selectedItems().first()->zValue(), 'f') + "own z value is "
                                   + QString::number(selectedItems().first()->data(UBGraphicsItemData::ItemOwnZValue).toReal(), 'f'));

385 386 387
    }
}

388 389 390 391 392 393 394 395 396 397
void UBGraphicsScene::setLastCenter(QPointF center)
{
    mViewState.setLastSceneCenter(center);
}

QPointF UBGraphicsScene::lastCenter()
{
    return mViewState.lastSceneCenter();
}

398 399 400 401
bool UBGraphicsScene::inputDevicePress(const QPointF& scenePos, const qreal& pressure)
{
    bool accepted = false;

402
    if (mInputDeviceIsPressed) {
403 404 405
        qWarning() << "scene received input device pressed, without input device release, muting event as input device move";
        accepted = inputDeviceMove(scenePos, pressure);
    }
406
    else {
407 408 409 410
        mInputDeviceIsPressed = true;

        UBStylusTool::Enum currentTool = (UBStylusTool::Enum)UBDrawingController::drawingController()->stylusTool();

411
        if (UBDrawingController::drawingController()->isDrawingTool()) {
412 413 414 415 416 417 418 419 420 421 422
            // -----------------------------------------------------------------
            // We fall here if we are using the Pen, the Marker or the Line tool
            // -----------------------------------------------------------------
            qreal width = 0;

            // delete current stroke, if not assigned to any polygon
            if (mCurrentStroke && mCurrentStroke->polygons().empty()){
                delete mCurrentStroke;
                mCurrentStroke = NULL;
            }

423 424 425 426
            // hide the marker preview circle
            if (currentTool == UBStylusTool::Marker)
                hideMarkerCircle();

427 428 429 430
            // hide the pen preview circle
            if (currentTool == UBStylusTool::Pen)
                hidePenCircle();

431 432 433
            // ---------------------------------------------------------------
            // Create a new Stroke. A Stroke is a collection of QGraphicsLines
            // ---------------------------------------------------------------
434
            mCurrentStroke = new UBGraphicsStroke(this);
435 436 437 438

            if (currentTool != UBStylusTool::Line){
                // Handle the pressure
                width = UBDrawingController::drawingController()->currentToolWidth() * pressure;
439 440
            }
            else{
441 442 443 444 445 446 447 448 449 450 451 452
                // Ignore pressure for the line tool
                width = UBDrawingController::drawingController()->currentToolWidth();
            }

            width /= UBApplication::boardController->systemScaleFactor();
            width /= UBApplication::boardController->currentZoom();

            mAddedItems.clear();
            mRemovedItems.clear();

            if (UBDrawingController::drawingController()->mActiveRuler)
                UBDrawingController::drawingController()->mActiveRuler->StartLine(scenePos, width);
453
            else {
454 455
                moveTo(scenePos);
                drawLineTo(scenePos, width, UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Line);
456

457
                mCurrentStroke->addPoint(scenePos, width);
458 459 460
            }
            accepted = true;
        }
461
        else if (currentTool == UBStylusTool::Eraser) {
462 463 464 465 466 467 468 469 470
            mAddedItems.clear();
            mRemovedItems.clear();
            moveTo(scenePos);

            qreal eraserWidth = UBSettings::settings()->currentEraserWidth();
            eraserWidth /= UBApplication::boardController->systemScaleFactor();
            eraserWidth /= UBApplication::boardController->currentZoom();

            eraseLineTo(scenePos, eraserWidth);
471
            drawEraser(scenePos, mInputDeviceIsPressed);
472 473 474

            accepted = true;
        }
475
        else if (currentTool == UBStylusTool::Pointer) {
476 477 478 479 480
            drawPointer(scenePos, true);
            accepted = true;
        }
    }

481
    if (mCurrentStroke && mCurrentStroke->polygons().empty()){
482
        delete mCurrentStroke;
483 484 485
        mCurrentStroke = NULL;
    }

486 487 488 489 490 491 492 493 494 495 496 497 498 499
    return accepted;
}

bool UBGraphicsScene::inputDeviceMove(const QPointF& scenePos, const qreal& pressure)
{
    bool accepted = false;

    UBDrawingController *dc = UBDrawingController::drawingController();
    UBStylusTool::Enum currentTool = (UBStylusTool::Enum)dc->stylusTool();

    QPointF position = QPointF(scenePos);

    if (currentTool == UBStylusTool::Eraser)
    {
500
        drawEraser(position, mInputDeviceIsPressed);
501 502 503
        accepted = true;
    }

504 505 506 507 508 509 510 511 512
    else if (currentTool == UBStylusTool::Marker) {
        if (mInputDeviceIsPressed)
            hideMarkerCircle();
        else {
            drawMarkerCircle(position);
            accepted = true;
        }
    }

513 514 515 516 517 518 519 520 521
    else if (currentTool == UBStylusTool::Pen) {
        if (mInputDeviceIsPressed)
            hidePenCircle();
        else {
            drawPenCircle(position);
            accepted = true;
        }
    }

522 523 524 525 526 527 528 529
    if (mInputDeviceIsPressed)
    {
        if (dc->isDrawingTool())
        {
            qreal width = 0;

            if (currentTool != UBStylusTool::Line){
                // Handle the pressure
530
                width = dc->currentToolWidth() * qMax(pressure, 0.2);
531 532 533 534 535 536 537 538 539 540
            }else{
                // Ignore pressure for line tool
                width = dc->currentToolWidth();
            }

            width /= UBApplication::boardController->systemScaleFactor();
            width /= UBApplication::boardController->currentZoom();

            if (currentTool == UBStylusTool::Line || dc->mActiveRuler)
            {
541
                if (UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Marker)
542 543 544 545
                if(NULL != mpLastPolygon && NULL != mCurrentStroke && mAddedItems.size() > 0){
                    UBCoreGraphicsScene::removeItemFromDeletion(mpLastPolygon);
                    mAddedItems.remove(mpLastPolygon);
                    mCurrentStroke->remove(mpLastPolygon);
546 547 548 549
                    if (mCurrentStroke->polygons().empty()){
                        delete mCurrentStroke;
                        mCurrentStroke = NULL;
                    }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
                    removeItem(mpLastPolygon);
                    mPreviousPolygonItems.removeAll(mpLastPolygon);
                }

                // ------------------------------------------------------------------------
                // Here we wanna make sure that the Line will 'grip' at i*45, i*90 degrees
                // ------------------------------------------------------------------------

                QLineF radius(mPreviousPoint, position);
                qreal angle = radius.angle();
                angle = qRound(angle / 45) * 45;
                qreal radiusLength = radius.length();
                QPointF newPosition(
                    mPreviousPoint.x() + radiusLength * cos((angle * PI) / 180),
                    mPreviousPoint.y() - radiusLength * sin((angle * PI) / 180));
                QLineF chord(position, newPosition);
Claudio Valerio's avatar
Claudio Valerio committed
566
                if (chord.length() < qMin((int)16, (int)(radiusLength / 20)))
567 568 569
                    position = newPosition;
            }

570
            if (!mCurrentStroke)
571
                mCurrentStroke = new UBGraphicsStroke(this);
572

573 574
            if(dc->mActiveRuler){
                dc->mActiveRuler->DrawLine(position, width);
575
            }
Craig Watson's avatar
Craig Watson committed
576 577 578 579 580

            else if (currentTool == UBStylusTool::Line) {
                drawLineTo(position, width, true);
            }

581 582
            else {
                bool interpolate = false;
583

584 585 586
                if ((currentTool == UBStylusTool::Pen && UBSettings::settings()->boardInterpolatePenStrokes->get().toBool())
                    || (currentTool == UBStylusTool::Marker && UBSettings::settings()->boardInterpolateMarkerStrokes->get().toBool()))
                {
587
                    interpolate = true;
588 589
                }

590 591 592 593 594 595 596 597 598 599 600

                // Don't draw segments smaller than a certain length. This can help with performance
                // (less polygons to draw) but mostly with making the curve look smooth.

                qreal antiScaleRatio = 1./(UBApplication::boardController->systemScaleFactor() * UBApplication::boardController->currentZoom());
                qreal MIN_DISTANCE = 10*antiScaleRatio; // arbitrary. Move to settings if relevant.
                qreal distance = QLineF(mPreviousPoint, scenePos).length();

                mDistanceFromLastStrokePoint += distance;

                if (mDistanceFromLastStrokePoint > MIN_DISTANCE) {
601
                    QList<QPair<QPointF, qreal> > newPoints = mCurrentStroke->addPoint(scenePos, width, interpolate);
602 603 604 605
                    if (newPoints.length() > 1)
                        drawCurve(newPoints);

                    mDistanceFromLastStrokePoint = 0;
606
                }
607

608
                if (interpolate) {
609 610 611 612 613 614 615 616 617 618
                    // Bezier curves aren't drawn all the way to the scenePos (they stop halfway between the previous and
                    // current scenePos), so we add a line from the last drawn position in the stroke and the
                    // scenePos, to make the drawing feel more responsive. This line is then deleted if a new segment is
                    // added to the stroke. (Or it is added to the stroke when we stop drawing)

                    if (mTempPolygon) {
                        removeItem(mTempPolygon);
                        mTempPolygon = NULL;
                    }

619
                    QPointF lastDrawnPoint = mCurrentStroke->points().last().first;
620 621 622 623

                    mTempPolygon = lineToPolygonItem(QLineF(lastDrawnPoint, scenePos), mPreviousWidth, width);
                    addItem(mTempPolygon);
                }
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
            }
        }
        else if (currentTool == UBStylusTool::Eraser)
        {
            qreal eraserWidth = UBSettings::settings()->currentEraserWidth();
            eraserWidth /= UBApplication::boardController->systemScaleFactor();
            eraserWidth /= UBApplication::boardController->currentZoom();

            eraseLineTo(position, eraserWidth);
        }
        else if (currentTool == UBStylusTool::Pointer)
        {
            drawPointer(position);
        }

        accepted = true;
    }

    return accepted;
}

bool UBGraphicsScene::inputDeviceRelease()
{
    bool accepted = false;

    if (mPointer)
    {
        mPointer->hide();
        accepted = true;
    }

655 656 657 658 659 660
    UBStylusTool::Enum currentTool = (UBStylusTool::Enum)UBDrawingController::drawingController()->stylusTool();

    if (currentTool == UBStylusTool::Eraser)
        redrawEraser(false);


661 662 663 664 665
    UBDrawingController *dc = UBDrawingController::drawingController();

    if (dc->isDrawingTool() || mDrawWithCompass)
    {
        if(mArcPolygonItem){
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
666

667
            UBGraphicsStrokesGroup* pStrokes = new UBGraphicsStrokesGroup();
668

669 670 671 672 673 674 675 676 677 678 679 680
            // Add the arc
            mAddedItems.remove(mArcPolygonItem);
            removeItem(mArcPolygonItem);
            UBCoreGraphicsScene::removeItemFromDeletion(mArcPolygonItem);
            mArcPolygonItem->setStrokesGroup(pStrokes);
            pStrokes->addToGroup(mArcPolygonItem);

            // Add the center cross
            foreach(QGraphicsItem* item, mAddedItems){
                mAddedItems.remove(item);
                removeItem(item);
                UBCoreGraphicsScene::removeItemFromDeletion(item);
681 682 683
                UBGraphicsPolygonItem* pi = qgraphicsitem_cast<UBGraphicsPolygonItem*>(item);
                if (pi)
                    pi->setStrokesGroup(pStrokes);
684 685
                pStrokes->addToGroup(item);
            }
686

687 688 689
            mAddedItems.clear();
            mAddedItems << pStrokes;
            addItem(pStrokes);
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
690

691
            mDrawWithCompass = false;
Claudio Valerio's avatar
Claudio Valerio committed
692 693
        }
        else if (mCurrentStroke){
694 695 696 697 698 699 700
            if (mTempPolygon) {
                UBGraphicsPolygonItem * poly = dynamic_cast<UBGraphicsPolygonItem*>(mTempPolygon->deepCopy());
                removeItem(mTempPolygon);
                mTempPolygon = NULL;
                addPolygonItemToCurrentStroke(poly);
            }

701 702 703 704 705 706 707 708
            // replace the stroke by a simplified version of it
            if ((currentTool == UBStylusTool::Pen && UBSettings::settings()->boardSimplifyPenStrokes->get().toBool())
                || (currentTool == UBStylusTool::Marker && UBSettings::settings()->boardSimplifyMarkerStrokes->get().toBool()))
            {
                simplifyCurrentStroke();
            }


709 710 711 712 713 714 715 716 717 718
            UBGraphicsStrokesGroup* pStrokes = new UBGraphicsStrokesGroup();

            // Remove the strokes that were just drawn here and replace them by a stroke item
            foreach(UBGraphicsPolygonItem* poly, mCurrentStroke->polygons()){
                mPreviousPolygonItems.removeAll(poly);
                removeItem(poly);
                UBCoreGraphicsScene::removeItemFromDeletion(poly);
                poly->setStrokesGroup(pStrokes);
                pStrokes->addToGroup(poly);
            }
719

720
            // TODO LATER : Generate well pressure-interpolated polygons and create the line group with them
721

722 723 724
            mAddedItems.clear();
            mAddedItems << pStrokes;
            addItem(pStrokes);
725 726 727 728 729

            if (mCurrentStroke->polygons().empty()){
                delete mCurrentStroke;
                mCurrentStroke = 0;
            }
730
            mCurrentPolygon = 0;
731 732 733 734 735 736
        }
    }

    if (mRemovedItems.size() > 0 || mAddedItems.size() > 0)
    {

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
737
        if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
            UBGraphicsItemUndoCommand* udcmd = new UBGraphicsItemUndoCommand(this, mRemovedItems, mAddedItems); //deleted by the undoStack

            if(UBApplication::undoStack)
                UBApplication::undoStack->push(udcmd);
        }

        mRemovedItems.clear();
        mAddedItems.clear();
        accepted = true;
    }

    mInputDeviceIsPressed = false;

    setDocumentUpdated();

753 754 755 756
    if (mCurrentStroke && mCurrentStroke->polygons().empty()){
        delete mCurrentStroke;
    }

757
    mCurrentStroke = NULL;
758 759 760
    return accepted;
}

761
void UBGraphicsScene::drawEraser(const QPointF &pPoint, bool pressed)
762
{
763 764 765 766
    if (mEraser) {
        qreal eraserWidth = UBSettings::settings()->currentEraserWidth();
        eraserWidth /= UBApplication::boardController->systemScaleFactor();
        eraserWidth /= UBApplication::boardController->currentZoom();
767

768
        qreal eraserRadius = eraserWidth / 2;
769 770 771

    // TODO UB 4.x optimize - no need to do that every time we move it
        mEraser->setRect(QRectF(pPoint.x() - eraserRadius, pPoint.y() - eraserRadius, eraserWidth, eraserWidth));
772 773 774
        redrawEraser(pressed);
    }
}
775

776 777 778
void UBGraphicsScene::redrawEraser(bool pressed)
{
    if (mEraser) {
779 780
        QPen pen = mEraser->pen();

781
        if(pressed)
782
            pen.setStyle(Qt::SolidLine);
783
        else
784
            pen.setStyle(Qt::DotLine);
785

786
        mEraser->setPen(pen);
787
        mEraser->show();
788 789 790
    }
}

791 792 793 794 795 796
void UBGraphicsScene::hideEraser()
{
    if (mEraser)
        mEraser->hide();
}

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
void UBGraphicsScene::drawPointer(const QPointF &pPoint, bool isFirstDraw)
{
    qreal pointerDiameter = UBSettings::pointerDiameter / UBApplication::boardController->currentZoom();
    qreal pointerRadius = pointerDiameter / 2;

    // TODO UB 4.x optimize - no need to do that every time we move it
    if (mPointer) {
        mPointer->setRect(QRectF(pPoint.x() - pointerRadius,
                                 pPoint.y() - pointerRadius,
                                 pointerDiameter,
                                 pointerDiameter));
        if(isFirstDraw) {
            mPointer->show();
        }
    }
}

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
void UBGraphicsScene::drawMarkerCircle(const QPointF &pPoint)
{
    if (mMarkerCircle) {
        qreal markerDiameter = UBSettings::settings()->currentMarkerWidth();
        markerDiameter /= UBApplication::boardController->systemScaleFactor();
        markerDiameter /= UBApplication::boardController->currentZoom();
        qreal markerRadius = markerDiameter/2;

        mMarkerCircle->setRect(QRectF(pPoint.x() - markerRadius, pPoint.y() - markerRadius,
                                      markerDiameter, markerDiameter));
        mMarkerCircle->show();
    }

}

829 830 831 832 833 834 835 836 837 838 839 840
void UBGraphicsScene::drawPenCircle(const QPointF &pPoint)
{
    if (mPenCircle && UBSettings::settings()->showPenPreviewCircle->get().toBool() &&
        UBSettings::settings()->currentPenWidth() >= UBSettings::settings()->penPreviewFromSize->get().toInt()) {
        qreal penDiameter = UBSettings::settings()->currentPenWidth();
        penDiameter /= UBApplication::boardController->systemScaleFactor();
        penDiameter /= UBApplication::boardController->currentZoom();
        qreal penRadius = penDiameter/2;

        mPenCircle->setRect(QRectF(pPoint.x() - penRadius, pPoint.y() - penRadius,
                                      penDiameter, penDiameter));

841 842 843 844
        if (controlView())
            if (controlView()->viewport())
                controlView()->viewport()->setCursor(QCursor (Qt::BlankCursor));

845 846 847 848
        mPenCircle->show();
    }
    else
    {
849 850 851
        if (controlView())
            if (controlView()->viewport())
                controlView()->viewport()->setCursor(UBResources::resources()->penCursor);
852 853 854 855
    }

}

856 857 858 859 860 861 862
void UBGraphicsScene::hideMarkerCircle()
{
    if (mMarkerCircle) {
        mMarkerCircle->hide();
    }
}

863 864 865 866 867 868
void UBGraphicsScene::hidePenCircle()
{
    if (mPenCircle)
        mPenCircle->hide();
}

869 870 871 872 873 874 875 876 877 878 879
// call this function when user release mouse button in Magnifier mode
void UBGraphicsScene::DisposeMagnifierQWidgets()
{
    if(magniferControlViewWidget)
    {
        magniferControlViewWidget->hide();
        magniferControlViewWidget->setParent(0);
        delete magniferControlViewWidget;
        magniferControlViewWidget = NULL;
    }

880 881 882 883 884 885 886
    if(magniferDisplayViewWidget)
    {
        magniferDisplayViewWidget->hide();
        magniferDisplayViewWidget->setParent(0);
        delete magniferDisplayViewWidget;
        magniferDisplayViewWidget = NULL;
    }
Claudio Valerio's avatar
Claudio Valerio committed
887
    // some time have crash here on access to app (when call from destructor when close OpenBoard app)
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    // so i just add try/catch section here
    try
    {
        UBApplication::app()->restoreOverrideCursor();
    }
    catch (...)
    {
    }

}

void UBGraphicsScene::moveTo(const QPointF &pPoint)
{
    mPreviousPoint = pPoint;
    mPreviousWidth = -1.0;
    mPreviousPolygonItems.clear();
    mArcPolygonItem = 0;
    mDrawWithCompass = false;
}
void UBGraphicsScene::drawLineTo(const QPointF &pEndPoint, const qreal &pWidth, bool bLineStyle)
908 909 910 911 912 913
{
    drawLineTo(pEndPoint, pWidth, pWidth, bLineStyle);

}

void UBGraphicsScene::drawLineTo(const QPointF &pEndPoint, const qreal &startWidth, const qreal &endWidth, bool bLineStyle)
914 915
{
    if (mPreviousWidth == -1.0)
916
        mPreviousWidth = startWidth;
917

918 919 920
    qreal initialWidth = startWidth;
    if (initialWidth == endWidth)
        initialWidth = mPreviousWidth;
921

922 923
    if (bLineStyle) {
        QSetIterator<QGraphicsItem*> itItems(mAddedItems);
924

925 926 927 928 929 930
        while (itItems.hasNext()) {
            QGraphicsItem* item = itItems.next();
            removeItem(item);
        }
        mAddedItems.clear();
    }
931

932
    UBGraphicsPolygonItem *polygonItem = lineToPolygonItem(QLineF(mPreviousPoint, pEndPoint), initialWidth, endWidth);
933 934 935 936 937 938 939
    addPolygonItemToCurrentStroke(polygonItem);

    if (!bLineStyle) {
        mPreviousPoint = pEndPoint;
        mPreviousWidth = endWidth;
    }
}
940

941 942 943 944 945 946 947 948 949
void UBGraphicsScene::drawCurve(const QList<QPair<QPointF, qreal> >& points)
{
    UBGraphicsPolygonItem* polygonItem = curveToPolygonItem(points);
    addPolygonItemToCurrentStroke(polygonItem);

    mPreviousPoint = points.last().first;
    mPreviousWidth = points.last().second;
}

950 951 952 953 954 955 956 957 958 959 960
void UBGraphicsScene::drawCurve(const QList<QPointF>& points, qreal startWidth, qreal endWidth)
{
    UBGraphicsPolygonItem* polygonItem = curveToPolygonItem(points, startWidth, endWidth);
    addPolygonItemToCurrentStroke(polygonItem);

    mPreviousWidth = endWidth;
    mPreviousPoint = points.last();
}

void UBGraphicsScene::addPolygonItemToCurrentStroke(UBGraphicsPolygonItem* polygonItem)
{
961 962 963 964 965 966 967 968 969 970 971 972
    if (!polygonItem->brush().isOpaque())
    {
        // -------------------------------------------------------------------------------------
        // Here we substract the polygons that are overlapping in order to keep the transparency
        // -------------------------------------------------------------------------------------
        for (int i = 0; i < mPreviousPolygonItems.size(); i++)
        {
            UBGraphicsPolygonItem* previous = mPreviousPolygonItems.value(i);
            polygonItem->subtract(previous);
        }
    }

973 974 975 976 977
    mpLastPolygon = polygonItem;
    mAddedItems.insert(polygonItem);

    // Here we add the item to the scene
    addItem(polygonItem);
978
    if (!mCurrentStroke)
979
        mCurrentStroke = new UBGraphicsStroke(this);
980

981
    polygonItem->setStroke(mCurrentStroke);
982

983
    mPreviousPolygonItems.append(polygonItem);
984

985 986 987 988 989
}

void UBGraphicsScene::eraseLineTo(const QPointF &pEndPoint, const qreal &pWidth)
{
    const QLineF line(mPreviousPoint, pEndPoint);
990
    mPreviousPoint = pEndPoint;
991 992 993 994

    const QPolygonF eraserPolygon = UBGeometryUtils::lineToPolygon(line, pWidth);
    const QRectF eraserBoundingRect = eraserPolygon.boundingRect();

995 996
    QPainterPath eraserPath;
    eraserPath.addPolygon(eraserPolygon);
997 998 999 1000

    // Get all the items that are intersecting with the eraser path
    QList<QGraphicsItem*> collidItems = items(eraserBoundingRect, Qt::IntersectsItemBoundingRect);

1001
    QList<UBGraphicsPolygonItem*> intersectedItems;
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1002

1003 1004
    typedef QList<QPolygonF> POLYGONSLIST;
    QList<POLYGONSLIST> intersectedPolygons;
1005

shibakaneki's avatar
shibakaneki committed
1006
    #pragma omp parallel for
1007 1008 1009 1010 1011
    for(int i=0; i<collidItems.size(); i++)
    {
        UBGraphicsPolygonItem *pi = qgraphicsitem_cast<UBGraphicsPolygonItem*>(collidItems[i]);
        if(pi == NULL)
            continue;
1012

1013 1014
        QPainterPath itemPainterPath;
        itemPainterPath.addPolygon(pi->sceneTransform().map(pi->polygon()));
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1015

1016
        if (eraserPath.contains(itemPainterPath))
1017
        {
1018
            #pragma omp critical
1019
            {
1020
                // Compete remove item
1021
                intersectedItems << pi;
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1022
                intersectedPolygons << QList<QPolygonF>();
1023 1024
            }
        }
1025
        else if (eraserPath.intersects(itemPainterPath))
1026
        {
1027
            itemPainterPath.setFillRule(Qt::WindingFill);
1028
            QPainterPath newPath = itemPainterPath.subtracted(eraserPath);
1029 1030 1031
            #pragma omp critical
            {
               intersectedItems << pi;
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1032
               intersectedPolygons << newPath.simplified().toFillPolygons(pi->sceneTransform().inverted());
1033 1034
            }
        }
1035
    }
1036

1037 1038
    for(int i=0; i<intersectedItems.size(); i++)
    {
1039 1040
        // item who intersects with eraser
        UBGraphicsPolygonItem *intersectedPolygonItem = intersectedItems[i];
1041

1042 1043
        if (!intersectedPolygons[i].empty())
        {
1044 1045
            // intersected polygons generated as QList<QPolygon> QPainterPath::toFillPolygons(),
            // so each intersectedPolygonItem has one or couple of QPolygons who should be removed from it.
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1046 1047
            for(int j = 0; j < intersectedPolygons[i].size(); j++)
            {
1048 1049 1050
                // create small polygon from couple of polygons to replace particular erased polygon
                UBGraphicsPolygonItem* polygonItem = new UBGraphicsPolygonItem(intersectedPolygons[i][j], intersectedPolygonItem->parentItem());

1051
                intersectedPolygonItem->copyItemParameters(polygonItem);
1052
                polygonItem->setNominalLine(false);
1053 1054 1055 1056
                polygonItem->setStroke(intersectedPolygonItem->stroke());
                polygonItem->setStrokesGroup(intersectedPolygonItem->strokesGroup());
                intersectedPolygonItem->strokesGroup()->addToGroup(polygonItem);
                mAddedItems << polygonItem;
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1057
            }
1058
        }
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
        //remove full polygon item for replace it by couple of polygons which creates the same stroke without a part intersects with eraser
         mRemovedItems << intersectedPolygonItem;

        QTransform t;
        bool bApplyTransform = false;
        if (intersectedPolygonItem->strokesGroup())
        {
            if (intersectedPolygonItem->strokesGroup()->parentItem())
            {
                bApplyTransform = true;
                t = intersectedPolygonItem->sceneTransform();
            }
            intersectedPolygonItem->strokesGroup()->removeFromGroup(intersectedPolygonItem);
        }
1074
        removeItem(intersectedPolygonItem);
1075 1076
        if (bApplyTransform)
            intersectedPolygonItem->setTransform(t);
1077 1078
    }

1079 1080
    if (!intersectedItems.empty())
        setModified(true);
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
}

void UBGraphicsScene::drawArcTo(const QPointF& pCenterPoint, qreal pSpanAngle)
{
    mDrawWithCompass = true;
    if (mArcPolygonItem)
    {
        mAddedItems.remove(mArcPolygonItem);
        removeItem(mArcPolygonItem);
        mArcPolygonItem = 0;
    }
    qreal penWidth = UBSettings::settings()->currentPenWidth();
    penWidth /= UBApplication::boardController->systemScaleFactor();
    penWidth /= UBApplication::boardController->currentZoom();

    mArcPolygonItem = arcToPolygonItem(QLineF(pCenterPoint, mPreviousPoint), pSpanAngle, penWidth);
1097
    mArcPolygonItem->setFillRule(Qt::WindingFill);
1098 1099 1100 1101 1102 1103 1104
    mArcPolygonItem->setStroke(mCurrentStroke);
    mAddedItems.insert(mArcPolygonItem);
    addItem(mArcPolygonItem);

    setDocumentUpdated();
}

Craig Watson's avatar
Craig Watson committed
1105
void UBGraphicsScene::setBackground(bool pIsDark, UBPageBackground pBackground)
1106 1107 1108 1109 1110 1111 1112
{
    bool needRepaint = false;

    if (mDarkBackground != pIsDark)
    {
        mDarkBackground = pIsDark;

1113 1114
        updateEraserColor();
        updateMarkerCircleColor();
1115
        updatePenCircleColor();
1116 1117 1118 1119 1120 1121
        recolorAllItems();

        needRepaint = true;
        setModified(true);
    }

Craig Watson's avatar
Craig Watson committed
1122
    if (mPageBackground != pBackground)
1123
    {
Craig Watson's avatar
Craig Watson committed
1124
        mPageBackground = pBackground;
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        needRepaint = true;
        setModified(true);
    }

    if (needRepaint)
    {
        foreach(QGraphicsView* view, views())
        {
            view->resetCachedContent();
        }
    }
}

void UBGraphicsScene::setBackgroundZoomFactor(qreal zoom)
{
    mZoomFactor = zoom;
}

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

void UBGraphicsScene::setBackgroundGridSize(int pSize)
{
    if (pSize > 0) {
        mBackgroundGridSize = pSize;
        setModified(true);

        foreach(QGraphicsView* view, views())
            view->resetCachedContent();
    }
}

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
void UBGraphicsScene::setDrawingMode(bool bModeDesktop)
{
    mIsDesktopMode = bModeDesktop;
}

void UBGraphicsScene::recolorAllItems()
{
    QMap<QGraphicsView*, QGraphicsView::ViewportUpdateMode> previousUpdateModes;
    foreach(QGraphicsView* view, views())
    {
        previousUpdateModes.insert(view, view->viewportUpdateMode());
        view->setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    }

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    bool currentIslight = isLightBackground();
    foreach (QGraphicsItem *item, items()) {
        if (item->type() == UBGraphicsStrokesGroup::Type) {
            UBGraphicsStrokesGroup *curGroup = static_cast<UBGraphicsStrokesGroup*>(item);
            QColor compareColor =  curGroup->color(currentIslight ? UBGraphicsStrokesGroup::colorOnDarkBackground
                                                                  : UBGraphicsStrokesGroup::colorOnLightBackground);

            if (curGroup->color() == compareColor) {
                QColor newColor = curGroup->color(!currentIslight ? UBGraphicsStrokesGroup::colorOnDarkBackground
                                                                  : UBGraphicsStrokesGroup::colorOnLightBackground);
                curGroup->setColor(newColor);
1180 1181
            }
        }
1182 1183 1184 1185 1186 1187

        if (item->type() == UBGraphicsTextItem::Type)
        {
            UBGraphicsTextItem *textItem = static_cast<UBGraphicsTextItem*>(item);
            textItem->recolor();
        }
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    }

    foreach(QGraphicsView* view, views())
    {
        view->setViewportUpdateMode(previousUpdateModes.value(view));
    }
}

UBGraphicsPolygonItem* UBGraphicsScene::lineToPolygonItem(const QLineF &pLine, const qreal &pWidth)
{
    UBGraphicsPolygonItem *polygonItem = new UBGraphicsPolygonItem(pLine, pWidth);

    initPolygonItem(polygonItem);

    return polygonItem;
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

UBGraphicsPolygonItem* UBGraphicsScene::lineToPolygonItem(const QLineF &pLine, const qreal &pStartWidth, const qreal &pEndWidth)
{
    UBGraphicsPolygonItem *polygonItem = new UBGraphicsPolygonItem(pLine, pStartWidth, pEndWidth);

    initPolygonItem(polygonItem);

    return polygonItem;
}

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
void UBGraphicsScene::initPolygonItem(UBGraphicsPolygonItem* polygonItem)
{
    QColor colorOnDarkBG;
    QColor colorOnLightBG;

    if (UBDrawingController::drawingController()->stylusTool() == UBStylusTool::Marker)
    {
        colorOnDarkBG = UBApplication::boardController->markerColorOnDarkBackground();
        colorOnLightBG = UBApplication::boardController->markerColorOnLightBackground();
    }
    else // settings->stylusTool() == UBStylusTool::Pen + failsafe
    {
        colorOnDarkBG = UBApplication::boardController->penColorOnDarkBackground();
        colorOnLightBG = UBApplication::boardController->penColorOnLightBackground();
    }

    if (mDarkBackground)
    {
        polygonItem->setColor(colorOnDarkBG);
    }
    else
    {
        polygonItem->setColor(colorOnLightBG);
    }

Craig Watson's avatar
Craig Watson committed
1240 1241
    //polygonItem->setColor(QColor(rand()%256, rand()%256, rand()%256, polygonItem->brush().color().alpha()));

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    polygonItem->setColorOnDarkBackground(colorOnDarkBG);
    polygonItem->setColorOnLightBackground(colorOnLightBG);

    polygonItem->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Graphic));
}

UBGraphicsPolygonItem* UBGraphicsScene::arcToPolygonItem(const QLineF& pStartRadius, qreal pSpanAngle, qreal pWidth)
{
    QPolygonF polygon = UBGeometryUtils::arcToPolygon(pStartRadius, pSpanAngle, pWidth);

    return polygonToPolygonItem(polygon);
}

1255 1256 1257 1258 1259 1260 1261 1262
UBGraphicsPolygonItem* UBGraphicsScene::curveToPolygonItem(const QList<QPair<QPointF, qreal> >& points)
{
    QPolygonF polygon = UBGeometryUtils::curveToPolygon(points, false, true);

    return polygonToPolygonItem(polygon);

}

1263 1264 1265 1266 1267 1268 1269
UBGraphicsPolygonItem* UBGraphicsScene::curveToPolygonItem(const QList<QPointF>& points, qreal startWidth, qreal endWidth)
{
    QPolygonF polygon = UBGeometryUtils::curveToPolygon(points, startWidth, endWidth);

    return polygonToPolygonItem(polygon);
}

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1270 1271 1272 1273 1274 1275 1276
void UBGraphicsScene::clearSelectionFrame()
{
    if (mSelectionFrame) {
        mSelectionFrame->setEnclosedItems(QList<QGraphicsItem*>());
    }
}

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
UBBoardView *UBGraphicsScene::controlView()
{
    UBBoardView *result = 0;
    foreach (QGraphicsView *view, views()) {
        if (view->objectName() == CONTROLVIEW_OBJ_NAME) {
            result = static_cast<UBBoardView*>(view);
        }
    }

    return result;
}

1289 1290 1291 1292 1293
void UBGraphicsScene::notifyZChanged(QGraphicsItem *item, qreal zValue)
{
    mZLayerController->shiftStoredZValue(item, zValue);
}

1294
void UBGraphicsScene::updateSelectionFrame()
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1295 1296 1297 1298 1299 1300
{
    if (!mSelectionFrame) {
        mSelectionFrame = new UBSelectionFrame();
        addItem(mSelectionFrame);
    }

1301 1302 1303 1304 1305 1306 1307
    QList<QGraphicsItem*> selItems = selectedItems();
    switch (selItems.count()) {
    case 0 : {
        mSelectionFrame->setVisible(false);
        mSelectionFrame->setEnclosedItems(selItems);
    } break;
    case 1: {
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1308
        mSelectionFrame->setVisible(false);
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        mSelectionFrame->setEnclosedItems(QList<QGraphicsItem*>());

        UBGraphicsItemDelegate *itemDelegate = UBGraphicsItem::Delegate(selItems.first());
        itemDelegate->createControls();
        selItems.first()->setVisible(true);
        itemDelegate->showControls();

    } break;
    default: {
        mSelectionFrame->setVisible(true);
        mSelectionFrame->setEnclosedItems(selItems);
    } break;
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1321 1322 1323
    }
}

1324 1325 1326 1327 1328
void UBGraphicsScene::updateSelectionFrameWrapper(int)
{
    updateSelectionFrame();
}

1329 1330 1331 1332 1333 1334 1335 1336 1337
UBGraphicsPolygonItem* UBGraphicsScene::polygonToPolygonItem(const QPolygonF pPolygon)
{
    UBGraphicsPolygonItem *polygonItem = new UBGraphicsPolygonItem(pPolygon);

    initPolygonItem(polygonItem);

    return polygonItem;
}

1338
void UBGraphicsScene::hideTool()
1339
{
1340 1341
    hideEraser();
    hideMarkerCircle();
1342
    hidePenCircle();
1343 1344 1345 1346 1347
}

void UBGraphicsScene::leaveEvent(QEvent * event)
{
    Q_UNUSED(event);
1348
    hideTool();
1349 1350 1351 1352
}

UBGraphicsScene* UBGraphicsScene::sceneDeepCopy() const
{
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1353
    UBGraphicsScene* copy = new UBGraphicsScene(this->document(), this->mUndoRedoStackEnabled);
1354

Craig Watson's avatar
Craig Watson committed
1355
    copy->setBackground(this->isDarkBackground(), mPageBackground);
1356
    copy->setBackgroundGridSize(mBackgroundGridSize);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    copy->setSceneRect(this->sceneRect());

    if (this->mNominalSize.isValid())
        copy->setNominalSize(this->mNominalSize);

    QListIterator<QGraphicsItem*> itItems(this->mFastAccessItems);
    QMap<UBGraphicsStroke*, UBGraphicsStroke*> groupClone;

    while (itItems.hasNext())
    {
        QGraphicsItem* item = itItems.next();
        QGraphicsItem* cloneItem = 0;
        UBItem* ubItem = dynamic_cast<UBItem*>(item);
        UBGraphicsStroke* stroke = dynamic_cast<UBGraphicsStroke*>(item);
1371 1372 1373 1374 1375 1376
        UBGraphicsGroupContainerItem* group = dynamic_cast<UBGraphicsGroupContainerItem*>(item);

        if(group){
            UBGraphicsGroupContainerItem* groupCloned = group->deepCopyNoChildDuplication();
            groupCloned->resetMatrix();
            groupCloned->resetTransform();
1377
            groupCloned->setPos(0, 0);
1378
            bool locked = groupCloned->Delegate()->isLocked();
1379

1380 1381 1382 1383 1384
            foreach(QGraphicsItem* eachItem ,group->childItems()){
                QGraphicsItem* copiedChild = dynamic_cast<QGraphicsItem*>(dynamic_cast<UBItem*>(eachItem)->deepCopy());
                copy->addItem(copiedChild);
                groupCloned->addToGroup(copiedChild);
            }
1385 1386 1387 1388

            if (locked)
                groupCloned->setData(UBGraphicsItemData::ItemLocked, QVariant(true));

1389
            copy->addItem(groupCloned);
1390
            groupCloned->setMatrix(group->matrix());
1391 1392
            groupCloned->setTransform(QTransform::fromTranslate(group->pos().x(), group->pos().y()));
            groupCloned->setTransform(group->transform(), true);
1393
        }
1394

1395
        if (ubItem && !stroke && !group && item->isVisible())
1396
            cloneItem = dynamic_cast<QGraphicsItem*>(ubItem->deepCopy());
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

        if (cloneItem)
        {
            copy->addItem(cloneItem);

            if (isBackgroundObject(item))
                copy->setAsBackgroundObject(cloneItem);

            if (this->mTools.contains(item))
                copy->mTools << cloneItem;

            UBGraphicsPolygonItem* polygon = dynamic_cast<UBGraphicsPolygonItem*>(item);

            if(polygon)
            {
                UBGraphicsStroke* stroke = dynamic_cast<UBGraphicsStroke*>(item->parentItem());

                if (stroke)
                {
                    UBGraphicsStroke* cloneStroke = groupClone.value(stroke);

                    if (!cloneStroke)
                    {
                        cloneStroke = stroke->deepCopy();
                        groupClone.insert(stroke, cloneStroke);
                    }

                    polygon->setStroke(cloneStroke);
                }
            }
        }
    }

    // TODO UB 4.7 ... complete all members ?

    return copy;
}

UBItem* UBGraphicsScene::deepCopy() const
{
    return sceneDeepCopy();
}

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1440
void UBGraphicsScene::clearContent(clearCase pCase)
1441 1442
{
    QSet<QGraphicsItem*> removedItems;
1443
    UBGraphicsItemUndoCommand::GroupDataTable groupsMap;
1444

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1445 1446
    switch (pCase) {
    case clearBackground :
1447 1448 1449 1450
        if(mBackgroundObject){
            removeItem(mBackgroundObject);
            removedItems << mBackgroundObject;
        }
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        break;

    case clearItemsAndAnnotations :
    case clearItems :
    case clearAnnotations :
        foreach(QGraphicsItem* item, items()) {

            UBGraphicsGroupContainerItem *itemGroup = item->parentItem()
                                                      ? qgraphicsitem_cast<UBGraphicsGroupContainerItem*>(item->parentItem())
                                                      : 0;
            UBGraphicsItemDelegate *curDelegate = UBGraphicsItem::Delegate(item);
            if (!curDelegate) {
                continue;
            }
1465

1466 1467 1468
            bool isGroup = item->type() == UBGraphicsGroupContainerItem::Type;
            bool isStrokesGroup = item->type() == UBGraphicsStrokesGroup::Type;

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
            bool shouldDelete = false;
            switch (static_cast<int>(pCase)) {
            case clearAnnotations :
                shouldDelete = isStrokesGroup;
                break;
            case clearItems :
                shouldDelete = !isGroup && !isBackgroundObject(item) && !isStrokesGroup;
                break;
            case clearItemsAndAnnotations:
                shouldDelete = !isGroup && !isBackgroundObject(item);
                break;
            }
1481

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1482 1483 1484
            if(shouldDelete) {
                if (itemGroup) {
                    itemGroup->removeFromGroup(item);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1485

1486
                    groupsMap.insert(itemGroup, UBGraphicsItem::getOwnUuid(item));
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1487
                    if (itemGroup->childItems().count() == 1) {
1488 1489 1490 1491 1492
                        groupsMap.insert(itemGroup, UBGraphicsItem::getOwnUuid(itemGroup->childItems().first()));
                        QGraphicsItem *lastItem = itemGroup->childItems().first();
                        bool isSelected = itemGroup->isSelected();
                        itemGroup->destroy(false);
                        lastItem->setSelected(isSelected);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1493 1494 1495
                    }
                    itemGroup->Delegate()->update();
                }
1496

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1497
                curDelegate->remove(false);
1498 1499 1500
                removedItems << item;
            }
        }
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1501
        break;
1502 1503 1504 1505 1506
    }

    // force refresh, QT is a bit lazy and take a lot of time (nb item ^2 ?) to trigger repaint
    update(sceneRect());

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1507
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1508

1509
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, removedItems, QSet<QGraphicsItem*>(), groupsMap);
1510 1511 1512
        UBApplication::undoStack->push(uc);
    }

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1513
    if (pCase == clearBackground) {
1514 1515 1516 1517 1518 1519
        mBackgroundObject = 0;
    }

    setDocumentUpdated();
}

1520
UBGraphicsPixmapItem* UBGraphicsScene::addPixmap(const QPixmap& pPixmap, QGraphicsItem* replaceFor, const QPointF& pPos, qreal pScaleFactor, bool pUseAnimation, bool useProxyForDocumentPath)
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
{
    UBGraphicsPixmapItem* pixmapItem = new UBGraphicsPixmapItem();

    pixmapItem->setFlag(QGraphicsItem::ItemIsMovable, true);
    pixmapItem->setFlag(QGraphicsItem::ItemIsSelectable, true);

    pixmapItem->setPixmap(pPixmap);

    QPointF half(pPixmap.width() * pScaleFactor / 2, pPixmap.height()  * pScaleFactor / 2);
    pixmapItem->setPos(pPos - half);

    addItem(pixmapItem);

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1534
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1535 1536 1537 1538
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, replaceFor, pixmapItem);
        UBApplication::undoStack->push(uc);
    }

1539
    pixmapItem->setTransform(QTransform::fromScale(pScaleFactor, pScaleFactor), true);
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

    if (pUseAnimation)
    {
        pixmapItem->setOpacity(0);

        QPropertyAnimation *animation = new QPropertyAnimation(pixmapItem, "opacity");
        animation->setDuration(1000);
        animation->setStartValue(0.0);
        animation->setEndValue(1.0);

        animation->start();
    }

    pixmapItem->show();
    setDocumentUpdated();

1556 1557 1558 1559 1560
    QString documentPath;
    if(useProxyForDocumentPath)
        documentPath = this->document()->persistencePath();
    else
        documentPath = UBApplication::boardController->selectedDocument()->persistencePath();
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

    QString fileName = UBPersistenceManager::imageDirectory + "/" + pixmapItem->uuid().toString() + ".png";

    QString path = documentPath + "/" + fileName;

    if (!QFile::exists(path))
    {
        QDir dir;
        dir.mkdir(documentPath + "/" + UBPersistenceManager::imageDirectory);

        pixmapItem->pixmap().toImage().save(path, "PNG");
    }

1574 1575 1576 1577 1578
    return pixmapItem;
}

void UBGraphicsScene::textUndoCommandAdded(UBGraphicsTextItem *textItem)
{
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1579
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1580 1581 1582 1583 1584 1585
        UBGraphicsTextItemUndoCommand* uc = new UBGraphicsTextItemUndoCommand(textItem);
        UBApplication::undoStack->push(uc);
    }
}
UBGraphicsMediaItem* UBGraphicsScene::addMedia(const QUrl& pMediaFileUrl, bool shouldPlayAsap, const QPointF& pPos)
{
1586 1587 1588 1589 1590
    qDebug() << pMediaFileUrl.toLocalFile();
    if (!QFile::exists(pMediaFileUrl.toLocalFile()))
    if (!QFile::exists(pMediaFileUrl.toString()))
        return NULL;

1591 1592 1593
    UBGraphicsMediaItem * mediaItem = UBGraphicsMediaItem::createMediaItem(pMediaFileUrl);

    if(mediaItem)
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
        connect(UBApplication::boardController, SIGNAL(activeSceneChanged()), mediaItem, SLOT(activeSceneChanged()));

    mediaItem->setPos(pPos);

    mediaItem->setFlag(QGraphicsItem::ItemIsMovable, true);
    mediaItem->setFlag(QGraphicsItem::ItemIsSelectable, true);

    addItem(mediaItem);

    mediaItem->show();

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1605
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1606 1607 1608 1609
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, mediaItem);
        UBApplication::undoStack->push(uc);
    }

1610 1611
    if (shouldPlayAsap)
        mediaItem->play();
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

    setDocumentUpdated();

    return mediaItem;
}

UBGraphicsMediaItem* UBGraphicsScene::addVideo(const QUrl& pVideoFileUrl, bool shouldPlayAsap, const QPointF& pPos)
{
   return addMedia(pVideoFileUrl, shouldPlayAsap, pPos);
}

UBGraphicsMediaItem* UBGraphicsScene::addAudio(const QUrl& pAudioFileUrl, bool shouldPlayAsap, const QPointF& pPos)
{
   return addMedia(pAudioFileUrl, shouldPlayAsap, pPos);
}

UBGraphicsWidgetItem* UBGraphicsScene::addWidget(const QUrl& pWidgetUrl, const QPointF& pPos)
{
1630
    int widgetType = UBGraphicsWidgetItem::widgetType(pWidgetUrl);
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

    if(widgetType == UBWidgetType::Apple)
    {
        return addAppleWidget(pWidgetUrl, pPos);
    }
    else if(widgetType == UBWidgetType::W3C)
    {
        return addW3CWidget(pWidgetUrl, pPos);
    }
    else
    {
        qDebug() << "UBGraphicsScene::addWidget: Unknown widget Type";
        return 0;
    }
}

UBGraphicsAppleWidgetItem* UBGraphicsScene::addAppleWidget(const QUrl& pWidgetUrl, const QPointF& pPos)
{
    UBGraphicsAppleWidgetItem *appleWidget = new UBGraphicsAppleWidgetItem(pWidgetUrl);

    addGraphicsWidget(appleWidget, pPos);

    return appleWidget;
}

1656
UBGraphicsW3CWidgetItem* UBGraphicsScene::addW3CWidget(const QUrl& pWidgetUrl, const QPointF& pPos)
1657
{
1658
    UBGraphicsW3CWidgetItem *w3CWidget = new UBGraphicsW3CWidgetItem(pWidgetUrl, 0);
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672

    addGraphicsWidget(w3CWidget, pPos);

    return w3CWidget;
}

void UBGraphicsScene::addGraphicsWidget(UBGraphicsWidgetItem* graphicsWidget, const QPointF& pPos)
{
    graphicsWidget->setFlag(QGraphicsItem::ItemIsSelectable, true);

    addItem(graphicsWidget);

    qreal ssf = 1 / UBApplication::boardController->systemScaleFactor();

1673
    graphicsWidget->setTransform(QTransform::fromScale(ssf, ssf), true);
1674 1675 1676 1677

    graphicsWidget->setPos(QPointF(pPos.x() - graphicsWidget->boundingRect().width() / 2,
        pPos.y() - graphicsWidget->boundingRect().height() / 2));

1678
    if (graphicsWidget->canBeContent())
1679
    {
1680
        graphicsWidget->loadMainHtml();
1681 1682

        graphicsWidget->setSelected(true);
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1683
        if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
            UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, graphicsWidget);
            UBApplication::undoStack->push(uc);
        }

        setDocumentUpdated();
    }
    else
    {
        UBApplication::boardController->moveGraphicsWidgetToControlView(graphicsWidget);
    }
1694 1695

    UBApplication::boardController->controlView()->setFocus();
1696 1697
}

Yimgo's avatar
Yimgo committed
1698 1699


1700 1701 1702 1703 1704 1705 1706 1707
UBGraphicsW3CWidgetItem* UBGraphicsScene::addOEmbed(const QUrl& pContentUrl, const QPointF& pPos)
{
    QStringList widgetPaths = UBPersistenceManager::persistenceManager()->allWidgets(UBSettings::settings()->applicationApplicationsLibraryDirectory());

    UBGraphicsW3CWidgetItem *widget = 0;

    foreach(QString widgetPath, widgetPaths)
    {
1708
        if (widgetPath.contains("VideoPicker"))
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
        {
            widget = addW3CWidget(QUrl::fromLocalFile(widgetPath), pPos);

            if (widget)
            {
                widget->setPreference("oembedUrl", pContentUrl.toString());
                setDocumentUpdated();
                break;
            }
        }
    }

    return widget;
}

UBGraphicsGroupContainerItem *UBGraphicsScene::createGroup(QList<QGraphicsItem *> items)
{
    UBGraphicsGroupContainerItem *groupItem = new UBGraphicsGroupContainerItem();

Ilia Ryabokon's avatar
Ilia Ryabokon committed
1728
    addItem(groupItem);
1729 1730 1731 1732 1733 1734 1735 1736 1737
    foreach (QGraphicsItem *item, items) {
        if (item->type() == UBGraphicsGroupContainerItem::Type) {
            QList<QGraphicsItem*> childItems = item->childItems();
            UBGraphicsGroupContainerItem *currentGroup = dynamic_cast<UBGraphicsGroupContainerItem*>(item);
            if (currentGroup) {
                currentGroup->destroy();
            }
            foreach (QGraphicsItem *chItem, childItems) {
                groupItem->addToGroup(chItem);
1738
                mFastAccessItems.removeAll(chItem);
1739 1740 1741
            }
        } else {
            groupItem->addToGroup(item);
1742
            mFastAccessItems.removeAll(item);
1743 1744 1745 1746 1747 1748
        }
    }

    groupItem->setVisible(true);
    groupItem->setFocus();

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1749
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1750
        UBGraphicsItemGroupUndoCommand* uc = new UBGraphicsItemGroupUndoCommand(this, groupItem);
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
        UBApplication::undoStack->push(uc);
    }

    setDocumentUpdated();

    return groupItem;
}

void UBGraphicsScene::addGroup(UBGraphicsGroupContainerItem *groupItem)
{
    addItem(groupItem);
1762 1763 1764 1765 1766 1767 1768 1769 1770
    for (int i = 0; i < groupItem->childItems().count(); i++)
    {
        QGraphicsItem *it = qgraphicsitem_cast<QGraphicsItem *>(groupItem->childItems().at(i));
        if (it)
        {
             mFastAccessItems.removeAll(it);
        }
    }

1771 1772 1773 1774 1775 1776 1777
    groupItem->setVisible(true);
    groupItem->setFocus();

    if (groupItem->uuid().isNull()) {
        groupItem->setUuid(QUuid::createUuid());
    }

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1778
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1779 1780 1781 1782 1783 1784 1785
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, groupItem);
        UBApplication::undoStack->push(uc);
    }

    setDocumentUpdated();
}

1786
UBGraphicsSvgItem* UBGraphicsScene::addSvg(const QUrl& pSvgFileUrl, const QPointF& pPos, const QByteArray pData)
1787 1788 1789
{
    QString path = pSvgFileUrl.toLocalFile();

1790 1791 1792 1793 1794
    UBGraphicsSvgItem *svgItem;
    if (pData.isNull())
        svgItem = new UBGraphicsSvgItem(path);
    else
        svgItem = new UBGraphicsSvgItem(pData);
1795 1796 1797 1798 1799

    svgItem->setFlag(QGraphicsItem::ItemIsMovable, true);
    svgItem->setFlag(QGraphicsItem::ItemIsSelectable, true);

    qreal sscale = 1 / UBApplication::boardController->systemScaleFactor();
1800
    svgItem->setTransform(QTransform::fromScale(sscale, sscale), true);
1801 1802 1803 1804 1805 1806 1807

    QPointF half(svgItem->boundingRect().width() / 2, svgItem->boundingRect().height() / 2);
    svgItem->setPos(pPos - half);
    svgItem->show();

    addItem(svgItem);

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1808
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1809 1810 1811 1812 1813 1814
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, svgItem);
        UBApplication::undoStack->push(uc);
    }

    setDocumentUpdated();

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    QString documentPath = UBApplication::boardController->selectedDocument()->persistencePath();

    QString fileName = UBPersistenceManager::imageDirectory + "/" + svgItem->uuid().toString() + ".svg";

    QString completePath = documentPath + "/" + fileName;

    if (!QFile::exists(completePath))
    {
        QDir dir;
        dir.mkdir(documentPath + "/" + UBPersistenceManager::imageDirectory);

        QFile file(completePath);
        if (!file.open(QIODevice::WriteOnly))
        {
            qWarning() << "cannot open file for writing embeded svg content " << completePath;
            return NULL;
        }

        file.write(svgItem->fileData());
        file.close();
    }

1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
    return svgItem;
}

UBGraphicsTextItem* UBGraphicsScene::addText(const QString& pString, const QPointF& pTopLeft)
{
    return addTextWithFont(pString, pTopLeft, UBSettings::settings()->fontPixelSize()
            , UBSettings::settings()->fontFamily(), UBSettings::settings()->isBoldFont()
            , UBSettings::settings()->isItalicFont());
}

UBGraphicsTextItem* UBGraphicsScene::addTextWithFont(const QString& pString, const QPointF& pTopLeft
            , int pointSize, const QString& fontFamily, bool bold, bool italic)
{
    UBGraphicsTextItem *textItem = new UBGraphicsTextItem();
    textItem->setPlainText(pString);

    QFont font = textItem->font();

    if (fontFamily == "")
    {
        font = QFont(UBSettings::settings()->fontFamily());
    }
    else
    {
        font = QFont(fontFamily);
    }

    if (pointSize < 1)
    {
        font.setPixelSize(UBSettings::settings()->fontPixelSize());
    }
    else
    {
        font.setPointSize(pointSize);
    }

    font.setBold(bold);
    font.setItalic(italic);
    textItem->setFont(font);

    QFontMetrics fi(font);
    QRect br = fi.boundingRect(pString);

    textItem->setTextWidth(qMax((qreal)br.width() + 50, (qreal)200));
    textItem->setTextHeight(br.height());

    addItem(textItem);

    textItem->setPos(pTopLeft);

    textItem->show();

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1889
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, textItem);
        UBApplication::undoStack->push(uc);
    }

    connect(textItem, SIGNAL(textUndoCommandAdded(UBGraphicsTextItem *)), this, SLOT(textUndoCommandAdded(UBGraphicsTextItem *)));

    textItem->setSelected(true);
    textItem->setFocus();

    setDocumentUpdated();

    return textItem;
}

UBGraphicsTextItem *UBGraphicsScene::addTextHtml(const QString &pString, const QPointF& pTopLeft)
{
    UBGraphicsTextItem *textItem = new UBGraphicsTextItem();
    textItem->setPlainText("");
1908
    textItem->setHtml(UBTextTools::cleanHtml(pString));
1909 1910 1911 1912

    addItem(textItem);
    textItem->show();

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
1913
    if (mUndoRedoStackEnabled) { //should be deleted after scene own undo stack implemented
1914 1915 1916 1917
        UBGraphicsItemUndoCommand* uc = new UBGraphicsItemUndoCommand(this, 0, textItem);
        UBApplication::undoStack->push(uc);
    }

1918
    connect(textItem, SIGNAL(textUndoCommandAdded(UBGraphicsTextItem *)), this, SLOT(textUndoCommandAdded(UBGraphicsTextItem *)));
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931

    textItem->setFocus();

    setDocumentUpdated();
    textItem->setPos(pTopLeft);

    return textItem;
}

void UBGraphicsScene::addItem(QGraphicsItem* item)
{
    UBCoreGraphicsScene::addItem(item);

Claudio Valerio's avatar
Claudio Valerio committed
1932
    // the default z value is already set. This is the case when a svg file is read
1933 1934 1935 1936
    if(item->zValue() == DEFAULT_Z_VALUE
            || item->zValue() == UBZLayerController::errorNum()
            || !mZLayerController->zLevelAvailable(item->zValue()))
    {
Claudio Valerio's avatar
Claudio Valerio committed
1937 1938 1939
        qreal zvalue = mZLayerController->generateZLevel(item);
        UBGraphicsItem::assignZValue(item, zvalue);
    }
1940

1941 1942 1943
    else
        notifyZChanged(item, item->zValue());

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    if (!mTools.contains(item))
      ++mItemCount;

    mFastAccessItems << item;
}

void UBGraphicsScene::addItems(const QSet<QGraphicsItem*>& items)
{
    foreach(QGraphicsItem* item, items) {
        UBCoreGraphicsScene::addItem(item);
        UBGraphicsItem::assignZValue(item, mZLayerController->generateZLevel(item));
    }

    mItemCount += items.size();

    mFastAccessItems += items.toList();
}

void UBGraphicsScene::removeItem(QGraphicsItem* item)
{
1964
    item->setSelected(false);
1965
    UBCoreGraphicsScene::removeItem(item);
1966
    UBApplication::boardController->freezeW3CWidget(item, true);
1967 1968 1969 1970 1971

    if (!mTools.contains(item))
      --mItemCount;

    mFastAccessItems.removeAll(item);
1972 1973 1974
    /* delete the item if it is cache to allow its reinstanciation, because Cache implements design pattern Singleton. */
    if (dynamic_cast<UBGraphicsCache*>(item))
        UBCoreGraphicsScene::deleteItem(item);
1975 1976 1977 1978
}

void UBGraphicsScene::removeItems(const QSet<QGraphicsItem*>& items)
{
1979
    foreach(QGraphicsItem* item, items)
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
        UBCoreGraphicsScene::removeItem(item);

    mItemCount -= items.size();

    foreach(QGraphicsItem* item, items)
        mFastAccessItems.removeAll(item);
}

void UBGraphicsScene::deselectAllItems()
{
    foreach(QGraphicsItem *gi, selectedItems ())
    {
1992
        gi->clearFocus();
1993
        gi->setSelected(false);
1994 1995 1996 1997
        // Hide selection frame
        if (mSelectionFrame) {
            mSelectionFrame->setEnclosedItems(QList<QGraphicsItem*>());
        }
Nicolas Nenon's avatar
Nicolas Nenon committed
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
        UBGraphicsTextItem* textItem = dynamic_cast<UBGraphicsTextItem*>(gi);
        if(textItem)
            textItem->activateTextEditor(false);
    }
}

void UBGraphicsScene::deselectAllItemsExcept(QGraphicsItem* item)
{
    foreach(QGraphicsItem* eachItem,selectedItems()){
        if(eachItem != item){
            eachItem->setSelected(false);

            UBGraphicsTextItem* textItem = dynamic_cast<UBGraphicsTextItem*>(eachItem);
            if(textItem)
                textItem->activateTextEditor(false);
        }
2014 2015 2016
    }
}

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
/**
 * Return the bounding rectangle of all items on the page except for tools (ruler, compass,...)
 */
QRectF UBGraphicsScene::annotationsBoundingRect() const
{
    QRectF boundingRect;

    foreach (QGraphicsItem *item, items()) {
        if (!mTools.contains(rootItem(item)))
            boundingRect |= item->sceneBoundingRect();
    }

    return boundingRect;
}

2032 2033
bool UBGraphicsScene::isEmpty() const
{
2034
    return mItemCount == 0;
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
}

QGraphicsItem* UBGraphicsScene::setAsBackgroundObject(QGraphicsItem* item, bool pAdaptTransformation, bool pExpand)
{
    if (mBackgroundObject)
    {
        removeItem(mBackgroundObject);
        mBackgroundObject = 0;
    }

    if (item)
    {
        item->setFlag(QGraphicsItem::ItemIsSelectable, false);
        item->setFlag(QGraphicsItem::ItemIsMovable, false);
        item->setAcceptedMouseButtons(Qt::NoButton);
        item->setData(UBGraphicsItemData::ItemLayerType, UBItemLayerType::FixedBackground);

        if (pAdaptTransformation)
        {
            item = scaleToFitDocumentSize(item, true, 0, pExpand);
        }

        if (item->scene() != this)
            addItem(item);

2060 2061 2062
        mZLayerController->setLayerType(item, itemLayerType::BackgroundItem);
        UBGraphicsItem::assignZValue(item, mZLayerController->generateZLevel(item));

2063 2064 2065 2066 2067 2068 2069
        mBackgroundObject = item;

    }

    return item;
}

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
void UBGraphicsScene::unsetBackgroundObject()
{
    if (!mBackgroundObject)
        return;

    mBackgroundObject->setFlag(QGraphicsItem::ItemIsSelectable, true);
    mBackgroundObject->setFlag(QGraphicsItem::ItemIsMovable, true);
    mBackgroundObject->setAcceptedMouseButtons(Qt::LeftButton);

    // Item zLayer and Layer Type should be set by the caller of this function, as
    // it may depend on the object type, where it was before, etc.

    mBackgroundObject = 0;
}

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
QRectF UBGraphicsScene::normalizedSceneRect(qreal ratio)
{

    QRectF normalizedRect(nominalSize().width() / -2, nominalSize().height() / -2,
        nominalSize().width(), nominalSize().height());

    foreach(QGraphicsItem* gi, mFastAccessItems)
    {
        if(gi && gi->isVisible() && !mTools.contains(gi))
        {
            normalizedRect = normalizedRect.united(gi->sceneBoundingRect());
        }
    }

    if (ratio > 0.0)
    {
        qreal normalizedRectRatio = normalizedRect.width() / normalizedRect.height();

        if (normalizedRectRatio > ratio)
        {
            //the normalized rect is too wide, we increase height
            qreal newHeight = normalizedRect.width() / ratio;
            qreal offset = (newHeight - normalizedRect.height()) / 2;
            normalizedRect.setY(normalizedRect.y() - offset);
            normalizedRect.setHeight(newHeight);
        }
        else if (normalizedRectRatio < ratio)
        {
            //the normalized rect is too high, we increase the width
            qreal newWidth = normalizedRect.height() * ratio;
            qreal offset = (newWidth - normalizedRect.width()) / 2;
            normalizedRect.setX(normalizedRect.x() - offset);
            normalizedRect.setWidth(newWidth);
        }
    }

    return normalizedRect;
}

2124
QGraphicsItem *UBGraphicsScene::itemForUuid(QUuid uuid)
2125 2126
{
    QGraphicsItem *result = 0;
2127
    QString ui = uuid.toString();
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163

    //simple search before implementing container for fast access
    foreach (QGraphicsItem *item, items()) {
        if (UBGraphicsScene::getPersonalUuid(item) == uuid && !uuid.isNull()) {
            result = item;
        }
    }

    return result;
}

void UBGraphicsScene::setDocument(UBDocumentProxy* pDocument)
{
    if (pDocument != mDocument)
    {
        if (mDocument)
        {
            setModified(true);
        }

        mDocument = pDocument;
        setParent(pDocument);
    }
}

QGraphicsItem* UBGraphicsScene::scaleToFitDocumentSize(QGraphicsItem* item, bool center, int margin, bool expand)
{
    int maxWidth = mNominalSize.width() - (margin * 2);
    int maxHeight = mNominalSize.height() - (margin * 2);

    QRectF size = item->sceneBoundingRect();

    if (expand || size.width() > maxWidth || size.height() > maxHeight)
    {
        qreal ratio = qMin(maxWidth / size.width(), maxHeight / size.height());

2164
        item->setTransform(QTransform::fromScale(ratio, ratio), true);
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268

        if(center)
        {
            item->setPos(item->sceneBoundingRect().width() / -2.0,
                item->sceneBoundingRect().height() / -2.0);
        }
    }

    return item;
}

void UBGraphicsScene::addRuler(QPointF center)
{
    UBGraphicsRuler* ruler = new UBGraphicsRuler(); // mem : owned and destroyed by the scene
    mTools << ruler;
    QRectF rect = ruler->rect();
    ruler->setRect(center.x() - rect.width()/2, center.y() - rect.height()/2, rect.width(), rect.height());

    ruler->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));

    addItem(ruler);

    ruler->setVisible(true);
}

void UBGraphicsScene::addProtractor(QPointF center)
{
    // Protractor

    UBGraphicsProtractor* protractor = new UBGraphicsProtractor(); // mem : owned and destroyed by the scene
    mTools << protractor;

    protractor->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));

    addItem(protractor);

    QPointF itemSceneCenter = protractor->sceneBoundingRect().center();
    protractor->moveBy(center.x() - itemSceneCenter.x(), center.y() - itemSceneCenter.y());

    protractor->setVisible(true);
}

void UBGraphicsScene::addTriangle(QPointF center)
{
    // Triangle

    UBGraphicsTriangle* triangle = new UBGraphicsTriangle(); // mem : owned and destroyed by the scene
    mTools << triangle;

    triangle->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));

    addItem(triangle);

    QPointF itemSceneCenter = triangle->sceneBoundingRect().center();
    triangle->moveBy(center.x() - itemSceneCenter.x(), center.y() - itemSceneCenter.y());

    triangle->setVisible(true);
}

void UBGraphicsScene::addMagnifier(UBMagnifierParams params)
{
    // can have only one magnifier at one time
    if(magniferControlViewWidget) return;

    QWidget *cContainer = (QWidget*)(UBApplication::boardController->controlContainer());
    QGraphicsView *cView = (QGraphicsView*)UBApplication::boardController->controlView();
    QGraphicsView *dView = (QGraphicsView*)UBApplication::boardController->displayView();

    QPoint dvZeroPoint = dView->mapToGlobal(QPoint(0,0));

    int cvW = cView->width();
    int dvW = dView->width();
    qreal wCoeff = (qreal)dvW / (qreal)cvW;

    int cvH = cView->height();
    int dvH = dView->height();
    qreal hCoeff = (qreal)dvH / (qreal)cvH;

    QPoint ccPoint(params.x,params.y);
    QPoint globalPoint = cContainer->mapToGlobal(ccPoint);
    QPoint cvPoint = cView->mapFromGlobal(globalPoint);
    QPoint dvPoint( cvPoint.x() * wCoeff + dvZeroPoint.x(), cvPoint.y() * hCoeff + dvZeroPoint.y());

    magniferControlViewWidget = new UBMagnifier((QWidget*)(UBApplication::boardController->controlContainer()), true);
    magniferControlViewWidget->setGrabView((QGraphicsView*)UBApplication::boardController->controlView());
    magniferControlViewWidget->setMoveView((QWidget*)(UBApplication::boardController->controlContainer()));
    magniferControlViewWidget->setSize(params.sizePercentFromScene);
    magniferControlViewWidget->setZoom(params.zoom);

    magniferDisplayViewWidget = new UBMagnifier((QWidget*)(UBApplication::boardController->displayView()), false);
    magniferDisplayViewWidget->setGrabView((QGraphicsView*)UBApplication::boardController->controlView());
    magniferDisplayViewWidget->setMoveView((QGraphicsView*)UBApplication::boardController->displayView());
    magniferDisplayViewWidget->setSize(params.sizePercentFromScene);
    magniferDisplayViewWidget->setZoom(params.zoom);

    magniferControlViewWidget->grabNMove(globalPoint, globalPoint, true);
    magniferDisplayViewWidget->grabNMove(globalPoint, dvPoint, true);
    magniferControlViewWidget->show();
    magniferDisplayViewWidget->show();

    connect(magniferControlViewWidget, SIGNAL(magnifierMoved_Signal(QPoint)), this, SLOT(moveMagnifier(QPoint)));
    connect(magniferControlViewWidget, SIGNAL(magnifierClose_Signal()), this, SLOT(closeMagnifier()));
    connect(magniferControlViewWidget, SIGNAL(magnifierZoomIn_Signal()), this, SLOT(zoomInMagnifier()));
    connect(magniferControlViewWidget, SIGNAL(magnifierZoomOut_Signal()), this, SLOT(zoomOutMagnifier()));
2269
    connect(magniferControlViewWidget, SIGNAL(magnifierDrawingModeChange_Signal(int)), this, SLOT(changeMagnifierMode(int)));
2270 2271 2272 2273 2274
    connect(magniferControlViewWidget, SIGNAL(magnifierResized_Signal(qreal)), this, SLOT(resizedMagnifier(qreal)));

    setModified(true);
}

2275 2276 2277 2278 2279 2280
void UBGraphicsScene::moveMagnifier()
{
   if (magniferControlViewWidget)
   {
       QPoint magnifierPos = QPoint(magniferControlViewWidget->pos().x() + magniferControlViewWidget->size().width() / 2, magniferControlViewWidget->pos().y() + magniferControlViewWidget->size().height() / 2 );
       moveMagnifier(magnifierPos, true);
2281
       setModified(true);
2282 2283 2284 2285
   }
}

void UBGraphicsScene::moveMagnifier(QPoint newPos, bool forceGrab)
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
{
    QWidget *cContainer = (QWidget*)(UBApplication::boardController->controlContainer());
    QGraphicsView *cView = (QGraphicsView*)UBApplication::boardController->controlView();
    QGraphicsView *dView = (QGraphicsView*)UBApplication::boardController->displayView();

    QPoint dvZeroPoint = dView->mapToGlobal(QPoint(0,0));

    int cvW = cView->width();
    int dvW = dView->width();
    qreal wCoeff = (qreal)dvW / (qreal)cvW;

    int cvH = cView->height();
    int dvH = dView->height();
    qreal hCoeff = (qreal)dvH / (qreal)cvH;

    QPoint globalPoint = cContainer->mapToGlobal(newPos);
    QPoint cvPoint = cView->mapFromGlobal(globalPoint);
    QPoint dvPoint( cvPoint.x() * wCoeff + dvZeroPoint.x(), cvPoint.y() * hCoeff + dvZeroPoint.y());

2305 2306
    magniferControlViewWidget->grabNMove(globalPoint, globalPoint, forceGrab, false);
    magniferDisplayViewWidget->grabNMove(globalPoint, dvPoint, forceGrab, true);
2307 2308 2309 2310 2311 2312 2313

    setModified(true);
}

void UBGraphicsScene::closeMagnifier()
{
    DisposeMagnifierQWidgets();
2314
    setModified(true);
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
}

void UBGraphicsScene::zoomInMagnifier()
{
    if(magniferControlViewWidget->params.zoom < 8)
    {
        magniferControlViewWidget->setZoom(magniferControlViewWidget->params.zoom + 0.5);
        magniferDisplayViewWidget->setZoom(magniferDisplayViewWidget->params.zoom + 0.5);
    }
}

void UBGraphicsScene::zoomOutMagnifier()
{
    if(magniferControlViewWidget->params.zoom > 1)
    {
        magniferControlViewWidget->setZoom(magniferControlViewWidget->params.zoom - 0.5);
        magniferDisplayViewWidget->setZoom(magniferDisplayViewWidget->params.zoom - 0.5);
2332
        setModified(true);
2333 2334 2335
    }
}

2336 2337 2338 2339 2340 2341
void UBGraphicsScene::changeMagnifierMode(int mode)
{
    if(magniferControlViewWidget)
        magniferControlViewWidget->setDrawingMode(mode);
}

2342 2343 2344 2345 2346 2347 2348 2349
void UBGraphicsScene::resizedMagnifier(qreal newPercent)
{
    if(newPercent > 18 && newPercent < 50)
    {
        magniferControlViewWidget->setSize(newPercent);
        magniferControlViewWidget->grabPoint();
        magniferDisplayViewWidget->setSize(newPercent);
        magniferDisplayViewWidget->grabPoint();
2350
        setModified(true);
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
    }
}

void UBGraphicsScene::addCompass(QPointF center)
{
    UBGraphicsCompass* compass = new UBGraphicsCompass(); // mem : owned and destroyed by the scene
    mTools << compass;
    addItem(compass);

    QRectF rect = compass->rect();
    compass->setRect(center.x() - rect.width() / 2, center.y() - rect.height() / 2, rect.width(), rect.height());

    compass->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));

    compass->setVisible(true);
}

void UBGraphicsScene::addCache()
{
2370 2371 2372
    UBGraphicsCache* cache = UBGraphicsCache::instance(this);
    if (!items().contains(cache)) {
        addItem(cache);
2373

2374
        cache->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));
2375

2376 2377 2378 2379 2380
        cache->setVisible(true);
        cache->setSelected(true);
        UBApplication::boardController->notifyCache(true);
        UBApplication::boardController->notifyPageChanged();
    }
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
}

void UBGraphicsScene::addMask(const QPointF &center)
{
    UBGraphicsCurtainItem* curtain = new UBGraphicsCurtainItem(); // mem : owned and destroyed by the scene
    mTools << curtain;

    addItem(curtain);

    QRectF rect = UBApplication::boardController->activeScene()->normalizedSceneRect();
    rect.setRect(center.x() - rect.width()/4, center.y() - rect.height()/4, rect.width()/2 , rect.height()/2);
    curtain->setRect(rect);
    curtain->setVisible(true);
    curtain->setSelected(true);
}

void UBGraphicsScene::setRenderingQuality(UBItem::RenderingQuality pRenderingQuality)
{
    QListIterator<QGraphicsItem*> itItems(mFastAccessItems);

    while (itItems.hasNext())
    {
        QGraphicsItem *gItem =  itItems.next();

        UBItem *ubItem = dynamic_cast<UBItem*>(gItem);

        if (ubItem)
        {
            ubItem->setRenderingQuality(pRenderingQuality);
        }
    }
}

QList<QUrl> UBGraphicsScene::relativeDependencies() const
{
    QList<QUrl> relativePathes;

    QListIterator<QGraphicsItem*> itItems(mFastAccessItems);

    while (itItems.hasNext())
    {
2422
        QGraphicsItem* item = itItems.next();
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435

        UBGraphicsVideoItem *videoItem = qgraphicsitem_cast<UBGraphicsVideoItem*> (item);
        if (videoItem){
            QString completeFileName = QFileInfo(videoItem->mediaFileUrl().toLocalFile()).fileName();
            QString path = UBPersistenceManager::videoDirectory + "/";
            relativePathes << QUrl(path + completeFileName);
            continue;
        }

        UBGraphicsAudioItem *audioItem = qgraphicsitem_cast<UBGraphicsAudioItem*> (item);
        if (audioItem){
            QString completeFileName = QFileInfo(audioItem->mediaFileUrl().toLocalFile()).fileName();
            QString path = UBPersistenceManager::audioDirectory + "/";
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
            relativePathes << QUrl(path + completeFileName);
            continue;
        }

        UBGraphicsWidgetItem* widget = qgraphicsitem_cast<UBGraphicsWidgetItem*>(item);
        if(widget){
            QString widgetPath = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString() + ".wgt";
            QString screenshotPath = UBPersistenceManager::widgetDirectory + "/" + widget->uuid().toString().remove("{").remove("}") + ".png";
            relativePathes << QUrl(widgetPath);
            relativePathes << QUrl(screenshotPath);
            continue;
        }

        UBGraphicsPixmapItem* pixmapItem = qgraphicsitem_cast<UBGraphicsPixmapItem*>(item);
        if(pixmapItem){
            relativePathes << QUrl(UBPersistenceManager::imageDirectory + "/" + pixmapItem->uuid().toString() + ".png");
            continue;
        }

        UBGraphicsSvgItem* svgItem = qgraphicsitem_cast<UBGraphicsSvgItem*>(item);
        if(svgItem){
            relativePathes << QUrl(UBPersistenceManager::imageDirectory + "/" + svgItem->uuid().toString() + ".svg");
            continue;
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
        }
    }

    return relativePathes;
}

QSize UBGraphicsScene::nominalSize()
{
    if (mDocument && !mNominalSize.isValid())
    {
        mNominalSize = mDocument->defaultDocumentSize();
    }

    return mNominalSize;
}

2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
/**
 * @brief Return the scene's boundary size, including any background item
 *
 * If no background item is present, this returns nominalSize()
 */
QSize UBGraphicsScene::sceneSize()
{
    UBGraphicsPDFItem *pdfItem = qgraphicsitem_cast<UBGraphicsPDFItem*>(backgroundObject());

    if (pdfItem) {
        QRectF targetRect = pdfItem->sceneBoundingRect();
        return targetRect.size().toSize();
    }

    else
        return nominalSize();
}

2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
void UBGraphicsScene::setNominalSize(const QSize& pSize)
{
    if (nominalSize() != pSize)
    {
        mNominalSize = pSize;

        if(mDocument)
            mDocument->setDefaultDocumentSize(pSize);
    }
}

void UBGraphicsScene::setNominalSize(int pWidth, int pHeight)
{
     setNominalSize(QSize(pWidth, pHeight));
}

void UBGraphicsScene::setSelectedZLevel(QGraphicsItem * item)
{
    item->setZValue(mZLayerController->generateZLevel(itemLayerType::SelectedItem));
}

void UBGraphicsScene::setOwnZlevel(QGraphicsItem *item)
{
    item->setZValue(item->data(UBGraphicsItemData::ItemOwnZValue).toReal());
}

QUuid UBGraphicsScene::getPersonalUuid(QGraphicsItem *item)
{
    QString idCandidate = item->data(UBGraphicsItemData::ItemUuid).toString();
    return idCandidate == QUuid().toString() ? QUuid() : QUuid(idCandidate);
}

2525
qreal UBGraphicsScene::changeZLevelTo(QGraphicsItem *item, UBZLayerController::moveDestination dest, bool addUndo)
2526
{
2527 2528 2529 2530 2531 2532 2533 2534 2535
    qreal previousZVal = item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
    qreal res = mZLayerController->changeZLevelTo(item, dest);

    if(addUndo){
        UBGraphicsItemZLevelUndoCommand* uc = new UBGraphicsItemZLevelUndoCommand(this, item, previousZVal, dest);
        UBApplication::undoStack->push(uc);
    }

    return res;
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
}

QGraphicsItem* UBGraphicsScene::rootItem(QGraphicsItem* item) const
{
    QGraphicsItem* root = item;

    while (root->parentItem())
    {
        root = root->parentItem();
    }

    return root;
}

void UBGraphicsScene::drawItems (QPainter * painter, int numItems,
        QGraphicsItem * items[], const QStyleOptionGraphicsItem options[], QWidget * widget)
{
    if (mRenderingContext == NonScreen || mRenderingContext == PdfExport)
    {
        int count = 0;

        QGraphicsItem** itemsFiltered = new QGraphicsItem*[numItems];
        QStyleOptionGraphicsItem *optionsFiltered = new QStyleOptionGraphicsItem[numItems];

        for (int i = 0; i < numItems; i++)
        {
            if (!mTools.contains(rootItem(items[i])))
            {
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
2564 2565
                bool isPdfItem =  qgraphicsitem_cast<UBGraphicsPDFItem*> (items[i]) != NULL;
                if(!isPdfItem || mRenderingContext == NonScreen)
2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
                {
                    itemsFiltered[count] = items[i];
                    optionsFiltered[count] = options[i];
                    count++;
                }
            }
        }

        QGraphicsScene::drawItems(painter, count, itemsFiltered, optionsFiltered, widget);

        delete[] optionsFiltered;
        delete[] itemsFiltered;

    }
    else if (mRenderingContext == Podcast)
    {
        int count = 0;

        QGraphicsItem** itemsFiltered = new QGraphicsItem*[numItems];
        QStyleOptionGraphicsItem *optionsFiltered = new QStyleOptionGraphicsItem[numItems];

        for (int i = 0; i < numItems; i++)
        {
            bool ok;
            int itemLayerType = items[i]->data(UBGraphicsItemData::ItemLayerType).toInt(&ok);
            if (ok && (itemLayerType >= UBItemLayerType::FixedBackground && itemLayerType <= UBItemLayerType::Tool))
            {
                itemsFiltered[count] = items[i];
                optionsFiltered[count] = options[i];
                count++;
            }
        }

        QGraphicsScene::drawItems(painter, count, itemsFiltered, optionsFiltered, widget);

        delete[] optionsFiltered;
        delete[] itemsFiltered;

    }
    else
    {
        QGraphicsScene::drawItems(painter, numItems, items, options, widget);
    }
}

void UBGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
    if (mIsDesktopMode)
    {
        QGraphicsScene::drawBackground (painter, rect);
        return;
    }
    bool darkBackground = isDarkBackground ();

    if (darkBackground)
    {
      painter->fillRect (rect, QBrush (QColor (Qt::black)));
    }
    else
    {
      painter->fillRect (rect, QBrush (QColor (Qt::white)));
    }

    if (mZoomFactor > 0.5)
    {
        QColor bgCrossColor;

        if (darkBackground)
2634
            bgCrossColor = QColor(UBSettings::settings()->boardCrossColorDarkBackground->get().toString());
2635
        else
2636
            bgCrossColor = QColor(UBSettings::settings()->boardCrossColorLightBackground->get().toString());
2637
        if (mZoomFactor < 0.7)
2638 2639 2640 2641 2642 2643 2644
        {
            int alpha = 255 * mZoomFactor / 2;
            bgCrossColor.setAlpha (alpha); // fade the crossing on small zooms
        }

        painter->setPen (bgCrossColor);

Craig Watson's avatar
Craig Watson committed
2645
        if (mPageBackground == UBPageBackground::crossed)
2646
        {
2647
            qreal firstY = ((int) (rect.y () / backgroundGridSize())) * backgroundGridSize();
2648

2649
            for (qreal yPos = firstY; yPos < rect.y () + rect.height (); yPos += backgroundGridSize())
2650 2651 2652 2653
            {
                painter->drawLine (rect.x (), yPos, rect.x () + rect.width (), yPos);
            }

2654
            qreal firstX = ((int) (rect.x () / backgroundGridSize())) * backgroundGridSize();
2655

2656
            for (qreal xPos = firstX; xPos < rect.x () + rect.width (); xPos += backgroundGridSize())
2657 2658 2659 2660
            {
                painter->drawLine (xPos, rect.y (), xPos, rect.y () + rect.height ());
            }
        }
Craig Watson's avatar
Craig Watson committed
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670

        else if (mPageBackground == UBPageBackground::ruled)
        {
            qreal firstY = ((int) (rect.y () / backgroundGridSize())) * backgroundGridSize();

            for (qreal yPos = firstY; yPos < rect.y () + rect.height (); yPos += backgroundGridSize())
            {
                painter->drawLine (rect.x (), yPos, rect.x () + rect.width (), yPos);
            }
        }
2671 2672 2673 2674 2675 2676 2677 2678
    }
}

void UBGraphicsScene::keyReleaseEvent(QKeyEvent * keyEvent)
{

    QList<QGraphicsItem*> si = selectedItems();

2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
    if(keyEvent->matches(QKeySequence::SelectAll)){
        QListIterator<QGraphicsItem*> itItems(this->mFastAccessItems);

        while (itItems.hasNext())
            itItems.next()->setSelected(true);

        keyEvent->accept();
        return;
    }

2689 2690 2691 2692 2693 2694 2695 2696
    if ((si.size() > 0) && (keyEvent->isAccepted()))
    {
#ifdef Q_OS_MAC
        if (keyEvent->key() == Qt::Key_Backspace)
#else
        if (keyEvent->matches(QKeySequence::Delete))
#endif
        {
2697 2698 2699 2700 2701
            QVector<UBGraphicsItem*> ubItemsToRemove;
            QVector<QGraphicsItem*> itemToRemove;

            bool bRemoveOk = true;

2702 2703 2704 2705
            foreach(QGraphicsItem* item, si)
            {
                switch (item->type())
                {
2706
                case UBGraphicsWidgetItem::Type:
2707 2708 2709 2710
                    {
                        UBGraphicsW3CWidgetItem *wc3_widget = dynamic_cast<UBGraphicsW3CWidgetItem*>(item);
                        if (0 != wc3_widget)
                        if (!wc3_widget->hasFocus())
2711
                            ubItemsToRemove << wc3_widget;
2712 2713 2714 2715 2716
                        break;
                    }
                case UBGraphicsTextItem::Type:
                    {
                        UBGraphicsTextItem *text_item = dynamic_cast<UBGraphicsTextItem*>(item);
2717 2718 2719 2720 2721 2722
                        if (0 != text_item){
                            if (!text_item->hasFocus())
                                ubItemsToRemove << text_item;
                            else
                                bRemoveOk = false;
                        }
2723 2724 2725
                        break;
                    }

2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
                case UBGraphicsGroupContainerItem::Type:
                {
                    UBGraphicsGroupContainerItem* group_item = dynamic_cast<UBGraphicsGroupContainerItem*>(item);
                    if(NULL != group_item){
                        if(!hasTextItemWithFocus(group_item))
                            ubItemsToRemove << group_item;
                        else
                            bRemoveOk = false;
                    }
                    break;
                }

2738 2739 2740 2741
                default:
                    {
                        UBGraphicsItem *ubgi = dynamic_cast<UBGraphicsItem*>(item);
                        if (0 != ubgi)
2742
                            ubItemsToRemove << ubgi;
2743
                        else
2744
                            itemToRemove << item;
2745 2746 2747
                    }
                }
            }
2748 2749 2750 2751 2752 2753 2754 2755 2756

            if(bRemoveOk){
                foreach(UBGraphicsItem* pUBItem, ubItemsToRemove){
                    pUBItem->remove();
                }
                foreach(QGraphicsItem* pItem, itemToRemove){
                    UBCoreGraphicsScene::removeItem(pItem);
                }
            }
2757 2758 2759 2760 2761 2762 2763 2764
        }

        keyEvent->accept();
    }

    QGraphicsScene::keyReleaseEvent(keyEvent);
}

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
bool UBGraphicsScene::hasTextItemWithFocus(UBGraphicsGroupContainerItem *item){
    bool bHasFocus = false;

    foreach(QGraphicsItem* pItem, item->childItems()){
        UBGraphicsTextItem *text_item = dynamic_cast<UBGraphicsTextItem*>(pItem);
        if (NULL != text_item){
            if(text_item->hasFocus()){
                bHasFocus = true;
                break;
            }
        }
    }

    return bHasFocus;
}

2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804

void UBGraphicsScene::simplifyCurrentStroke()
{
    if (!mCurrentStroke)
        return;

    UBGraphicsStroke* simplerStroke = mCurrentStroke->simplify();
    if (!simplerStroke)
        return;

    foreach(UBGraphicsPolygonItem* poly, mCurrentStroke->polygons()){
        mPreviousPolygonItems.removeAll(poly);
        removeItem(poly);
    }

    mCurrentStroke = simplerStroke;

    foreach(UBGraphicsPolygonItem* poly, mCurrentStroke->polygons()) {
        addItem(poly);
        mPreviousPolygonItems.append(poly);
    }

}

2805 2806 2807 2808 2809 2810 2811 2812 2813
void UBGraphicsScene::setDocumentUpdated()
{
    if (document())
        document()->setMetaData(UBSettings::documentUpdatedAt
                , UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime()));
}

void UBGraphicsScene::createEraiser()
{
2814 2815 2816 2817
    if (UBSettings::settings()->showEraserPreviewCircle->get().toBool()) {
        mEraser = new QGraphicsEllipseItem(); // mem : owned and destroyed by the scene
        mEraser->setRect(QRect(0, 0, 0, 0));
        mEraser->setVisible(false);
2818

2819
        updateEraserColor();
2820

2821 2822
        mEraser->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Control));
        mEraser->setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::Eraiser)); //Necessary to set if we want z value to be assigned correctly
2823

2824 2825 2826
        mTools << mEraser;
        addItem(mEraser);
    }
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
}

void UBGraphicsScene::createPointer()
{
    mPointer = new QGraphicsEllipseItem();  // mem : owned and destroyed by the scene
    mPointer->setRect(QRect(0, 0, 20, 20));
    mPointer->setVisible(false);

    mPointer->setPen(Qt::NoPen);
    mPointer->setBrush(QBrush(QColor(255, 0, 0, 186)));

    mPointer->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Tool));
    mPointer->setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::Pointer)); //Necessary to set if we want z value to be assigned correctly

    mTools << mPointer;
    addItem(mPointer);
}

2845 2846
void UBGraphicsScene::createMarkerCircle()
{
2847 2848
    if (UBSettings::settings()->showMarkerPreviewCircle->get().toBool()) {
        mMarkerCircle = new QGraphicsEllipseItem();
2849

2850 2851
        mMarkerCircle->setRect(QRect(0, 0, 0, 0));
        mMarkerCircle->setVisible(false);
2852

2853
        mMarkerCircle->setPen(Qt::DotLine);
2854
        updateMarkerCircleColor();
2855

2856 2857
        mMarkerCircle->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Control));
        mMarkerCircle->setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::Eraiser));
2858

2859 2860 2861
        mTools << mMarkerCircle;
        addItem(mMarkerCircle);
    }
2862 2863
}

2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
void UBGraphicsScene::createPenCircle()
{
    if (UBSettings::settings()->showPenPreviewCircle->get().toBool()) {
        mPenCircle = new QGraphicsEllipseItem();

        mPenCircle->setRect(QRect(0, 0, 0, 0));
        mPenCircle->setVisible(false);

        mPenCircle->setPen(Qt::DotLine);
        updatePenCircleColor();

        mPenCircle->setData(UBGraphicsItemData::ItemLayerType, QVariant(UBItemLayerType::Control));
        mPenCircle->setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::Eraiser));

        mTools << mPenCircle;
        addItem(mPenCircle);
    }
}

2883
void UBGraphicsScene::updateEraserColor()
2884 2885 2886 2887
{
    if (!mEraser)
        return;

2888
    if (mDarkBackground) {
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
        mEraser->setBrush(UBSettings::eraserBrushDarkBackground);
        mEraser->setPen(UBSettings::eraserPenDarkBackground);
    }

    else {
        mEraser->setBrush(UBSettings::eraserBrushLightBackground);
        mEraser->setPen(UBSettings::eraserPenLightBackground);
    }
}

2899
void UBGraphicsScene::updateMarkerCircleColor()
2900 2901 2902 2903 2904 2905
{
    if (!mMarkerCircle)
        return;

    QPen mcPen = mMarkerCircle->pen();

2906
    if (mDarkBackground) {
2907
        mcPen.setColor(UBSettings::markerCirclePenColorDarkBackground);
2908
        mMarkerCircle->setBrush(UBSettings::markerCircleBrushColorDarkBackground);
2909 2910 2911 2912
    }

    else {
        mcPen.setColor(UBSettings::markerCirclePenColorLightBackground);
2913
        mMarkerCircle->setBrush(UBSettings::markerCircleBrushColorLightBackground);
2914 2915
    }

2916
    mcPen.setStyle(Qt::DotLine);
2917 2918 2919
    mMarkerCircle->setPen(mcPen);
}

2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
void UBGraphicsScene::updatePenCircleColor()
{
    if (!mPenCircle)
        return;

    QPen mcPen = mPenCircle->pen();

    if (mDarkBackground) {
        mcPen.setColor(UBSettings::penCirclePenColorDarkBackground);
        mPenCircle->setBrush(UBSettings::penCircleBrushColorDarkBackground);
    }

    else {
        mcPen.setColor(UBSettings::penCirclePenColorLightBackground);
        mPenCircle->setBrush(UBSettings::penCircleBrushColorLightBackground);
    }

    mcPen.setStyle(Qt::DotLine);
    mPenCircle->setPen(mcPen);
}

2941 2942 2943
void UBGraphicsScene::setToolCursor(int tool)
{
    if (tool == (int)UBStylusTool::Selector ||
2944 2945
            tool == (int)UBStylusTool::Text ||
            tool == (int)UBStylusTool::Play) {
2946
        deselectAllItems();
2947 2948
        hideMarkerCircle();
        hidePenCircle();
2949
    }
2950 2951 2952

    if (mCurrentStroke && mCurrentStroke->polygons().empty()){
        delete mCurrentStroke;
2953
        mCurrentStroke = NULL;
2954
    }
2955

2956 2957
}

2958 2959
void UBGraphicsScene::initStroke()
{
2960
    mCurrentStroke = new UBGraphicsStroke(this);
2961
}