calprintdefaultplugins.cpp 65.4 KB
Newer Older
1
/*
2
3
4
5
6
7
8
9
  SPDX-FileCopyrightText: 1998 Preston Brown <pbrown@kde.org>
  SPDX-FileCopyrightText: 2003 Reinhold Kainhofer <reinhold@kainhofer.com>
  SPDX-FileCopyrightText: 2003 Cornelius Schumacher <schumacher@kde.org>
  SPDX-FileCopyrightText: 2008 Ron Goodheart <rong.dev@gmail.com>
  SPDX-FileCopyrightText: 2010-2020 Laurent Montel <montel@kde.org>
  SPDX-FileCopyrightText: 2012-2013 Allen Winter <winter@kde.org>

  SPDX-License-Identifier: GPL-2.0-or-later WITH Qt-Commercial-exception-1.0
10
11
12
13
14
*/

#include "calprintdefaultplugins.h"
#include "kcalprefs.h"
#include "utils.h"
15

16
17
#include <Item>

18
#include <KCalendarCore/Visitor>
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#include <KCalUtils/IncidenceFormatter>
#include <KCalUtils/Stringify>

#include <KConfigGroup>

#include <QPainter>
#include <QPrinter>

using namespace CalendarSupport;

static QString cleanStr(const QString &instr)
{
    QString ret = instr;
    return ret.replace(QLatin1Char('\n'), QLatin1Char(' '));
}

/**************************************************************
 *           Print Incidence
 **************************************************************/

CalPrintIncidence::CalPrintIncidence() : CalPrintPluginBase()
{
}

CalPrintIncidence::~CalPrintIncidence()
{
}

QWidget *CalPrintIncidence::createConfigWidget(QWidget *w)
{
    return new CalPrintIncidenceConfig(w);
}

void CalPrintIncidence::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
55
56
    CalPrintIncidenceConfig *cfg
        = dynamic_cast<CalPrintIncidenceConfig *>((QWidget *)mConfigWidget);
57
58
59
60
61
62
63
64
65
66
67
68
69
    if (cfg) {
        mUseColors = cfg->mColors->isChecked();
        mPrintFooter = cfg->mPrintFooter->isChecked();
        mShowOptions = cfg->mShowDetails->isChecked();
        mShowSubitemsNotes = cfg->mShowSubitemsNotes->isChecked();
        mShowAttendees = cfg->mShowAttendees->isChecked();
        mShowAttachments = cfg->mShowAttachments->isChecked();
        mShowNoteLines = cfg->mShowNoteLines->isChecked();
    }
}

void CalPrintIncidence::setSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
70
71
    CalPrintIncidenceConfig *cfg
        = dynamic_cast<CalPrintIncidenceConfig *>((QWidget *)mConfigWidget);
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
    if (cfg) {
        cfg->mColors->setChecked(mUseColors);
        cfg->mPrintFooter->setChecked(mPrintFooter);
        cfg->mShowDetails->setChecked(mShowOptions);
        cfg->mShowSubitemsNotes->setChecked(mShowSubitemsNotes);
        cfg->mShowAttendees->setChecked(mShowAttendees);
        cfg->mShowAttachments->setChecked(mShowAttachments);
        cfg->mShowNoteLines->setChecked(mShowNoteLines);
    }
}

void CalPrintIncidence::loadConfig()
{
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        mShowOptions = grp.readEntry("Show Options", false);
        mShowSubitemsNotes = grp.readEntry("Show Subitems and Notes", false);
        mShowAttendees = grp.readEntry("Use Attendees", false);
        mShowAttachments = grp.readEntry("Use Attachments", false);
        mShowNoteLines = grp.readEntry("Note Lines", false);
    }
    setSettingsWidget();
}

void CalPrintIncidence::saveConfig()
{
    readSettingsWidget();
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        grp.writeEntry("Show Options", mShowOptions);
        grp.writeEntry("Show Subitems and Notes", mShowSubitemsNotes);
        grp.writeEntry("Use Attendees", mShowAttendees);
        grp.writeEntry("Use Attachments", mShowAttachments);
        grp.writeEntry("Note Lines", mShowNoteLines);
    }
}

