monthscene.cpp 23.4 KB
Newer Older
1
/*
2
  SPDX-FileCopyrightText: 2008 Bruno Virlet <bruno.virlet@gmail.com>
3

4
  SPDX-License-Identifier: GPL-2.0-or-later WITH Qt-Commercial-exception-1.0
5 6 7 8 9 10
*/

#include "monthscene.h"
#include "monthgraphicsitems.h"
#include "monthitem.h"
#include "monthview.h"
11
#include "helper.h"
12
#include "prefs.h"
13

14 15 16 17 18 19 20 21 22 23 24 25 26
#include <CalendarSupport/Utils>

#include <QGraphicsSceneMouseEvent>
#include <QResizeEvent>
#include <KLocalizedString>
#include <QToolTip>
#include <QIcon>

static const int AUTO_REPEAT_DELAY = 600;

using namespace EventViews;

MonthScene::MonthScene(MonthView *parent)
Laurent Montel's avatar
Laurent Montel committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    : QGraphicsScene(parent)
    , mMonthView(parent)
    , mInitialized(false)
    , mClickedItem(nullptr)
    , mActionItem(nullptr)
    , mActionInitiated(false)
    , mSelectedItem(nullptr)
    , mStartCell(nullptr)
    , mPreviousCell(nullptr)
    , mActionType(None)
    , mStartHeight(0)
    , mCurrentIndicator(nullptr)
{
    mBirthdayPixmap = QIcon::fromTheme(QStringLiteral("view-calendar-birthday")).pixmap(16, 16);
    mAnniversaryPixmap
        = QIcon::fromTheme(QStringLiteral("view-calendar-wedding-anniversary")).pixmap(16, 16);
    mAlarmPixmap = QIcon::fromTheme(QStringLiteral("appointment-reminder")).pixmap(16, 16);
    mRecurPixmap = QIcon::fromTheme(QStringLiteral("appointment-recurring")).pixmap(16, 16);
    mReadonlyPixmap = QIcon::fromTheme(QStringLiteral("object-locked")).pixmap(16, 16);
    mReplyPixmap = QIcon::fromTheme(QStringLiteral("mail-reply-sender")).pixmap(16, 16);
    mHolidayPixmap = QIcon::fromTheme(QStringLiteral("view-calendar-holiday")).pixmap(16, 16);
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

    setSceneRect(0, 0, parent->width(), parent->height());
}

MonthScene::~MonthScene()
{
    qDeleteAll(mMonthCellMap);
    qDeleteAll(mManagerList);
}

MonthCell *MonthScene::selectedCell() const
{
    return mMonthCellMap.value(mSelectedCellDate);
}

MonthCell *MonthScene::previousCell() const
{
    return mPreviousCell;
}

Laurent Montel's avatar
Laurent Montel committed
68
int MonthScene::getRightSpan(QDate date) const
69 70 71 72 73 74 75 76 77
{
    MonthCell *cell = mMonthCellMap.value(date);
    if (!cell) {
        return 0;
    }

    return 7 - cell->x() - 1;
}

Laurent Montel's avatar
Laurent Montel committed
78
int MonthScene::getLeftSpan(QDate date) const
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
{
    MonthCell *cell = mMonthCellMap.value(date);
    if (!cell) {
        return 0;
    }

    return cell->x();
}

int MonthScene::maxRowCount()
{
    return (rowHeight() - MonthCell::topMargin()) / itemHeightIncludingSpacing();
}

int MonthScene::itemHeightIncludingSpacing()
{
    return MonthCell::topMargin() + 2;
}

int MonthScene::itemHeight()
{
    return MonthCell::topMargin();
}

MonthCell *MonthScene::firstCellForMonthItem(MonthItem *manager)
{
    for (QDate d = manager->startDate(); d <= manager->endDate(); d = d.addDays(1)) {
        MonthCell *monthCell = mMonthCellMap.value(d);
        if (monthCell) {
            return monthCell;
        }
    }

Laurent Montel's avatar
Laurent Montel committed
112
    return nullptr;
113 114 115 116
}

