timelabels.cpp 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
  Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  Copyright (c) 2007 Bruno Virlet <bruno@virlet.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/
#include "timelabels.h"
#include "agenda.h"
#include "prefs.h"
#include "timelabelszone.h"
#include "timescaleconfigdialog.h"

#include <KLocalizedString>

#include <QFrame>
Volker Krause's avatar
Volker Krause committed
33
#include <QIcon>
34 35 36 37 38 39
#include <QMenu>
#include <QPainter>
#include <QPointer>

using namespace EventViews;

Volker Krause's avatar
Volker Krause committed
40 41 42
TimeLabels::TimeLabels(const QTimeZone &zone, int rows, TimeLabelsZone *parent, Qt::WindowFlags f) :
    QFrame(parent, f),
    mTimezone(zone)
43 44 45 46 47 48 49 50 51 52 53 54 55 56
{
    mTimeLabelsZone = parent;
    mRows = rows;
    mMiniWidth = 0;

    mCellHeight = mTimeLabelsZone->preferences()->hourSize() * 4;

    setBackgroundRole(QPalette::Background);

    mMousePos = new QFrame(this);
    mMousePos->setLineWidth(1);
    mMousePos->setFrameStyle(QFrame::HLine | QFrame::Plain);
    mMousePos->setFixedSize(width(), 1);
    colorMousePos();
Laurent Montel's avatar
Laurent Montel committed
57
    mAgenda = nullptr;
58

Volker Krause's avatar
Volker Krause committed
59
    if (mTimezone.isValid()) {
60
        setToolTip(i18n("Timezone:") + i18n(mTimezone.id().constData()));
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 112 113
    }

    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);

    updateConfig();
}

void TimeLabels::mousePosChanged(const QPoint &pos)
{
    colorMousePos();
    mMousePos->move(0, pos.y());

    // The repaint somehow prevents that the red line leaves a black artifact when
    // moved down. It's not a full solution, though.
    repaint();
}

void TimeLabels::showMousePos()
{
    // touch screen have no mouse position
    mMousePos->show();
}

void TimeLabels::hideMousePos()
{
    mMousePos->hide();
}

void TimeLabels::colorMousePos()
{
    QPalette pal;
    pal.setColor(QPalette::Window,  // for Oxygen
                 mTimeLabelsZone->preferences()->agendaMarcusBainsLineLineColor());
    pal.setColor(QPalette::WindowText,  // for Plastique
                 mTimeLabelsZone->preferences()->agendaMarcusBainsLineLineColor());
    mMousePos->setPalette(pal);
}

void TimeLabels::setCellHeight(double height)
{
    if (mCellHeight != height) {
        mCellHeight = height;
        updateGeometry();
    }
}

QSize TimeLabels::minimumSizeHint() const
{
    QSize sh = QFrame::sizeHint();
    sh.setWidth(mMiniWidth);
    return sh;
}

114 115 116 117 118 119 120 121
static bool use12Clock()
{
    const QString str = QLocale().timeFormat();
    // 'A' or 'a' means am/pm is shown (and then 'h' uses 12-hour format)
    // but 'H' forces a 24-hour format anyway, even with am/pm shown.
    return str.contains(QLatin1Char('a'), Qt::CaseInsensitive) && !str.contains(QLatin1Char('H'));
}

122 123 124 125 126 127
/** updates widget's internal state */
void TimeLabels::updateConfig()
{
    setFont(mTimeLabelsZone->preferences()->agendaTimeLabelsFont());

    QString test = QStringLiteral("20");
128
    if (use12Clock()) {
129 130 131
        test = QStringLiteral("12");
    }
    mMiniWidth = fontMetrics().width(test);
132
    if (use12Clock()) {
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 176 177 178 179 180 181 182 183
        test = QStringLiteral("pm");
    } else {
        test = QStringLiteral("00");
    }
    QFont sFont = font();
    sFont.setPointSize(sFont.pointSize() / 2);
    QFontMetrics fmS(sFont);
    mMiniWidth += fmS.width(test) + frameWidth() * 2 + 4;

    /** Can happen if all resources are disabled */
    if (!mAgenda) {
        return;
    }

    // update HourSize
    mCellHeight = mTimeLabelsZone->preferences()->hourSize() * 4;
    // If the agenda is zoomed out so that more than 24 would be shown,
    // the agenda only shows 24 hours, so we need to take the cell height
    // from the agenda, which is larger than the configured one!
    if (mCellHeight < 4 * mAgenda->gridSpacingY()) {
        mCellHeight = 4 * mAgenda->gridSpacingY();
    }

    updateGeometry();

    repaint();
}