109
class TimePrintStringsVisitor : public KCalendarCore::Visitor
110
111
{
public:
Laurent Montel's avatar
Laurent Montel committed
112
113
114
    TimePrintStringsVisitor()
    {
    }
115

116
    bool act(KCalendarCore::IncidenceBase::Ptr incidence)
117
118
119
    {
        return incidence->accept(*this, incidence);
    }
Laurent Montel's avatar
Laurent Montel committed
120

121
122
123
124
125
    QString mStartCaption, mStartString;
    QString mEndCaption, mEndString;
    QString mDurationCaption, mDurationString;

protected:
126
    bool visit(const KCalendarCore::Event::Ptr &event) override
Laurent Montel's avatar
Laurent Montel committed
127
128
129
130
131
    {
        if (event->dtStart().isValid()) {
            mStartCaption = i18n("Start date: ");
            mStartString = KCalUtils::IncidenceFormatter::dateTimeToString(
                event->dtStart(), event->allDay(), false);
132
133
134
135
136
        } else {
            mStartCaption = i18n("No start date");
            mStartString.clear();
        }

Laurent Montel's avatar
Laurent Montel committed
137
        if (event->hasEndDate()) {
138
            mEndCaption = i18n("End date: ");
Laurent Montel's avatar
Laurent Montel committed
139
140
141
            mEndString = KCalUtils::IncidenceFormatter::dateTimeToString(
                event->dtEnd(), event->allDay(), false);
        } else if (event->hasDuration()) {
142
143
144
145
146
147
148
149
150
151
152
153
154
155
            mEndCaption = i18n("Duration: ");
            int mins = event->duration().asSeconds() / 60;
            if (mins >= 60) {
                mEndString += i18np("1 hour ", "%1 hours ", mins / 60);
            }
            if (mins % 60 > 0) {
                mEndString += i18np("1 minute ", "%1 minutes ", mins % 60);
            }
        } else {
            mEndCaption = i18n("No end date");
            mEndString.clear();
        }
        return true;
    }
Laurent Montel's avatar
Laurent Montel committed
156

157
    bool visit(const KCalendarCore::Todo::Ptr &todo) override
Laurent Montel's avatar
Laurent Montel committed
158
159
160
161
162
    {
        if (todo->hasStartDate()) {
            mStartCaption = i18n("Start date: ");
            mStartString = KCalUtils::IncidenceFormatter::dateTimeToString(
                todo->dtStart(), todo->allDay(), false);
163
164
165
166
167
        } else {
            mStartCaption = i18n("No start date");
            mStartString.clear();
        }

Laurent Montel's avatar
Laurent Montel committed
168
        if (todo->hasDueDate()) {
169
            mEndCaption = i18n("Due date: ");
Laurent Montel's avatar
Laurent Montel committed
170
171
            mEndString = KCalUtils::IncidenceFormatter::dateTimeToString(
                todo->dtDue(), todo->allDay(), false);
172
173
174
175
176
177
        } else {
            mEndCaption = i18n("No due date");
            mEndString.clear();
        }
        return true;
    }
Laurent Montel's avatar
Laurent Montel committed
178

179
    bool visit(const KCalendarCore::Journal::Ptr &journal) override
Laurent Montel's avatar
Laurent Montel committed
180
    {
181
        mStartCaption = i18n("Start date: ");
Laurent Montel's avatar
Laurent Montel committed
182
183
        mStartString = KCalUtils::IncidenceFormatter::dateTimeToString(
            journal->dtStart(), journal->allDay(), false);
184
185
186
187
        mEndCaption.clear();
        mEndString.clear();
        return true;
    }
Laurent Montel's avatar
Laurent Montel committed
188

189
    bool visit(const KCalendarCore::FreeBusy::Ptr &fb) override
Laurent Montel's avatar
Laurent Montel committed
190
    {
191
192
193
194
195
        Q_UNUSED(fb);
        return true;
    }
};

Laurent Montel's avatar
Laurent Montel committed
196
int CalPrintIncidence::printCaptionAndText(QPainter &p, const QRect &box, const QString &caption, const QString &text, const QFont &captionFont, const QFont &textFont)
197
198
{
    QFontMetrics captionFM(captionFont);
Laurent Montel's avatar
Laurent Montel committed
199
    int textWd = captionFM.boundingRect(caption).width();
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    QRect textRect(box);

    QFont oldFont(p.font());
    p.setFont(captionFont);
    p.drawText(box, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, caption);

    if (!text.isEmpty()) {
        textRect.setLeft(textRect.left() + textWd);
        p.setFont(textFont);
        p.drawText(textRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, text);
    }
    p.setFont(oldFont);
    return textRect.bottom();
}