void MonthScene::updateGeometry()
{
Laurent Montel's avatar
Laurent Montel committed
117
    for (MonthItem *manager : qAsConst(mManagerList)) {
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
        manager->updateGeometry();
    }
}

int MonthScene::availableWidth() const
{
    return static_cast<int>(sceneRect().width());
}

int MonthScene::availableHeight() const
{
    return static_cast<int>(sceneRect().height() - headerHeight());
}

int MonthScene::columnWidth() const
{
    return static_cast<int>((availableWidth() - 1) / 7.);
}

int MonthScene::rowHeight() const
{
    return static_cast<int>((availableHeight() - 1) / 6.);
}

int MonthScene::headerHeight() const
{
    return 50;
}

int MonthScene::cellVerticalPos(const MonthCell *cell) const
{
    return headerHeight() + cell->y() * rowHeight();
}

int MonthScene::cellHorizontalPos(const MonthCell *cell) const
{
    return cell->x() * columnWidth();
}

int MonthScene::sceneYToMonthGridY(int yScene)
{
    return yScene - headerHeight();
}

int MonthScene::sceneXToMonthGridX(int xScene)
{
    return xScene;
}

void MonthGraphicsView::drawBackground(QPainter *p, const QRectF &rect)
{
    Q_ASSERT(mScene);
    PrefsPtr prefs = mScene->monthView()->preferences();
    p->setFont(prefs->monthViewFont());
172
    p->fillRect(rect, palette().color(QPalette::Window));
173 174 175 176 177 178 179 180 181

    /*
      Headers
    */
    QFont font = prefs->monthViewFont();
    font.setBold(true);
    font.setPointSize(15);
    p->setFont(font);
    const int dayLabelsHeight = 20;
Laurent Montel's avatar
Laurent Montel committed
182
    p->drawText(QRect(0, 0,    // top right
183 184 185
                      static_cast<int>(mScene->sceneRect().width()),
                      static_cast<int>(mScene->headerHeight() - dayLabelsHeight)),
                Qt::AlignCenter,
186
                mMonthView->averageDate().toString(QStringLiteral("MMMM yyyy")));
187 188 189 190 191 192 193 194

    font.setPointSize(dayLabelsHeight - 10);
    p->setFont(font);

    const QDate start = mMonthView->actualStartDateTime().date();
    const QDate end = mMonthView->actualEndDateTime().date();

    for (QDate d = start;
Laurent Montel's avatar
Laurent Montel committed
195
         d <= start.addDays(6); d = d.addDays(1)) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        MonthCell *cell = mScene->mMonthCellMap.value(d);

        if (!cell) {
            // This means drawBackground() is being called before reloadIncidences(). Can happen with some
            // themes. Bug  #190191
            return;
        }

        p->drawText(QRect(mScene->cellHorizontalPos(cell),
                          mScene->cellVerticalPos(cell) - 15,
                          mScene->columnWidth(),
                          15),
                    Qt::AlignCenter,
                    QLocale::system().dayName(d.dayOfWeek(), QLocale::LongFormat));
    }

    /*
      Month grid
    */
    int columnWidth = mScene->columnWidth();
    int rowHeight = mScene->rowHeight();

Laurent Montel's avatar
Laurent Montel committed
218 219 220
    const QList<QDate> workDays = CalendarSupport::workDays(
        mMonthView->actualStartDateTime().date(),
        mMonthView->actualEndDateTime().date());
