timelabels.cpp 13.1 KB
Newer Older
1
/*
2
3
4
5
6
  SPDX-FileCopyrightText: 2001 Cornelius Schumacher <schumacher@kde.org>
  SPDX-FileCopyrightText: 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  SPDX-FileCopyrightText: 2007 Bruno Virlet <bruno@virlet.org>

  SPDX-License-Identifier: GPL-2.0-or-later WITH Qt-Commercial-exception-1.0
7
8
9
10
11
12
13
*/
#include "timelabels.h"
#include "agenda.h"
#include "prefs.h"
#include "timelabelszone.h"
#include "timescaleconfigdialog.h"

14
15
#include <KCalUtils/Stringify>

16
17
#include <KLocalizedString>

18
#include <QHelpEvent>
Volker Krause's avatar
Volker Krause committed
19
#include <QIcon>
20
21
22
#include <QMenu>
#include <QPainter>
#include <QPointer>
23
#include <QToolTip>
24
25
26

using namespace EventViews;

Laurent Montel's avatar
Laurent Montel committed
27
28
29
TimeLabels::TimeLabels(const QTimeZone &zone, int rows, TimeLabelsZone *parent, Qt::WindowFlags f)
    : QFrame(parent, f)
    , mTimezone(zone)
30
31
32
33
34
35
36
{
    mTimeLabelsZone = parent;
    mRows = rows;
    mMiniWidth = 0;

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

37
    setBackgroundRole(QPalette::Window);
38
39
40
41
42
43

    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
44
    mAgenda = nullptr;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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

    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;
}

97
98
99
100
101
102
103
104
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'));
}

105
106
107
108
109
110
/** updates widget's internal state */
void TimeLabels::updateConfig()
{
    setFont(mTimeLabelsZone->preferences()->agendaTimeLabelsFont());

    QString test = QStringLiteral("20");
111
    if (use12Clock()) {
112
113
        test = QStringLiteral("12");
    }
Laurent Montel's avatar
Laurent Montel committed
114
    mMiniWidth = fontMetrics().boundingRect(test).width();
115
    if (use12Clock()) {
116
117
118
119
120
121
122
        test = QStringLiteral("pm");
    } else {
        test = QStringLiteral("00");
    }
    QFont sFont = font();
    sFont.setPointSize(sFont.pointSize() / 2);
    QFontMetrics fmS(sFont);
Laurent Montel's avatar
Laurent Montel committed
123
    mMiniWidth += fmS.boundingRect(test).width() + frameWidth() * 2 + 4;
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

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

157
158
int TimeLabels::yposToCell(const int ypos) const
{
159
    const KCalendarCore::DateList datelist = mAgenda->dateList();
Laurent Montel's avatar
Laurent Montel committed
160
    if (datelist.isEmpty()) {
161
        return 0;
Laurent Montel's avatar
Laurent Montel committed
162
    }
163
164

    const auto firstDay = QDateTime(datelist.first(), QTime(0, 0, 0), Qt::LocalTime).toUTC();
Laurent Montel's avatar
Laurent Montel committed
165
166
167
168
169
    const int beginning   // the hour we start drawing with
        = !mTimezone.isValid()
          ? 0
          : (mTimezone.offsetFromUtc(firstDay)
             -mTimeLabelsZone->preferences()->timeZone().offsetFromUtc(firstDay)) / 3600;
170

171
172
173
174
175
176
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
    return static_cast<int>(ypos / mCellHeight) + beginning;
}

int TimeLabels::cellToHour(const int cell) const
{
    int tCell = cell % 24;
    // handle different timezones
    if (tCell < 0) {
        tCell += 24;
    }
    // handle 24h and am/pm time formats
    if (use12Clock()) {
        if (tCell == 0) {
            tCell = 12;
        }
        if (tCell < 0) {
            tCell += 24;
        }
        if (tCell > 12) {
            tCell %= 12;
            if (tCell == 0) {
                tCell = 12;
            }
        }
    }
    return tCell;
}

QString TimeLabels::cellToSuffix(const int cell) const
{
    //TODO: rewrite this using QTime's time formats. "am/pm" doesn't make sense
    // in some locale's
    QString suffix;
    if (use12Clock()) {
        if ((cell / 12) % 2 != 0) {
            suffix = QStringLiteral("pm");
        } else {
            suffix = QStringLiteral("am");
        }
    } else {
        suffix = QStringLiteral("00");
    }
    return suffix;
}

216
217
218
/** This is called in response to repaint() */
void TimeLabels::paintEvent(QPaintEvent *)
{
219
220
221
    if (!mAgenda) {
        return;
    }
222
    const KCalendarCore::DateList datelist = mAgenda->dateList();
Laurent Montel's avatar
Laurent Montel committed
223
    if (datelist.isEmpty()) {
224
        return;
Laurent Montel's avatar
Laurent Montel committed
225
    }
226

227
228
229
230
231
    QPainter p(this);

    const int ch = height();

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

234
    const auto firstDay = QDateTime(datelist.first(), QTime(0, 0, 0), Qt::LocalTime).toUTC();
Laurent Montel's avatar
Laurent Montel committed
235
236
237
238
239
    const int beginning
        = !mTimezone.isValid()
          ? 0
          : (mTimezone.offsetFromUtc(firstDay)
             -mTimeLabelsZone->preferences()->timeZone().offsetFromUtc(firstDay)) / 3600;
240
241
242
243
244
245
246
247
248
249

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

250
    int cell = yposToCell(cy);
251
252
253
254
255
256
257
    double y = (cell - beginning) * mCellHeight;
    QFontMetrics fm = fontMetrics();
    QString hour;
    int timeHeight = fm.ascent();
    QFont hourFont = mTimeLabelsZone->preferences()->agendaTimeLabelsFont();
    p.setFont(font());

258
    //TODO: rewrite this using QTime's time formats. "am/pm" doesn't make sense
259
260
    // in some locale's
    QString suffix;
261
    if (!use12Clock()) {
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        suffix = QStringLiteral("00");
    } else {
        suffix = QStringLiteral("am");
    }

    // 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;
Laurent Montel's avatar
Laurent Montel committed
287
    const int tw2 = fmS.boundingRect(suffix).width();
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    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));