void CalPrintIncidence::print(QPainter &p, int width, int height)
{
    QFont oldFont(p.font());
    QFont textFont(QStringLiteral("sans-serif"), 11, QFont::Normal);
    QFont captionFont(QStringLiteral("sans-serif"), 11, QFont::Bold);
    p.setFont(textFont);
    int lineHeight = p.fontMetrics().lineSpacing();
    QString cap, txt;

224
    KCalendarCore::Incidence::List::ConstIterator it;
225
226
227
228
229
230
231
232
233
    for (it = mSelectedIncidences.constBegin(); it != mSelectedIncidences.constEnd(); ++it) {
        // don't do anything on a 0-pointer!
        if (!(*it)) {
            continue;
        }
        if (it != mSelectedIncidences.constBegin()) {
            mPrinter->newPage();
        }

234
        const bool isJournal = ((*it)->type() == KCalendarCore::Incidence::TypeJournal);
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
263
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

        //  PAGE Layout (same for landscape and portrait! astonishingly, it looks good with both!):
        //  +-----------------------------------+
        //  | Header:  Summary                  |
        //  +===================================+
        //  | start: ______   end: _________    |
        //  | repeats: ___________________      |
        //  | reminder: __________________      |
        //  +-----------------------------------+
        //  | Location: ______________________  |
        //  +------------------------+----------+
        //  | Description:           | Notes or |
        //  |                        | Subitems |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  |                        |          |
        //  +------------------------+----------+
        //  | Attachments:           | Settings |
        //  |                        |          |
        //  +------------------------+----------+
        //  | Attendees:                        |
        //  |                                   |
        //  +-----------------------------------+
        //  | Categories: _____________________ |
        //  +-----------------------------------+

        QRect box(0, 0, width, height);
        QRect titleBox(box);
        titleBox.setHeight(headerHeight());
        QColor headerColor = categoryBgColor(*it);
        // Draw summary as header, no small calendars in title bar, expand height if needed
        int titleBottom = drawHeader(p, (*it)->summary(), QDate(), QDate(),
                                     titleBox, true, headerColor);
        titleBox.setBottom(titleBottom);

        QRect timesBox(titleBox);
        timesBox.setTop(titleBox.bottom() + padding());
        timesBox.setHeight(height / 8);

        TimePrintStringsVisitor stringVis;
        int h = timesBox.top();
        if (stringVis.act(*it)) {
            QRect textRect(timesBox.left() + padding(),
                           timesBox.top() + padding(), 0, lineHeight);
            textRect.setRight(timesBox.center().x());
            h = printCaptionAndText(p, textRect, stringVis.mStartCaption,
                                    stringVis.mStartString, captionFont, textFont);

            textRect.setLeft(textRect.right());
            textRect.setRight(timesBox.right() - padding());
            h = qMax(printCaptionAndText(p, textRect, stringVis.mEndCaption,
                                         stringVis.mEndString, captionFont, textFont), h);
        }

        // Recurrence Printing
        if ((*it)->recurs()) {
            QRect recurBox(timesBox.left() + padding(), h + padding(),
                           timesBox.right() - padding(), lineHeight);
298
            KCalendarCore::Recurrence *recurs = (*it)->recurrence();
299
300
301
302
303
304
            QString displayString = KCalUtils::IncidenceFormatter::recurrenceString((*it));
            // exception dates
            QString exceptString;
            if (!recurs->exDates().isEmpty()) {
                exceptString = i18nc("except for listed dates", " except");
                for (int i = 0; i < recurs->exDates().size(); ++i) {
Laurent Montel's avatar
Laurent Montel committed
305
                    exceptString.append(QLatin1Char(' '));
306
                    exceptString.append(QLocale::system().toString(recurs->exDates().at(i),
Laurent Montel's avatar
Laurent Montel committed
307
                                                                   QLocale::ShortFormat));
308
309
310
311
312
313
314
315
316
317
318
                }
            }
            displayString.append(exceptString);
            h = qMax(printCaptionAndText(p, recurBox, i18n("Repeats: "),
                                         displayString, captionFont, textFont), h);
        }

        if (!isJournal) {
            // Alarms Printing
            QRect alarmBox(timesBox.left() + padding(), h + padding(),
                           timesBox.right() - padding(), lineHeight);
319
            KCalendarCore::Alarm::List alarms = (*it)->alarms();
Laurent Montel's avatar
Laurent Montel committed
320
            if (alarms.isEmpty()) {
321
322
323
324
325
326
                cap = i18n("No reminders");
                txt.clear();
            } else {
                cap = i18np("Reminder: ", "%1 reminders: ", alarms.count());

                QStringList alarmStrings;
327
                KCalendarCore::Alarm::List::ConstIterator it;
328
329
                alarmStrings.reserve(alarms.count());
                for (it = alarms.constBegin(); it != alarms.constEnd(); ++it) {
330
                    KCalendarCore::Alarm::Ptr alarm = *it;
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

                    // Alarm offset, copied from koeditoralarms.cpp:
                    KLocalizedString offsetstr;
                    int offset = 0;
                    if (alarm->hasStartOffset()) {
                        offset = alarm->startOffset().asSeconds();
                        if (offset < 0) {
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end",
                                               "%1 before the start");
                            offset = -offset;
                        } else {
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end",
                                               "%1 after the start");
                        }
                    } else if (alarm->hasEndOffset()) {
                        offset = alarm->endOffset().asSeconds();
                        if (offset < 0) {
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end",
                                               "%1 before the end");
                            offset = -offset;
                        } else {
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end",
                                               "%1 after the end");
                        }
                    }

                    offset = offset / 60; // make minutes
Laurent Montel's avatar
Laurent Montel committed
358
                    int useoffset = 0;
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378

                    if (offset % (24 * 60) == 0 && offset > 0) {     // divides evenly into days?
                        useoffset = offset / (24 * 60);
                        offsetstr = offsetstr.subs(i18np("1 day", "%1 days", useoffset));
                    } else if (offset % 60 == 0 && offset > 0) {   // divides evenly into hours?
                        useoffset = offset / 60;
                        offsetstr = offsetstr.subs(i18np("1 hour", "%1 hours", useoffset));
                    } else {
                        useoffset = offset;
                        offsetstr = offsetstr.subs(i18np("1 minute", "%1 minutes", useoffset));
                    }
                    alarmStrings << offsetstr.toString();
                }
                txt = alarmStrings.join(i18nc("Spacer for the joined list of categories", ", "));
            }
            h = qMax(printCaptionAndText(p, alarmBox, cap, txt, captionFont, textFont), h);
        }
        QRect organizerBox(timesBox.left() + padding(), h + padding(),
                           timesBox.right() - padding(), lineHeight);
        h = qMax(printCaptionAndText(p, organizerBox, i18n("Organizer: "),
379
                                     (*it)->organizer().fullName(), captionFont, textFont), h);
380
381
382
383
384
385
386
387
388
389
390

        // Finally, draw the frame around the time information...
        timesBox.setBottom(qMax(timesBox.bottom(), h + padding()));
        drawBox(p, BOX_BORDER_WIDTH, timesBox);

        QRect locationBox(timesBox);
        locationBox.setTop(timesBox.bottom() + padding());
        locationBox.setHeight(0);
        int locationBottom = 0;
        if (!isJournal) {
            locationBottom = drawBoxWithCaption(p, locationBox, i18n("Location: "),
Laurent Montel's avatar
Laurent Montel committed
391
392
                                                (*it)->location(), /*sameLine=*/ true,
                                                /*expand=*/ true, captionFont, textFont);
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        }
        locationBox.setBottom(locationBottom);

        // Now start constructing the boxes from the bottom:
        QRect footerBox(locationBox);
        footerBox.setBottom(box.bottom());
        footerBox.setTop(footerBox.bottom() - lineHeight - 2 * padding());

        QRect categoriesBox(footerBox);
        categoriesBox.setBottom(footerBox.top());
        categoriesBox.setTop(categoriesBox.bottom() - lineHeight - 2 * padding());
        QRect attendeesBox(box.left(), categoriesBox.top() - padding() - box.height() / 9,
                           box.width(), box.height() / 9);
        QRect attachmentsBox(box.left(), attendeesBox.top() - padding() - box.height() / 9,
                             box.width() * 3 / 4 - padding(), box.height() / 9);