221 222 223 224 225 226 227 228 229 230 231

    for (QDate d = start; d <= end; d = d.addDays(1)) {
        if (!mScene->mMonthCellMap.contains(d)) {
            // This means drawBackground() is being called before reloadIncidences(). Can happen with some
            // themes. Bug  #190191
            return;
        }

        MonthCell *cell = mScene->mMonthCellMap[ d ];

        QColor color;
232 233 234 235 236 237
        if (!mMonthView->preferences()->useSystemColor()) {
            if (workDays.contains(d)) {
                color = mMonthView->preferences()->monthGridWorkHoursBackgroundColor();
            } else {
                color = mMonthView->preferences()->monthGridBackgroundColor();
            }
238
        } else {
239 240 241 242 243
            if (workDays.contains(d)) {
                color = palette().color(QPalette::Base);
            } else {
                color = palette().color(QPalette::AlternateBase);
            }
244
        }
245
        const bool usingDark = EventViews::isColorDark(color);
246
        if (cell == mScene->selectedCell()) {
247
            color = (usingDark) ? color.lighter(150) : color.darker(115);
248 249
        }
        if (cell->date() == QDate::currentDate()) {
250
            color = (usingDark) ? color.lighter(200) : color.darker(140);
251 252 253
        }

        // Draw cell
254
        p->setPen(mMonthView->preferences()->monthGridBackgroundColor().darker(150));
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        p->setBrush(color);
        p->drawRect(QRect(mScene->cellHorizontalPos(cell), mScene->cellVerticalPos(cell),
                          columnWidth, rowHeight));

        if (mMonthView->isBusyDay(d)) {
            QColor busyColor = mMonthView->preferences()->viewBgBusyColor();
            busyColor.setAlpha(EventViews::BUSY_BACKGROUND_ALPHA);
            p->setBrush(busyColor);
            p->drawRect(QRect(mScene->cellHorizontalPos(cell), mScene->cellVerticalPos(cell),
                              columnWidth, rowHeight));
        }

        // Draw cell header
        int cellHeaderX = mScene->cellHorizontalPos(cell) + 1;
        int cellHeaderY = mScene->cellVerticalPos(cell) + 1;
        int cellHeaderWidth = columnWidth - 2;
        int cellHeaderHeight = cell->topMargin() - 2;
        QLinearGradient bgGradient(QPointF(cellHeaderX, cellHeaderY),
                                   QPointF(cellHeaderX + cellHeaderWidth,
                                           cellHeaderY + cellHeaderHeight));
275 276
        // Compute color of grid lines based on dark/lightness
        if (!usingDark) {
277 278 279 280
            p->setBrush(color.darker(110));
        } else {
            p->setBrush(color.lighter(140));
        }
281

282 283 284 285 286 287 288 289
        bgGradient.setColorAt(1, color);

        p->setPen(Qt::NoPen);
        p->drawRect(QRect(cellHeaderX, cellHeaderY,
                          cellHeaderWidth, cellHeaderHeight));
    }

    font = mMonthView->preferences()->monthViewFont();
290
    font.setPixelSize(MonthCell::topMargin() - 4);
291 292 293

    p->setFont(font);

294 295 296 297 298 299
    QPen oldPen;
    if (!mMonthView->preferences()->useSystemColor()) {
        oldPen = mMonthView->preferences()->monthGridBackgroundColor().darker(150);
    } else {
        oldPen = palette().color(QPalette::WindowText).darker(150);
    }
300