304
305
306
        // set the hour and suffix from the cell
        hour.setNum(cellToHour(cell));
        suffix = cellToSuffix(cell);
307
308
309

        // draw the time label
        p.setPen(textColor);
Laurent Montel's avatar
Laurent Montel committed
310
        const int timeWidth = fm.boundingRect(hour).width();
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        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
{
Laurent Montel's avatar
Laurent Montel committed
326
    return {mMiniWidth, mRows * mCellHeight};
327
328
329
330
}

void TimeLabels::contextMenuEvent(QContextMenuEvent *event)
{
Laurent Montel's avatar
Laurent Montel committed
331
    Q_UNUSED(event)
332
333

    QMenu popup(this);
334
335
336
337
    QAction *editTimeZones = popup.addAction(QIcon::fromTheme(QStringLiteral("document-properties")),
                                             i18n("&Add Timezones..."));
    QAction *removeTimeZone = popup.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")),
                                              i18n("&Remove Timezone %1", i18n(mTimezone.id().constData())));
Laurent Montel's avatar
Laurent Montel committed
338
339
340
    if (!mTimezone.isValid()
        || !mTimeLabelsZone->preferences()->timeScaleTimezones().count()
        || mTimezone == mTimeLabelsZone->preferences()->timeZone()) {
341
342
343
344
345
        removeTimeZone->setEnabled(false);
    }

    QAction *activatedAction = popup.exec(QCursor::pos());
    if (activatedAction == editTimeZones) {
346
        QPointer<TimeScaleConfigDialog> dialog = new TimeScaleConfigDialog(mTimeLabelsZone->preferences(), this);
347
348
349
350
351
352
        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
353
        list.removeAll(QString::fromUtf8(mTimezone.id()));
354
355
356
357
358
359
360
361
        mTimeLabelsZone->preferences()->setTimeScaleTimezones(list);
        mTimeLabelsZone->preferences()->writeConfig();
        mTimeLabelsZone->reset();
        hide();
        deleteLater();
    }
}