Laurent Montel's avatar
Laurent Montel committed
408
        QRect optionsBox(isJournal ? box.left() : attachmentsBox.right() + padding(),
409
410
411
412
                         attachmentsBox.top(), 0, 0);
        optionsBox.setRight(box.right());
        optionsBox.setBottom(attachmentsBox.bottom());
        QRect notesBox(optionsBox.left(),
Laurent Montel's avatar
Laurent Montel committed
413
414
                       isJournal ? (timesBox.bottom() + padding())
                       : (locationBox.bottom() + padding()),
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
                       optionsBox.width(), 0);
        notesBox.setBottom(optionsBox.top() - padding());
        QRect descriptionBox(notesBox);
        descriptionBox.setLeft(box.left());
        descriptionBox.setRight(attachmentsBox.right());

        // Adjust boxes depending on the show options...
        if (!mShowSubitemsNotes || isJournal) {
            descriptionBox.setRight(box.right());
        }
        if (!mShowAttachments || !mShowAttendees) {
            descriptionBox.setBottom(attachmentsBox.bottom());
            optionsBox.setTop(attendeesBox.top());
            optionsBox.setBottom(attendeesBox.bottom());
            notesBox.setBottom(attachmentsBox.bottom());
            if (mShowOptions) {
                attendeesBox.setRight(attachmentsBox.right());
            }
            if (!mShowAttachments && !mShowAttendees) {
                if (mShowSubitemsNotes) {
                    descriptionBox.setBottom(attendeesBox.bottom());
                }
                if (!mShowOptions) {
                    descriptionBox.setBottom(attendeesBox.bottom());
                    notesBox.setBottom(attendeesBox.bottom());
                }
            }
        }
        if (mShowAttachments && !isJournal) {
            if (!mShowOptions) {
                attachmentsBox.setRight(box.right());
                attachmentsBox.setRight(box.right());
            }
            if (!mShowAttendees) {
                attachmentsBox.setTop(attendeesBox.top());
                attachmentsBox.setBottom(attendeesBox.bottom());
            }
        }
        int newBottom = drawBoxWithCaption(p, descriptionBox, i18n("Description:"),
Laurent Montel's avatar
Laurent Montel committed
454
455
                                           (*it)->description(), /*sameLine=*/ false,
                                           /*expand=*/ false, captionFont, textFont,
456
457
458
459
460
461
462
463
464
                                           (*it)->descriptionIsRich());
        if (mShowNoteLines) {
            drawNoteLines(p, descriptionBox, newBottom);
        }

        Akonadi::Item item = mCalendar->item((*it)->uid());
        Akonadi::Item::List relations = mCalendar->childItems(item.id());

        if (mShowSubitemsNotes && !isJournal) {
465
            if (relations.isEmpty() || (*it)->type() != KCalendarCore::Incidence::TypeTodo) {
466
                int notesPosition = drawBoxWithCaption(p, notesBox, i18n("Notes:"),
Laurent Montel's avatar
Laurent Montel committed
467
468
                                                       QString(), /*sameLine=*/ false,
                                                       /*expand=*/ false, captionFont, textFont);
469
470
471
                drawNoteLines(p, notesBox, notesPosition);
            } else {
                QString subitemCaption;
Laurent Montel's avatar
Laurent Montel committed
472
                if (relations.isEmpty()) {
473
474
475
476
477
478
479
480
481
482
483
484
                    subitemCaption = i18n("No Subitems");
                    txt.clear();
                } else {
                    subitemCaption = i18np("1 Subitem:",
                                           "%1 Subitems:",
                                           relations.count());
                }

                QString subitemString;
                QString statusString;
                QString datesString;
                int count = 0;
Laurent Montel's avatar
Laurent Montel committed
485
                for (const Akonadi::Item &item : qAsConst(relations)) {
486
                    KCalendarCore::Todo::Ptr todo = CalendarSupport::todo(item);
487
488
489
490
491
492
493
                    ++count;
                    if (!todo) {   // defensive, skip any zero pointers
                        continue;
                    }
                    // format the status
                    statusString = KCalUtils::Stringify::incidenceStatus(todo->status());
                    if (statusString.isEmpty()) {
494
                        if (todo->status() == KCalendarCore::Incidence::StatusNone) {
495
496
497
498
499
500
501
502
                            statusString = i18nc("no status", "none");
                        } else {
                            statusString = i18nc("unknown status", "unknown");
                        }
                    }
                    // format the dates if provided
                    datesString.clear();
                    if (todo->dtStart().isValid()) {
503
                        datesString += i18nc("subitem start date", "Start Date: %1\n",
Laurent Montel's avatar
Laurent Montel committed
504
505
                                             QLocale().toString(todo->dtStart().toLocalTime().date(),
                                                                QLocale::ShortFormat));
506
                        if (!todo->allDay()) {
507
                            datesString += i18nc("subitem start time", "Start Time: %1\n",
Laurent Montel's avatar
Laurent Montel committed
508
509
                                                 QLocale().toString(todo->dtStart().toLocalTime().
                                                                    time(), QLocale::ShortFormat));
510
511
                        }
                    }
512
                    if (todo->dateTime(KCalendarCore::Incidence::RoleEnd).isValid()) {
513
                        subitemString += i18nc("subitem due date", "Due Date: %1\n",
514
                                               QLocale().toString(todo->dateTime(KCalendarCore::Incidence
Laurent Montel's avatar
Laurent Montel committed
515
516
517
                                                                                 ::RoleEnd).
                                                                  toLocalTime().date(),
                                                                  QLocale::ShortFormat));
518
519

                        if (!todo->allDay()) {
520
                            subitemString += i18nc("subitem due time", "Due Time: %1\n",
521
                                                   QLocale().toString(todo->dateTime(KCalendarCore::
Laurent Montel's avatar
Laurent Montel committed
522
523
524
                                                                                     Incidence::
                                                                                     RoleEnd).
                                                                      toLocalTime().time(),
Laurent Montel's avatar
Laurent Montel committed
525
                                                                      QLocale::ShortFormat));
526
527
528
529
530
531
532
533
534
535
536
537
                        }
                    }
                    subitemString += i18nc("subitem counter", "%1: ", count);
                    subitemString += todo->summary();
                    subitemString += QLatin1Char('\n');
                    if (!datesString.isEmpty()) {
                        subitemString += datesString;
                        subitemString += QLatin1Char('\n');
                    }
                    subitemString += i18nc("subitem Status: statusString",
                                           "Status: %1\n",
                                           statusString);
Laurent Montel's avatar
Laurent Montel committed
538
539
                    subitemString += KCalUtils::IncidenceFormatter::recurrenceString(todo)
                                     + QLatin1Char('\n');
540
541
542
543
544
545
546
547
548
                    subitemString += i18nc("subitem Priority: N",
                                           "Priority: %1\n",
                                           QString::number(todo->priority()));
                    subitemString += i18nc("subitem Secrecy: secrecyString",
                                           "Secrecy: %1\n",
                                           KCalUtils::Stringify::incidenceSecrecy(todo->secrecy()));
                    subitemString += QLatin1Char('\n');
                }
                drawBoxWithCaption(p, notesBox, subitemCaption,
Laurent Montel's avatar
Laurent Montel committed
549
550
                                   subitemString, /*sameLine=*/ false,
                                   /*expand=*/ false, captionFont, textFont);
551
552
553
554
            }
        }

        if (mShowAttachments && !isJournal) {
555
            const KCalendarCore::Attachment::List attachments = (*it)->attachments();
556
            QString attachmentCaption;
Laurent Montel's avatar
Laurent Montel committed
557
            if (attachments.isEmpty()) {
558
559
560
561
562
563
564
565
                attachmentCaption = i18n("No Attachments");
                txt.clear();
            } else {
                attachmentCaption = i18np("1 Attachment:",
                                          "%1 Attachments:",
                                          attachments.count());
            }
            QString attachmentString;
566
            KCalendarCore::Attachment::List::ConstIterator ait = attachments.constBegin();
567
568
569
570
            for (; ait != attachments.constEnd(); ++ait) {
                if (!attachmentString.isEmpty()) {
                    attachmentString += i18nc("Spacer for list of attachments", "  ");
                }
571
                attachmentString.append((*ait).label());
572
573
574
            }
            drawBoxWithCaption(p, attachmentsBox,
                               attachmentCaption, attachmentString,
Laurent Montel's avatar
Laurent Montel committed
575
                               /*sameLine=*/ false, /*expand=*/ false,
576
577
578
                               captionFont, textFont);
        }
        if (mShowAttendees) {
579
            const KCalendarCore::Attendee::List attendees = (*it)->attendees();
580
            QString attendeeCaption;
Laurent Montel's avatar
Laurent Montel committed
581
            if (attendees.isEmpty()) {
582
583
584
585
586
587
588
                attendeeCaption = i18n("No Attendees");
            } else {
                attendeeCaption = i18np("1 Attendee:",
                                        "%1 Attendees:",
                                        attendees.count());
            }
            QString attendeeString;
589
            KCalendarCore::Attendee::List::ConstIterator ait = attendees.constBegin();
590
591
592
593
594
            for (; ait != attendees.constEnd(); ++ait) {
                if (!attendeeString.isEmpty()) {
                    attendeeString += QLatin1Char('\n');
                }
                attendeeString += i18nc(
Laurent Montel's avatar
Laurent Montel committed
595
596
597
598
                    "Formatting of an attendee: "
                    "'Name (Role): Status', e.g. 'Reinhold Kainhofer "
                    "<reinhold@kainhofer.com> (Participant): Awaiting Response'",
                    "%1 (%2): %3",
599
600
601
                    (*ait).fullName(),
                    KCalUtils::Stringify::attendeeRole((*ait).role()),
                    KCalUtils::Stringify::attendeeStatus((*ait).status()));
602
603
            }
            drawBoxWithCaption(p, attendeesBox, attendeeCaption, attendeeString,
Laurent Montel's avatar
Laurent Montel committed
604
                               /*sameLine=*/ false, /*expand=*/ false,
605
606
607
608
609
610
                               captionFont, textFont);
        }

        if (mShowOptions) {
            QString optionsString;
            if (!KCalUtils::Stringify::incidenceStatus((*it)->status()).isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
611
612
                optionsString
                    += i18n("Status: %1", KCalUtils::Stringify::incidenceStatus((*it)->status()));
613
614
615
                optionsString += QLatin1Char('\n');
            }
            if (!KCalUtils::Stringify::incidenceSecrecy((*it)->secrecy()).isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
616
617
618
                optionsString
                    += i18n("Secrecy: %1",
                            KCalUtils::Stringify::incidenceSecrecy((*it)->secrecy()));
619
620
                optionsString += QLatin1Char('\n');
            }
621
622
623
            if ((*it)->type() == KCalendarCore::Incidence::TypeEvent) {
                KCalendarCore::Event::Ptr e = (*it).staticCast<KCalendarCore::Event>();
                if (e->transparency() == KCalendarCore::Event::Opaque) {
624
625
626
627
628
                    optionsString += i18n("Show as: Busy");
                } else {
                    optionsString += i18n("Show as: Free");
                }
                optionsString += QLatin1Char('\n');
629
630
            } else if ((*it)->type() == KCalendarCore::Incidence::TypeTodo) {
                KCalendarCore::Todo::Ptr t = (*it).staticCast<KCalendarCore::Todo>();
631
632
633
634
                if (t->isOverdue()) {
                    optionsString += i18n("This task is overdue!");
                    optionsString += QLatin1Char('\n');
                }
635
            } else if ((*it)->type() == KCalendarCore::Incidence::TypeJournal) {
636
637
638
                //TODO: Anything Journal-specific?
            }
            drawBoxWithCaption(p, optionsBox, i18n("Settings: "),
Laurent Montel's avatar
Laurent Montel committed
639
                               optionsString, /*sameLine=*/ false, /*expand=*/ false,
640
641
642
643
                               captionFont, textFont);
        }

        drawBoxWithCaption(p, categoriesBox, i18n("Categories: "),
Laurent Montel's avatar
Laurent Montel committed
644
645
646
                           (*it)->categories().join(i18nc("Spacer for the joined list of categories",
                                                          ", ")),
                           /*sameLine=*/ true, /*expand=*/ false, captionFont, textFont);
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

        if (mPrintFooter) {
            drawFooter(p, footerBox);
        }
    }
    p.setFont(oldFont);
}