/**  */
void TimeLabels::setAgenda(Agenda *agenda)
{
    mAgenda = agenda;

    if (mAgenda) {
        connect(mAgenda, &Agenda::mousePosSignal, this, &TimeLabels::mousePosChanged);
        connect(mAgenda, &Agenda::enterAgenda, this, &TimeLabels::showMousePos);
        connect(mAgenda, &Agenda::leaveAgenda, this, &TimeLabels::hideMousePos);
        connect(mAgenda, &Agenda::gridSpacingYChanged, this, &TimeLabels::setCellHeight);
    }
}

/** This is called in response to repaint() */
void TimeLabels::paintEvent(QPaintEvent *)
{
    QPainter p(this);

    const int ch = height();

    // We won't paint parts that aren't visible
    const int cy = -y();// y() returns a negative value.

184
    const auto firstDay = QDateTime(mAgenda->dateList().first(), QTime(0,0,0), Qt::LocalTime).toUTC();
185
    const int beginning =
Volker Krause's avatar
Volker Krause committed
186
        !mTimezone.isValid() ?
187
        0 :
188 189
        (mTimezone.offsetFromUtc(firstDay) -
         mTimeLabelsZone->preferences()->timeZone().offsetFromUtc(firstDay)) / (60 * 60);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    // bug:  the parameters cx and cw are the areas that need to be
    //       redrawn, not the area of the widget.  unfortunately, this
    //       code assumes the latter...

    // now, for a workaround...
    const int cx = frameWidth() * 2;
    const int cw = width();
    // end of workaround

    int cell = static_cast<int>(cy / mCellHeight) + beginning;    // the hour we start drawing with
    double y = (cell - beginning) * mCellHeight;
    QFontMetrics fm = fontMetrics();
    QString hour;
    int timeHeight = fm.ascent();
    QFont hourFont = mTimeLabelsZone->preferences()->agendaTimeLabelsFont();
    p.setFont(font());

208
    //TODO: rewrite this using QTime's time formats. "am/pm" doesn't make sense
209 210
    // in some locale's
    QString suffix;
211
    if (!use12Clock()) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        suffix = QStringLiteral("00");
    } else {
        suffix = QStringLiteral("am");
        if (cell > 11) {
            suffix = QStringLiteral("pm");
        }
    }

    // We adjust the size of the hour font to keep it reasonable
    if (timeHeight > mCellHeight) {
        timeHeight = static_cast<int>(mCellHeight - 1);
        int pointS = hourFont.pointSize();
        while (pointS > 4) {   // TODO: use smallestReadableFont() when added to kdelibs
            hourFont.setPointSize(pointS);
            fm = QFontMetrics(hourFont);
            if (fm.ascent() < mCellHeight) {
                break;
            }
            --pointS;
        }
        fm = QFontMetrics(hourFont);
        timeHeight = fm.ascent();
    }
    //timeHeight -= (timeHeight/4-2);
    QFont suffixFont = hourFont;
    suffixFont.setPointSize(suffixFont.pointSize() / 2);
    QFontMetrics fmS(suffixFont);
    const int startW = cw - frameWidth() - 2;
    const int tw2 = fmS.width(suffix);
    const int divTimeHeight = (timeHeight - 1) / 2 - 1;
    //testline
    //p->drawLine(0,0,0,contentsHeight());
    while (y < cy + ch + mCellHeight) {
        QColor lineColor, textColor;
        textColor = palette().color(QPalette::WindowText);
        if (cell < 0 || cell >= 24) {
            textColor.setAlphaF(0.5);
        }
        lineColor = textColor;
        lineColor.setAlphaF(lineColor.alphaF() / 5.);
        p.setPen(lineColor);

        // hour, full line
        p.drawLine(cx, int(y), cw + 2, int(y));

        hour.setNum(cell % 24);
        // handle different timezones
        if (cell < 0) {
            hour.setNum(cell + 24);
        }
        // handle 24h and am/pm time formats
263
        if (use12Clock()) {
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
            if (cell == 12) {
                suffix = QStringLiteral("pm");
            }
            if (cell == 0) {
                hour.setNum(12);
            }
            if (cell > 12) {
                hour.setNum(cell - 12);
            }
        }

        // draw the time label
        p.setPen(textColor);
        const int timeWidth = fm.width(hour);
        int offset = startW - timeWidth - tw2 - 1;
        p.setFont(hourFont);
        p.drawText(offset, static_cast<int>(y + timeHeight), hour);
        p.setFont(suffixFont);
        offset = startW - tw2;
        p.drawText(offset, static_cast<int>(y + timeHeight - divTimeHeight), suffix);

        // increment indices
        y += mCellHeight;
        cell++;
    }
}