Volker Krause's avatar
Volker Krause committed
362
QTimeZone TimeLabels::timeZone() const
363
{
Volker Krause's avatar
Volker Krause committed
364
    return mTimezone;
365
366
367
368
}

QString TimeLabels::header() const
{
369
    return i18n(mTimezone.id().constData());
370
371
372
373
}

QString TimeLabels::headerToolTip() const
{
374
    QDateTime now = QDateTime::currentDateTime();
375
    QString toolTip;
376

377
    toolTip += QLatin1String("<qt>");
378
379
380
    toolTip += i18nc("title for timezone info, the timezone id and utc offset",
                     "<b>%1 (%2)</b>", i18n(mTimezone.id().constData()),
                     KCalUtils::Stringify::tzUTCOffsetStr(mTimezone));
381
    toolTip += QLatin1String("<hr>");
382
383
384
385
    toolTip += i18nc("heading for timezone display name",
                     "<i>Name:</i> %1", mTimezone.displayName(now, QTimeZone::LongName));
    toolTip += QLatin1String("<br/>");

Volker Krause's avatar
Volker Krause committed
386
    if (mTimezone.country() != QLocale::AnyCountry) {
387
388
        toolTip += i18nc("heading for timezone country",
                         "<i>Country:</i> %1", QLocale::countryToString(mTimezone.country()));
389
390
        toolTip += QLatin1String("<br/>");
    }
Volker Krause's avatar
Volker Krause committed
391
392

    auto abbreviations = QStringLiteral("&nbsp;");
393
394
    const auto lst = mTimezone.transitions(now, now.addYears(1));
    for (const auto &transition : lst) {
Volker Krause's avatar
Volker Krause committed
395
396
397
398
399
        abbreviations += transition.abbreviation;
        abbreviations += QLatin1String(",&nbsp;");
    }
    abbreviations.chop(7);
    if (!abbreviations.isEmpty()) {
400
401
        toolTip += i18nc("heading for comma-separated list of timezone abbreviations",
                         "<i>Abbreviations:</i>");
Volker Krause's avatar
Volker Krause committed
402
        toolTip += abbreviations;
403
404
        toolTip += QLatin1String("<br/>");
    }
Laurent Montel's avatar
Laurent Montel committed
405
406
    const QString timeZoneComment(mTimezone.comment());
    if (!timeZoneComment.isEmpty()) {
407
408
        toolTip += i18nc("heading for the timezone comment",
                         "<i>Comment:</i> %1", timeZoneComment);
409
410
411
412
413
    }
    toolTip += QLatin1String("</qt>");

    return toolTip;
}
414
415
416
417

bool TimeLabels::event(QEvent *event)
{
    if (event->type() == QEvent::ToolTip) {
418
        auto helpEvent = static_cast<QHelpEvent *>(event);
419
420
421
422
423
424
        const int cell = yposToCell(helpEvent->pos().y());

        QString toolTip;
        toolTip += QLatin1String("<qt>");
        toolTip += i18nc("[hour of the day][am/pm/00] [timezone id (timezone-offset)]",
                         "%1%2<br/>%3 (%4)",
Laurent Montel's avatar
Laurent Montel committed
425
                         cellToHour(cell), cellToSuffix(cell),
426
427
428
429
430
431
432
433
434
435
                         i18n(mTimezone.id().constData()),
                         KCalUtils::Stringify::tzUTCOffsetStr(mTimezone));
        toolTip += QLatin1String("</qt>");

        QToolTip::showText(helpEvent->globalPos(), toolTip, this);

        return true;
    }
    return QWidget::event(event);
}