/**************************************************************
 *           Print Day
 **************************************************************/

CalPrintDay::CalPrintDay() : CalPrintPluginBase()
{
}

CalPrintDay::~CalPrintDay()
{
}

QWidget *CalPrintDay::createConfigWidget(QWidget *w)
{
    return new CalPrintDayConfig(w);
}

void CalPrintDay::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
674
675
    CalPrintDayConfig *cfg
        = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
    if (cfg) {
        mFromDate = cfg->mFromDate->date();
        mToDate = cfg->mToDate->date();

        if (cfg->mPrintTypeFilofax->isChecked()) {
            mDayPrintType = Filofax;
        } else if (cfg->mPrintTypeTimetable->isChecked()) {
            mDayPrintType = Timetable;
        } else {
            mDayPrintType = SingleTimetable;
        }

        mStartTime = cfg->mFromTime->time();
        mEndTime = cfg->mToTime->time();
        mIncludeAllEvents = cfg->mIncludeAllEvents->isChecked();

        mIncludeDescription = cfg->mIncludeDescription->isChecked();
        mSingleLineLimit = cfg->mSingleLineLimit->isChecked();
        mIncludeTodos = cfg->mIncludeTodos->isChecked();
        mUseColors = cfg->mColors->isChecked();
        mPrintFooter = cfg->mPrintFooter->isChecked();
        mShowNoteLines = cfg->mShowNoteLines->isChecked();
        mExcludeTime = cfg->mExcludeTime->isChecked();
        mExcludeConfidential = cfg->mExcludeConfidential->isChecked();
        mExcludePrivate = cfg->mExcludePrivate->isChecked();
    }
}