301 302
    // Draw dates
    for (QDate d = mMonthView->actualStartDateTime().date();
Laurent Montel's avatar
Laurent Montel committed
303
         d <= mMonthView->actualEndDateTime().date(); d = d.addDays(1)) {
304 305 306 307 308 309 310 311 312 313 314
        MonthCell *cell = mScene->mMonthCellMap.value(d);

        QFont font = p->font();
        if (cell->date() == QDate::currentDate()) {
            font.setBold(true);
        } else {
            font.setBold(false);
        }
        p->setFont(font);

        if (d.month() == mMonthView->currentMonth()) {
315
            p->setPen(palette().color(QPalette::WindowText));
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        } else {
            p->setPen(oldPen);
        }

        /*
          Draw arrows if all items won't fit
        */

        // Up arrow if first item is above cell top
        if (mScene->startHeight() != 0 && cell->hasEventBelow(mScene->startHeight())) {
            cell->upArrow()->setPos(
                mScene->cellHorizontalPos(cell) + columnWidth / 2,
                mScene->cellVerticalPos(cell) + cell->upArrow()->boundingRect().height() / 2 + 2);
            cell->upArrow()->show();
        } else {
            cell->upArrow()->hide();
        }

        // Down arrow if last item is below cell bottom
        if (!mScene->lastItemFit(cell)) {
            cell->downArrow()->setPos(
                mScene->cellHorizontalPos(cell) + columnWidth / 2,
Laurent Montel's avatar
Laurent Montel committed
338 339
                mScene->cellVerticalPos(cell) + rowHeight
                -cell->downArrow()->boundingRect().height() / 2 - 2);
340 341 342 343 344 345 346
            cell->downArrow()->show();
        } else {
            cell->downArrow()->hide();
        }

        QString dayText;
        // Prepend month name if d is the first or last day of month
347 348
        if (d.day() == 1 ||             // d is the first day of month
            d.addDays(1).day() == 1) {  // d is the last day of month
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
            dayText = i18nc("'Month day' for month view cells", "%1 %2",
                            QLocale::system().monthName(d.month(), QLocale::ShortFormat),
                            d.day());
        } else {
            dayText = QString::number(d.day());
        }

        p->drawText(QRect(mScene->cellHorizontalPos(cell),     // top right
                          mScene->cellVerticalPos(cell),       // of the cell
                          mScene->columnWidth() - 2,
                          cell->topMargin()),
                    Qt::AlignRight,
                    dayText);
    }

    // ...
}

void MonthScene::resetAll()
{
    qDeleteAll(mMonthCellMap);
    mMonthCellMap.clear();

    qDeleteAll(mManagerList);
    mManagerList.clear();

Laurent Montel's avatar
Laurent Montel committed
375 376 377
    mSelectedItem = nullptr;
    mActionItem = nullptr;
    mClickedItem = nullptr;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
}

Akonadi::IncidenceChanger *MonthScene::incidenceChanger() const
{
    return mMonthView->changer();
}

QDate MonthScene::firstDateOnRow(int row) const
{
    return mMonthView->actualStartDateTime().date().addDays(7 * row);
}

bool MonthScene::lastItemFit(MonthCell *cell)
{
    if (cell->firstFreeSpace() > maxRowCount() + startHeight()) {
        return false;
    } else {
        return true;
    }
}

int MonthScene::totalHeight()
{
    int max = 0;
    for (QDate d = mMonthView->actualStartDateTime().date();
Laurent Montel's avatar
Laurent Montel committed
403
         d <= mMonthView->actualEndDateTime().date(); d = d.addDays(1)) {
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        int c = mMonthCellMap[ d ]->firstFreeSpace();
        if (c > max) {
            max = c;
        }
    }

    return max;
}

void MonthScene::wheelEvent(QGraphicsSceneWheelEvent *event)
{
    Q_UNUSED(event);   // until we figure out what to do in here

    /*  int numDegrees = -event->delta() / 8;
      int numSteps = numDegrees / 15;

      if (startHeight() + numSteps < 0) {
        numSteps = -startHeight();
      }

      int cellHeight = 0;

      MonthCell *currentCell = getCellFromPos(event->scenePos());
      if (currentCell) {
        cellHeight = currentCell->firstFreeSpace();
      }
      if (cellHeight == 0) {
        // no items in this cell, there's no point to scroll
        return;
      }

      int newHeight;
      int maxStartHeight = qMax(0, cellHeight - maxRowCount());
      if (numSteps > 0  && startHeight() + numSteps >= maxStartHeight) {
        newHeight = maxStartHeight;
      } else {
        newHeight = startHeight() + numSteps;
      }

      if (newHeight == startHeight()) {
        return;
      }

      setStartHeight(newHeight);

      foreach (MonthItem *manager, mManagerList) {
        manager->updateGeometry();
      }

      invalidate(QRectF(), BackgroundLayer);

      event->accept();
    */
}

void MonthScene::scrollCellsDown()
{
    int newHeight = startHeight() + 1;
    setStartHeight(newHeight);

Laurent Montel's avatar
Laurent Montel committed
464
    for (MonthItem *manager : qAsConst(mManagerList)) {
465 466 467 468 469 470 471 472 473 474 475
        manager->updateGeometry();
    }

    invalidate(QRectF(), BackgroundLayer);
}