QSize TimeLabels::sizeHint() const
{
    return QSize(mMiniWidth, mRows * mCellHeight);
}

void TimeLabels::contextMenuEvent(QContextMenuEvent *event)
{
    Q_UNUSED(event);

    QMenu popup(this);
    QAction *editTimeZones =
        popup.addAction(QIcon::fromTheme(QStringLiteral("document-properties")), i18n("&Add Timezones..."));
    QAction *removeTimeZone =
        popup.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")),
305
                        i18n("&Remove Timezone %1", i18n(mTimezone.id().constData())));
Volker Krause's avatar
Volker Krause committed
306
    if (!mTimezone.isValid() ||
307
            !mTimeLabelsZone->preferences()->timeScaleTimezones().count() ||
Volker Krause's avatar
Volker Krause committed
308
            mTimezone == mTimeLabelsZone->preferences()->timeZone()) {
309 310 311 312 313 314 315 316 317 318 319 320 321
        removeTimeZone->setEnabled(false);
    }

    QAction *activatedAction = popup.exec(QCursor::pos());
    if (activatedAction == editTimeZones) {
        QPointer<TimeScaleConfigDialog> dialog =
            new TimeScaleConfigDialog(mTimeLabelsZone->preferences(), this);
        if (dialog->exec() == QDialog::Accepted) {
            mTimeLabelsZone->reset();
        }
        delete dialog;
    } else if (activatedAction == removeTimeZone) {
        QStringList list = mTimeLabelsZone->preferences()->timeScaleTimezones();
Volker Krause's avatar
Volker Krause committed
322
        list.removeAll(QString::fromUtf8(mTimezone.id()));
323 324 325 326 327 328 329 330
        mTimeLabelsZone->preferences()->setTimeScaleTimezones(list);
        mTimeLabelsZone->preferences()->writeConfig();
        mTimeLabelsZone->reset();
        hide();
        deleteLater();
    }
}

Volker Krause's avatar
Volker Krause committed
331
QTimeZone TimeLabels::timeZone() const
332
{
Volker Krause's avatar
Volker Krause committed
333
    return mTimezone;
334 335 336 337
}

QString TimeLabels::header() const
{
338
    return i18n(mTimezone.id().constData());
339 340 341 342 343 344
}

QString TimeLabels::headerToolTip() const
{
    QString toolTip;
    toolTip += QLatin1String("<qt>");
345
    toolTip += i18n("<b>%1</b>", i18n(mTimezone.id().constData()));
346 347
    toolTip += QLatin1String("<hr>");
    //TODO: Once string freeze is lifted, add UTC offset here
Volker Krause's avatar
Volker Krause committed
348 349
    if (mTimezone.country() != QLocale::AnyCountry) {
        toolTip += i18n("<i>Country:</i> %1", QLocale::countryToString(mTimezone.country()));
350 351
        toolTip += QLatin1String("<br/>");
    }
Volker Krause's avatar
Volker Krause committed
352 353 354 355 356 357 358 359 360 361

    auto abbreviations = QStringLiteral("&nbsp;");
    foreach (const auto &transition, mTimezone.transitions(QDateTime::currentDateTime(), QDateTime::currentDateTime().addYears(1))) {
        abbreviations += transition.abbreviation;
        abbreviations += QLatin1String(",&nbsp;");
    }
    abbreviations.chop(7);
    if (!abbreviations.isEmpty()) {
        toolTip += i18n("<i>Abbreviations:</i>");
        toolTip += abbreviations;
362 363
        toolTip += QLatin1String("<br/>");
    }
Volker Krause's avatar
Volker Krause committed
364 365
    if (!mTimezone.comment().isEmpty()) {
        toolTip += i18n("<i>Comment:</i> %1", mTimezone.comment());
366 367 368 369 370 371
    }
    toolTip += QLatin1String("</qt>");

    return toolTip;
}