void CalPrintDay::setSettingsWidget()
{
    CalPrintDayConfig *cfg = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
    if (cfg) {
        cfg->mFromDate->setDate(mFromDate);
        cfg->mToDate->setDate(mToDate);

        cfg->mPrintTypeFilofax->setChecked(mDayPrintType == Filofax);
        cfg->mPrintTypeTimetable->setChecked(mDayPrintType == Timetable);
        cfg->mPrintTypeSingleTimetable->setChecked(mDayPrintType == SingleTimetable);

        cfg->mFromTime->setTime(mStartTime);
        cfg->mToTime->setTime(mEndTime);
        cfg->mIncludeAllEvents->setChecked(mIncludeAllEvents);

        cfg->mIncludeDescription->setChecked(mIncludeDescription);
        cfg->mSingleLineLimit->setChecked(mSingleLineLimit);
        cfg->mIncludeTodos->setChecked(mIncludeTodos);
        cfg->mColors->setChecked(mUseColors);
        cfg->mPrintFooter->setChecked(mPrintFooter);
        cfg->mShowNoteLines->setChecked(mShowNoteLines);
        cfg->mExcludeTime->setChecked(mExcludeTime);
        cfg->mExcludeConfidential->setChecked(mExcludeConfidential);
        cfg->mExcludePrivate->setChecked(mExcludePrivate);
    }
}

void CalPrintDay::loadConfig()
{
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        QDate dt = QDate::currentDate(); // any valid QDate will do
        QTime tm1(dayStart());
        QDateTime startTm(dt, tm1);
        QDateTime endTm(dt, tm1.addSecs(12 * 60 * 60));
        mStartTime = grp.readEntry("Start time", startTm).time();
        mEndTime = grp.readEntry("End time", endTm).time();
        mIncludeDescription = grp.readEntry("Include description", false);
        mIncludeTodos = grp.readEntry("Include todos", false);
        mIncludeAllEvents = grp.readEntry("Include all events", false);
Laurent Montel's avatar
Laurent Montel committed
744
        mDayPrintType = static_cast<eDayPrintType>(grp.readEntry("Print type", static_cast<int>(Timetable)));
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
        mSingleLineLimit = grp.readEntry("Single line limit", false);
        mShowNoteLines = grp.readEntry("Note Lines", false);
        mExcludeTime = grp.readEntry("Exclude time", false);
        mExcludeConfidential = grp.readEntry("Exclude confidential", true);
        mExcludePrivate = grp.readEntry("Exclude private", true);
    }
    setSettingsWidget();
}