void MonthScene::scrollCellsUp()
{
    int newHeight = startHeight() - 1;
    setStartHeight(newHeight);

Laurent Montel's avatar
Laurent Montel committed
476
    for (MonthItem *manager : qAsConst(mManagerList)) {
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        manager->updateGeometry();
    }

    invalidate(QRectF(), BackgroundLayer);
}

void MonthScene::clickOnScrollIndicator(ScrollIndicator *scrollItem)
{
    if (scrollItem->direction() == ScrollIndicator::UpArrow) {
        scrollCellsUp();
    } else if (scrollItem->direction() == ScrollIndicator::DownArrow) {
        scrollCellsDown();
    }
}

void MonthScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    QPointF pos = mouseEvent->scenePos();
    repeatTimer.stop();
496
    MonthGraphicsItem *iItem = dynamic_cast<MonthGraphicsItem *>(itemAt(pos, {}));
497 498
    if (iItem) {
        if (iItem->monthItem()) {
Laurent Montel's avatar
Laurent Montel committed
499
            auto *tmp = qobject_cast<IncidenceMonthItem *>(iItem->monthItem());
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
            if (tmp) {
                selectItem(iItem->monthItem());
                mMonthView->defaultAction(tmp->akonadiItem());

                mouseEvent->accept();
            }
        }
    } else {
        Q_EMIT newEventSignal();
    }
}

void MonthScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    QPointF pos = mouseEvent->scenePos();

    MonthGraphicsView *view = static_cast<MonthGraphicsView *>(views().at(0));

    // Change cursor depending on the part of the item it hovers to inform
    // the user that he can resize the item.
    if (mActionType == None) {
521
        MonthGraphicsItem *iItem = dynamic_cast<MonthGraphicsItem *>(itemAt(pos, {}));
522
        if (iItem) {
523 524
            if (iItem->monthItem()->isResizable() &&
                iItem->isBeginItem() && iItem->mapFromScene(pos).x() <= 10) {
525
                view->setActionCursor(Resize);
526 527 528
            } else if (iItem->monthItem()->isResizable() &&
                       iItem->isEndItem() &&
                       iItem->mapFromScene(pos).x() >= iItem->boundingRect().width() - 10) {
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
                view->setActionCursor(Resize);
            } else {
                view->setActionCursor(None);
            }
        } else {
            view->setActionCursor(None);
        }
        mouseEvent->accept();
        return;
    }

    // If an item was selected during the click, we maybe have an item to move !
    if (mActionItem) {
        MonthCell *currentCell = getCellFromPos(pos);

        // Initiate action if not already done
        if (!mActionInitiated && mActionType != None) {
            if (mActionType == Move) {
                mActionItem->beginMove();
            } else if (mActionType == Resize) {
                mActionItem->beginResize();
            }
            mActionInitiated = true;
        }
        view->setActionCursor(mActionType);

        // Move or resize action
        if (currentCell && currentCell != mPreviousCell) {
            bool ok = true;
            if (mActionType == Move) {
                mActionItem->moveBy(mPreviousCell->date().daysTo(currentCell->date()));
            } else if (mActionType == Resize) {
                ok = mActionItem->resizeBy(mPreviousCell->date().daysTo(currentCell->date()));
            }

            if (ok) {
                mPreviousCell = currentCell;
            }
            mActionItem->updateGeometry();
            update();
        }
        mouseEvent->accept();
    }
}

void MonthScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    QPointF pos = mouseEvent->scenePos();

Laurent Montel's avatar
Laurent Montel committed
578 579
    mClickedItem = nullptr;
    mCurrentIndicator = nullptr;
580

581
    MonthGraphicsItem *iItem = dynamic_cast<MonthGraphicsItem *>(itemAt(pos, {}));