void CalPrintDay::saveConfig()
{
    readSettingsWidget();
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        QDateTime dt = QDateTime::currentDateTime(); // any valid QDateTime will do
        dt.setTime(mStartTime);
        grp.writeEntry("Start time", dt);
        dt.setTime(mEndTime);
        grp.writeEntry("End time", dt);
        grp.writeEntry("Include description", mIncludeDescription);
        grp.writeEntry("Include todos", mIncludeTodos);
        grp.writeEntry("Include all events", mIncludeAllEvents);
        grp.writeEntry("Print type", int(mDayPrintType));
        grp.writeEntry("Single line limit", mSingleLineLimit);
        grp.writeEntry("Note Lines", mShowNoteLines);
        grp.writeEntry("Exclude time", mExcludeTime);
        grp.writeEntry("Exclude confidential", mExcludeConfidential);
        grp.writeEntry("Exclude private", mExcludePrivate);
    }
}

void CalPrintDay::setDateRange(const QDate &from, const QDate &to)
{
    CalPrintPluginBase::setDateRange(from, to);
Laurent Montel's avatar
Laurent Montel committed
779
780
    CalPrintDayConfig *cfg
        = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
    if (cfg) {
        cfg->mFromDate->setDate(from);
        cfg->mToDate->setDate(to);
    }
}

void CalPrintDay::print(QPainter &p, int width, int height)
{
    QDate curDay(mFromDate);

    QRect headerBox(0, 0, width, headerHeight());
    QRect footerBox(0, height - footerHeight(), width, footerHeight());
    height -= footerHeight();

    auto local = QLocale::system();

    switch (mDayPrintType) {
    case Filofax:
Laurent Montel's avatar
Laurent Montel committed
799
800
    case SingleTimetable:
    {
801
802
803
804
805
806
        QRect daysBox(headerBox);
        daysBox.setTop(headerBox.bottom() + padding());
        daysBox.setBottom(height);
        QString line1 = local.toString(mFromDate, QLocale::ShortFormat);
        QString line2 = local.toString(mToDate, QLocale::ShortFormat);
        QString title;
807
        if (orientation() == QPageLayout::Landscape) {
808
809
810
811
812
813
814
            title = i18nc("date from-to", "%1 - %2", line1, line2);
        } else {
            title = i18nc("date from-\nto", "%1 -\n%2", line1, line2);
        }
        drawHeader(p, title, mFromDate, QDate(), headerBox);
        if (mDayPrintType == Filofax) {
            drawDays(p, mFromDate, mToDate, mStartTime, mEndTime, daysBox,
Laurent Montel's avatar
Laurent Montel committed
815
                     mSingleLineLimit, mShowNoteLines,
816
817
818
819
820
821
822
823
824
825
                     mIncludeDescription, mExcludeConfidential, mExcludePrivate);
        } else if (mDayPrintType == SingleTimetable) {
            drawTimeTable(p, mFromDate, mToDate,
                          mIncludeAllEvents, mStartTime, mEndTime, daysBox,
                          mIncludeDescription, mExcludeTime, mExcludeConfidential,
                          mExcludePrivate);
        }
        if (mPrintFooter) {
            drawFooter(p, footerBox);
        }
Laurent Montel's avatar
Laurent Montel committed
826
        break;
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    }

    case Timetable:
    default:
        do {
            QTime curStartTime(mStartTime);
            QTime curEndTime(mEndTime);

            // For an invalid time range, simply show one hour, starting at the hour
            // before the given start time
            if (curEndTime <= curStartTime) {
                curStartTime = QTime(curStartTime.hour(), 0, 0);
                curEndTime = curStartTime.addSecs(3600);
            }

            drawHeader(p, local.toString(curDay, QLocale::ShortFormat), curDay, QDate(), headerBox);
843
            KCalendarCore::Event::List eventList = mCalendar->events(curDay, QTimeZone::systemTimeZone(),
Laurent Montel's avatar
Laurent Montel committed
844
845
                                                                     KCalendarCore::EventSortStartDate,
                                                                     KCalendarCore::SortDirectionAscending);
846
847

            // split out the all day events as they will be printed in a separate box
848
849
            KCalendarCore::Event::List alldayEvents, timedEvents;
            for (const KCalendarCore::Event::Ptr &event : qAsConst(eventList)) {
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
                if (event->allDay()) {
                    alldayEvents.append(event);
                } else {
                    timedEvents.append(event);
                }
            }

            int fontSize = 11;
            QFont textFont(QStringLiteral("sans-serif"), fontSize, QFont::Normal);
            p.setFont(textFont);
            int lineSpacing = p.fontMetrics().lineSpacing();

            int maxAllDayEvents = 8; // the max we allow to be printed, sorry.
            int allDayHeight = qMin(alldayEvents.count(), maxAllDayEvents) * lineSpacing;
            allDayHeight = qMax(allDayHeight, (5 * lineSpacing)) + (2 * padding());
            QRect allDayBox(TIMELINE_WIDTH + padding(), headerBox.bottom() + padding(),
                            width - TIMELINE_WIDTH - padding(), allDayHeight);
Laurent Montel's avatar
Laurent Montel committed
867
            if (!alldayEvents.isEmpty()) {
868
869
870
871
872
                // draw the side bar for all-day events
                QFont oldFont(p.font());
                p.setFont(QFont(QStringLiteral("sans-serif"), 9, QFont::Normal));
                drawVerticalBox(p,
                                BOX_BORDER_WIDTH,
Laurent Montel's avatar
Laurent Montel committed
873
874
                                QRect(0, headerBox.bottom() + padding(), TIMELINE_WIDTH,
                                      allDayHeight),
875
876
877
878
879
880
881
882
883
884
885
886
                                i18n("Today's Events"),
                                Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextWordWrap);
                p.setFont(oldFont);

                // now draw at most maxAllDayEvents in the all-day box
                drawBox(p, BOX_BORDER_WIDTH, allDayBox);

                QRect eventBox(allDayBox);
                eventBox.setLeft(TIMELINE_WIDTH + (2 * padding()));
                eventBox.setTop(eventBox.top() + padding());
                eventBox.setBottom(eventBox.top() + lineSpacing);
                int count = 0;
887
                for (const KCalendarCore::Event::Ptr &event : qAsConst(alldayEvents)) {
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                    if (count == maxAllDayEvents) {
                        break;
                    }
                    count++;
                    QString str;
                    if (event->location().isEmpty()) {
                        str = cleanStr(event->summary());
                    } else {
                        str = i18nc("summary, location", "%1, %2",
                                    cleanStr(event->summary()), cleanStr(event->location()));
                    }
                    printEventString(p, eventBox, str);
                    eventBox.setTop(eventBox.bottom());
                    eventBox.setBottom(eventBox.top() + lineSpacing);
                }
            } else {
                allDayBox.setBottom(headerBox.bottom());
            }

            QRect dayBox(allDayBox);
            dayBox.setTop(allDayBox.bottom() + padding());
            dayBox.setBottom(height);
            QList<QDate> workDays = CalendarSupport::workDays(curDay, curDay);
            drawAgendaDayBox(p, timedEvents, curDay, mIncludeAllEvents,
                             curStartTime, curEndTime, dayBox,
                             mIncludeDescription, mExcludeTime,
                             mExcludeConfidential, mExcludePrivate,
                             workDays);

            QRect tlBox(dayBox);
            tlBox.setLeft(0);
            tlBox.setWidth(TIMELINE_WIDTH);
            drawTimeLine(p, curStartTime, curEndTime, tlBox);

            if (mPrintFooter) {
                drawFooter(p, footerBox);
            }

            curDay = curDay.addDays(1);
            if (curDay <= mToDate) {
                mPrinter->newPage();
            }
        } while (curDay <= mToDate);
    } //switch
}

/**************************************************************
 *           Print Week
 **************************************************************/

CalPrintWeek::CalPrintWeek() : CalPrintPluginBase()
{
}

CalPrintWeek::~CalPrintWeek()
{
}

QWidget *CalPrintWeek::createConfigWidget(QWidget *w)
{
    return new CalPrintWeekConfig(w);
}

void CalPrintWeek::readSettingsWidget()
{
    CalPrintWeekConfig *cfg = dynamic_cast<CalPrintWeekConfig *>((QWidget *)mConfigWidget);
    if (cfg) {
        mFromDate = cfg->mFromDate->date();
        mToDate = cfg->mToDate->date();

        if (cfg->mPrintTypeFilofax->isChecked()) {
            mWeekPrintType = Filofax;
        } else if (cfg->mPrintTypeTimetable->isChecked()) {
            mWeekPrintType = Timetable;
        } else if (cfg->mPrintTypeSplitWeek->isChecked()) {
            mWeekPrintType = SplitWeek;
        } else {
            mWeekPrintType = Timetable;
        }

        mStartTime = cfg->mFromTime->time();
        mEndTime = cfg->mToTime->time();

        mShowNoteLines = cfg->mShowNoteLines->isChecked();
        mSingleLineLimit = cfg->mSingleLineLimit->isChecked();
        mIncludeTodos = cfg->mIncludeTodos->isChecked();
        mUseColors = cfg->mColors->isChecked();
        mPrintFooter = cfg->mPrintFooter->isChecked();
        mIncludeDescription = cfg->mIncludeDescription->isChecked();
        mExcludeTime = cfg->mExcludeTime->isChecked();
        mExcludeConfidential = cfg->mExcludeConfidential->isChecked();
        mExcludePrivate = cfg->mExcludePrivate->isChecked();
    }
}

void CalPrintWeek::setSettingsWidget()
{
    CalPrintWeekConfig *cfg = dynamic_cast<CalPrintWeekConfig *>((QWidget *)mConfigWidget);
    if (cfg) {
        cfg->mFromDate->setDate(mFromDate);
        cfg->mToDate->setDate(mToDate);

        cfg->mPrintTypeFilofax->setChecked(mWeekPrintType == Filofax);
        cfg->mPrintTypeTimetable->setChecked(mWeekPrintType == Timetable);
        cfg->mPrintTypeSplitWeek->setChecked(mWeekPrintType == SplitWeek);

        cfg->mFromTime->setTime(mStartTime);
        cfg->mToTime->setTime(mEndTime);

        cfg->mShowNoteLines->setChecked(mShowNoteLines);
        cfg->mSingleLineLimit->setChecked(mSingleLineLimit);
        cfg->mIncludeTodos->setChecked(mIncludeTodos);
        cfg->mColors->setChecked(mUseColors);