582 583 584 585 586
    if (iItem) {
        mClickedItem = iItem->monthItem();

        selectItem(mClickedItem);
        if (mouseEvent->button() == Qt::RightButton) {
Laurent Montel's avatar
Laurent Montel committed
587
            auto *tmp = qobject_cast<IncidenceMonthItem *>(mClickedItem);
588 589 590 591 592 593 594 595 596 597 598 599 600
            if (tmp) {
                Q_EMIT showIncidencePopupSignal(tmp->akonadiItem(), tmp->realStartDate());
            }
        }

        if (mouseEvent->button() == Qt::LeftButton) {
            // Basic initialization for resize and move
            mActionItem = mClickedItem;
            mStartCell = getCellFromPos(pos);
            mPreviousCell = mStartCell;
            mActionInitiated = false;

            // Move or resize ?
601 602
            if (iItem->monthItem()->isResizable() &&
                iItem->isBeginItem() && iItem->mapFromScene(pos).x() <= 10) {
603 604
                mActionType = Resize;
                mResizeType = ResizeLeft;
605 606 607
            } else if (iItem->monthItem()->isResizable() &&
                       iItem->isEndItem() &&
                       iItem->mapFromScene(pos).x() >= iItem->boundingRect().width() - 10) {
608 609 610 611 612 613 614
                mActionType = Resize;
                mResizeType = ResizeRight;
            } else if (iItem->monthItem()->isMoveable()) {
                mActionType = Move;
            }
        }
        mouseEvent->accept();
615
    } else if (ScrollIndicator *scrollItem = dynamic_cast<ScrollIndicator *>(itemAt(pos, {}))) {
616 617 618 619 620
        clickOnScrollIndicator(scrollItem);
        mCurrentIndicator = scrollItem;
        repeatTimer.start(AUTO_REPEAT_DELAY, this);
    } else {
        // unselect items when clicking somewhere else
Laurent Montel's avatar
Laurent Montel committed
621
        selectItem(nullptr);
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

        MonthCell *cell = getCellFromPos(pos);
        if (cell) {
            mSelectedCellDate = cell->date();
            update();
            if (mouseEvent->button() == Qt::RightButton) {
                Q_EMIT showNewEventPopupSignal();
            }
            mouseEvent->accept();
        }
    }
}

void MonthScene::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == repeatTimer.timerId()) {
        if (mCurrentIndicator->isVisible()) {
            clickOnScrollIndicator(mCurrentIndicator);
            repeatTimer.start(AUTO_REPEAT_DELAY, this);
        } else {
Laurent Montel's avatar
Laurent Montel committed
642
            mCurrentIndicator = nullptr;
643 644 645 646 647 648 649 650 651
            repeatTimer.stop();
        }
    }
}

void MonthScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
    // Find the first item that does tooltips
    const QPointF pos = helpEvent->scenePos();
652
    MonthGraphicsItem *toolTipItem = dynamic_cast<MonthGraphicsItem *>(itemAt(pos, {}));
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

    // Show or hide the tooltip
    QString text;
    QPoint point;
    if (toolTipItem) {
        text = toolTipItem->getToolTip();
        point = helpEvent->screenPos();
    }
    QToolTip::showText(point, text, helpEvent->widget());
    helpEvent->setAccepted(!text.isEmpty());
}

void MonthScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    QPointF pos = mouseEvent->scenePos();

    static_cast<MonthGraphicsView *>(views().at(0))->setActionCursor(None);

    repeatTimer.stop();
Laurent Montel's avatar
Laurent Montel committed
672
    mCurrentIndicator = nullptr;
673 674 675 676 677 678 679 680 681 682 683 684 685 686

    if (mActionItem) {
        MonthCell *currentCell = getCellFromPos(pos);

        const bool somethingChanged = currentCell && currentCell != mStartCell;

        if (somethingChanged) {   // We want to act if a move really happened
            if (mActionType == Resize) {
                mActionItem->endResize();
            } else if (mActionType == Move) {
                mActionItem->endMove();
            }
        }

Laurent Montel's avatar
Laurent Montel committed
687
        mActionItem = nullptr;
688
        mActionType = None;
Laurent Montel's avatar
Laurent Montel committed
689
        mStartCell = nullptr;
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

        mouseEvent->accept();
    }
}

// returns true if the point is in the monthgrid (allows to avoid selecting a cell when
// a click is outside the month grid
bool MonthScene::isInMonthGrid(int x, int y) const
{
    return x >= 0 && y >= 0 && x <= availableWidth() && y <= availableHeight();
}

// The function converts the coordinates to the month grid coordinates to
// be able to locate the cell.
MonthCell *MonthScene::getCellFromPos(const QPointF &pos)
{
    int y = sceneYToMonthGridY(static_cast<int>(pos.y()));
    int x = sceneXToMonthGridX(static_cast<int>(pos.x()));
    if (!isInMonthGrid(x, y)) {
Laurent Montel's avatar
Laurent Montel committed
709
        return nullptr;
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    }
    int id = (int)(y / rowHeight()) * 7 + (int)(x / columnWidth());

    return mMonthCellMap.value(mMonthView->actualStartDateTime().date().addDays(id));
}

void MonthScene::selectItem(MonthItem *item)
{
    /*
      if (mSelectedItem == item) {
        return;
      }

      I commented the above code so it's possible to selected a selected item.
      korg-mobile needs that, otherwise clicking on a selected item wont bring the editor up.
      Another solution would be to have two Q_SIGNALS: incidenceSelected() and incidenceClicked()
    */

Laurent Montel's avatar
Laurent Montel committed
728
    auto *tmp = qobject_cast<IncidenceMonthItem *>(item);
729 730

    if (!tmp) {
Laurent Montel's avatar
Laurent Montel committed
731
        mSelectedItem = nullptr;
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        Q_EMIT incidenceSelected(Akonadi::Item(), QDate());
        return;
    }

    mSelectedItem = item;
    Q_ASSERT(CalendarSupport::hasIncidence(tmp->akonadiItem()));

    if (mMonthView->selectedIncidenceDates().isEmpty()) {
        Q_EMIT incidenceSelected(tmp->akonadiItem(), QDate());
    } else {
        Q_EMIT incidenceSelected(tmp->akonadiItem(), mMonthView->selectedIncidenceDates().at(0));
    }
    update();
}

void MonthScene::removeIncidence(const QString &uid)
{
Laurent Montel's avatar
Laurent Montel committed
749
    for (MonthItem *manager : qAsConst(mManagerList)) {
Laurent Montel's avatar
Laurent Montel committed
750
        auto *imi = qobject_cast<IncidenceMonthItem *>(manager);
751 752 753 754
        if (!imi) {
            continue;
        }

755
        KCalendarCore::Incidence::Ptr incidence = imi->incidence();
756 757 758 759
        if (!incidence) {
            continue;
        }
        if (incidence->uid() == uid) {
760 761
            const auto lst = imi->monthGraphicsItems();
            for (MonthGraphicsItem *gitem : lst) {
762 763 764 765 766 767 768 769
                removeItem(gitem);
            }
        }
    }
}

//----------------------------------------------------------
MonthGraphicsView::MonthGraphicsView(MonthView *parent)
Laurent Montel's avatar
Laurent Montel committed
770 771
    : QGraphicsView(parent)
    , mMonthView(parent)
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
{
    setMouseTracking(true);
}

void MonthGraphicsView::setActionCursor(MonthScene::ActionType actionType)
{
    switch (actionType) {
    case MonthScene::Move:
#ifndef QT_NO_CURSOR
        setCursor(Qt::ArrowCursor);
#endif
        break;
    case MonthScene::Resize:
#ifndef QT_NO_CURSOR
        setCursor(Qt::SizeHorCursor);
#endif
        break;
#ifndef QT_NO_CURSOR
    default:
        setCursor(Qt::ArrowCursor);
#endif
    }
}

void MonthGraphicsView::setScene(MonthScene *scene)
{
    mScene = scene;
    QGraphicsView::setScene(scene);
}

void MonthGraphicsView::resizeEvent(QResizeEvent *event)
{
    mScene->setSceneRect(0, 0, event->size().width(), event->size().height());
    mScene->updateGeometry();
}