calprintdefaultplugins.cpp 68 KB
Newer Older
1
/*
2
3
4
5
  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>
Laurent Montel's avatar
Laurent Montel committed
6
  SPDX-FileCopyrightText: 2010-2021 Laurent Montel <montel@kde.org>
7
8
9
  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

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

#include <KConfigGroup>

#include <QPainter>
#include <QPrinter>

using namespace CalendarSupport;

30
static QString cleanString(const QString &instr)
31
32
33
34
35
36
37
38
39
{
    QString ret = instr;
    return ret.replace(QLatin1Char('\n'), QLatin1Char(' '));
}

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

Laurent Montel's avatar
Laurent Montel committed
40
41
CalPrintIncidence::CalPrintIncidence()
    : CalPrintPluginBase()
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{
}

CalPrintIncidence::~CalPrintIncidence()
{
}

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

void CalPrintIncidence::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
56
    auto 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
    auto cfg = dynamic_cast<CalPrintIncidenceConfig *>((QWidget *)mConfigWidget);
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
    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);
    }
}

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
135
        if (event->hasEndDate()) {
136
            mEndCaption = i18n("End date: ");
Laurent Montel's avatar
Laurent Montel committed
137
            mEndString = KCalUtils::IncidenceFormatter::dateTimeToString(event->dtEnd(), event->allDay(), false);
Laurent Montel's avatar
Laurent Montel committed
138
        } else if (event->hasDuration()) {
139
140
141
142
143
144
145
146
147
148
149
150
151
152
            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
153

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

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

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

183
    bool visit(const KCalendarCore::FreeBusy::Ptr &fb) override
Laurent Montel's avatar
Laurent Montel committed
184
    {
Laurent Montel's avatar
Laurent Montel committed
185
        Q_UNUSED(fb)
186
187
188
189
        return true;
    }
};

Laurent Montel's avatar
Laurent Montel committed
190
int CalPrintIncidence::printCaptionAndText(QPainter &p, QRect box, const QString &caption, const QString &text, const QFont &captionFont, const QFont &textFont)
191
192
{
    QFontMetrics captionFM(captionFont);
Laurent Montel's avatar
Laurent Montel committed
193
    int textWd = captionFM.boundingRect(caption).width();
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    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;

218
    KCalendarCore::Incidence::List::ConstIterator it;
219
220
221
222
223
224
225
226
227
    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();
        }

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

        //  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
Laurent Montel's avatar
Laurent Montel committed
265
        int titleBottom = drawHeader(p, (*it)->summary(), QDate(), QDate(), titleBox, true, headerColor);
266
267
268
269
270
271
272
273
274
        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)) {
Laurent Montel's avatar
Laurent Montel committed
275
            QRect textRect(timesBox.left() + padding(), timesBox.top() + padding(), 0, lineHeight);
276
            textRect.setRight(timesBox.center().x());
Laurent Montel's avatar
Laurent Montel committed
277
            h = printCaptionAndText(p, textRect, stringVis.mStartCaption, stringVis.mStartString, captionFont, textFont);
278
279
280

            textRect.setLeft(textRect.right());
            textRect.setRight(timesBox.right() - padding());
Laurent Montel's avatar
Laurent Montel committed
281
            h = qMax(printCaptionAndText(p, textRect, stringVis.mEndCaption, stringVis.mEndString, captionFont, textFont), h);
282
283
284
285
        }

        // Recurrence Printing
        if ((*it)->recurs()) {
Laurent Montel's avatar
Laurent Montel committed
286
            QRect recurBox(timesBox.left() + padding(), h + padding(), timesBox.right() - padding(), lineHeight);
287
            KCalendarCore::Recurrence *recurs = (*it)->recurrence();
288
289
290
291
292
293
            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
294
                    exceptString.append(QLatin1Char(' '));
Laurent Montel's avatar
Laurent Montel committed
295
                    exceptString.append(QLocale::system().toString(recurs->exDates().at(i), QLocale::ShortFormat));
296
297
298
                }
            }
            displayString.append(exceptString);
Laurent Montel's avatar
Laurent Montel committed
299
            h = qMax(printCaptionAndText(p, recurBox, i18n("Repeats: "), displayString, captionFont, textFont), h);
300
301
302
303
        }

        if (!isJournal) {
            // Alarms Printing
Laurent Montel's avatar
Laurent Montel committed
304
            QRect alarmBox(timesBox.left() + padding(), h + padding(), timesBox.right() - padding(), lineHeight);
305
            KCalendarCore::Alarm::List alarms = (*it)->alarms();
Laurent Montel's avatar
Laurent Montel committed
306
            if (alarms.isEmpty()) {
307
308
309
310
311
312
                cap = i18n("No reminders");
                txt.clear();
            } else {
                cap = i18np("Reminder: ", "%1 reminders: ", alarms.count());

                QStringList alarmStrings;
313
                KCalendarCore::Alarm::List::ConstIterator it;
314
315
                alarmStrings.reserve(alarms.count());
                for (it = alarms.constBegin(); it != alarms.constEnd(); ++it) {
316
                    KCalendarCore::Alarm::Ptr alarm = *it;
317
318
319
320
321
322
323

                    // Alarm offset, copied from koeditoralarms.cpp:
                    KLocalizedString offsetstr;
                    int offset = 0;
                    if (alarm->hasStartOffset()) {
                        offset = alarm->startOffset().asSeconds();
                        if (offset < 0) {
Laurent Montel's avatar
Laurent Montel committed
324
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end", "%1 before the start");
325
326
                            offset = -offset;
                        } else {
Laurent Montel's avatar
Laurent Montel committed
327
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end", "%1 after the start");
328
329
330
331
                        }
                    } else if (alarm->hasEndOffset()) {
                        offset = alarm->endOffset().asSeconds();
                        if (offset < 0) {
Laurent Montel's avatar
Laurent Montel committed
332
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end", "%1 before the end");
333
334
                            offset = -offset;
                        } else {
Laurent Montel's avatar
Laurent Montel committed
335
                            offsetstr = ki18nc("N days/hours/minutes before/after the start/end", "%1 after the end");
336
337
338
339
                        }
                    }

                    offset = offset / 60; // make minutes
Laurent Montel's avatar
Laurent Montel committed
340
                    int useoffset = 0;
341

Laurent Montel's avatar
Laurent Montel committed
342
                    if (offset % (24 * 60) == 0 && offset > 0) { // divides evenly into days?
343
344
                        useoffset = offset / (24 * 60);
                        offsetstr = offsetstr.subs(i18np("1 day", "%1 days", useoffset));
Laurent Montel's avatar
Laurent Montel committed
345
                    } else if (offset % 60 == 0 && offset > 0) { // divides evenly into hours?
346
347
348
349
350
351
352
353
                        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();
                }
354
                txt = alarmStrings.join(i18nc("Spacer for the joined list of categories/tags", ", "));
355
356
357
            }
            h = qMax(printCaptionAndText(p, alarmBox, cap, txt, captionFont, textFont), h);
        }
Laurent Montel's avatar
Laurent Montel committed
358
359
        QRect organizerBox(timesBox.left() + padding(), h + padding(), timesBox.right() - padding(), lineHeight);
        h = qMax(printCaptionAndText(p, organizerBox, i18n("Organizer: "), (*it)->organizer().fullName(), captionFont, textFont), h);
360
361
362
363
364
365
366
367
368
369

        // 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) {
Laurent Montel's avatar
Laurent Montel committed
370
371
372
373
374
375
376
377
            locationBottom = drawBoxWithCaption(p,
                                                locationBox,
                                                i18n("Location: "),
                                                (*it)->location(),
                                                /*sameLine=*/true,
                                                /*expand=*/true,
                                                captionFont,
                                                textFont);
378
379
380
381
382
383
384
385
386
387
388
        }
        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());
Laurent Montel's avatar
Laurent Montel committed
389
390
391
        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);
        QRect optionsBox(isJournal ? box.left() : attachmentsBox.right() + padding(), attachmentsBox.top(), 0, 0);
392
393
        optionsBox.setRight(box.right());
        optionsBox.setBottom(attachmentsBox.bottom());
Laurent Montel's avatar
Laurent Montel committed
394
        QRect notesBox(optionsBox.left(), isJournal ? (timesBox.bottom() + padding()) : (locationBox.bottom() + padding()), optionsBox.width(), 0);
395
396
397
398
399
400
401
402
403
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
        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());
            }
        }
Laurent Montel's avatar
Laurent Montel committed
432
433
434
435
436
437
438
439
        int newBottom = drawBoxWithCaption(p,
                                           descriptionBox,
                                           i18n("Description:"),
                                           (*it)->description(),
                                           /*sameLine=*/false,
                                           /*expand=*/false,
                                           captionFont,
                                           textFont,
440
441
442
443
444
445
446
447
448
                                           (*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) {
449
            if (relations.isEmpty() || (*it)->type() != KCalendarCore::Incidence::TypeTodo) {
Laurent Montel's avatar
Laurent Montel committed
450
451
452
453
454
455
456
457
                int notesPosition = drawBoxWithCaption(p,
                                                       notesBox,
                                                       i18n("Notes:"),
                                                       QString(),
                                                       /*sameLine=*/false,
                                                       /*expand=*/false,
                                                       captionFont,
                                                       textFont);
458
459
460
                drawNoteLines(p, notesBox, notesPosition);
            } else {
                QString subitemCaption;
Laurent Montel's avatar
Laurent Montel committed
461
                if (relations.isEmpty()) {
462
463
464
                    subitemCaption = i18n("No Subitems");
                    txt.clear();
                } else {
Laurent Montel's avatar
Laurent Montel committed
465
                    subitemCaption = i18np("1 Subitem:", "%1 Subitems:", relations.count());
466
467
468
469
470
471
                }

                QString subitemString;
                QString statusString;
                QString datesString;
                int count = 0;
Laurent Montel's avatar
Laurent Montel committed
472
                for (const Akonadi::Item &item : qAsConst(relations)) {
473
                    KCalendarCore::Todo::Ptr todo = CalendarSupport::todo(item);
474
                    ++count;
Laurent Montel's avatar
Laurent Montel committed
475
                    if (!todo) { // defensive, skip any zero pointers
476
477
478
479
480
                        continue;
                    }
                    // format the status
                    statusString = KCalUtils::Stringify::incidenceStatus(todo->status());
                    if (statusString.isEmpty()) {
481
                        if (todo->status() == KCalendarCore::Incidence::StatusNone) {
482
483
484
485
486
487
488
489
                            statusString = i18nc("no status", "none");
                        } else {
                            statusString = i18nc("unknown status", "unknown");
                        }
                    }
                    // format the dates if provided
                    datesString.clear();
                    if (todo->dtStart().isValid()) {
Laurent Montel's avatar
Laurent Montel committed
490
491
                        datesString +=
                            i18nc("subitem start date", "Start Date: %1\n", QLocale().toString(todo->dtStart().toLocalTime().date(), QLocale::ShortFormat));
492
                        if (!todo->allDay()) {
Laurent Montel's avatar
Laurent Montel committed
493
494
                            datesString +=
                                i18nc("subitem start time", "Start Time: %1\n", QLocale().toString(todo->dtStart().toLocalTime().time(), QLocale::ShortFormat));
495
496
                        }
                    }
497
                    if (todo->dateTime(KCalendarCore::Incidence::RoleEnd).isValid()) {
Laurent Montel's avatar
Laurent Montel committed
498
499
500
501
                        subitemString +=
                            i18nc("subitem due date",
                                  "Due Date: %1\n",
                                  QLocale().toString(todo->dateTime(KCalendarCore::Incidence ::RoleEnd).toLocalTime().date(), QLocale::ShortFormat));
502
503

                        if (!todo->allDay()) {
Laurent Montel's avatar
Laurent Montel committed
504
505
506
507
                            subitemString +=
                                i18nc("subitem due time",
                                      "Due Time: %1\n",
                                      QLocale().toString(todo->dateTime(KCalendarCore::Incidence::RoleEnd).toLocalTime().time(), QLocale::ShortFormat));
508
509
510
511
512
513
514
515
516
                        }
                    }
                    subitemString += i18nc("subitem counter", "%1: ", count);
                    subitemString += todo->summary();
                    subitemString += QLatin1Char('\n');
                    if (!datesString.isEmpty()) {
                        subitemString += datesString;
                        subitemString += QLatin1Char('\n');
                    }
Laurent Montel's avatar
Laurent Montel committed
517
518
519
520
                    subitemString += i18nc("subitem Status: statusString", "Status: %1\n", statusString);
                    subitemString += KCalUtils::IncidenceFormatter::recurrenceString(todo) + QLatin1Char('\n');
                    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()));
521
522
                    subitemString += QLatin1Char('\n');
                }
Laurent Montel's avatar
Laurent Montel committed
523
524
525
526
527
528
529
530
                drawBoxWithCaption(p,
                                   notesBox,
                                   subitemCaption,
                                   subitemString,
                                   /*sameLine=*/false,
                                   /*expand=*/false,
                                   captionFont,
                                   textFont);
531
532
533
534
            }
        }

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

        if (mShowOptions) {
            QString optionsString;
            if (!KCalUtils::Stringify::incidenceStatus((*it)->status()).isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
596
                optionsString += i18n("Status: %1", KCalUtils::Stringify::incidenceStatus((*it)->status()));
597
598
599
                optionsString += QLatin1Char('\n');
            }
            if (!KCalUtils::Stringify::incidenceSecrecy((*it)->secrecy()).isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
600
                optionsString += i18n("Secrecy: %1", KCalUtils::Stringify::incidenceSecrecy((*it)->secrecy()));
601
602
                optionsString += QLatin1Char('\n');
            }
603
604
605
            if ((*it)->type() == KCalendarCore::Incidence::TypeEvent) {
                KCalendarCore::Event::Ptr e = (*it).staticCast<KCalendarCore::Event>();
                if (e->transparency() == KCalendarCore::Event::Opaque) {
606
607
608
609
610
                    optionsString += i18n("Show as: Busy");
                } else {
                    optionsString += i18n("Show as: Free");
                }
                optionsString += QLatin1Char('\n');
611
612
            } else if ((*it)->type() == KCalendarCore::Incidence::TypeTodo) {
                KCalendarCore::Todo::Ptr t = (*it).staticCast<KCalendarCore::Todo>();
613
614
615
616
                if (t->isOverdue()) {
                    optionsString += i18n("This task is overdue!");
                    optionsString += QLatin1Char('\n');
                }
617
            } else if ((*it)->type() == KCalendarCore::Incidence::TypeJournal) {
Laurent Montel's avatar
Laurent Montel committed
618
                // TODO: Anything Journal-specific?
619
            }
Laurent Montel's avatar
Laurent Montel committed
620
            drawBoxWithCaption(p, optionsBox, i18n("Settings: "), optionsString, /*sameLine=*/false, /*expand=*/false, captionFont, textFont);
621
622
        }

Laurent Montel's avatar
Laurent Montel committed
623
624
        drawBoxWithCaption(p,
                           categoriesBox,
625
626
                           i18n("Tags: "),
                           (*it)->categories().join(i18nc("Spacer for the joined list of categories/tags", ", ")),
Laurent Montel's avatar
Laurent Montel committed
627
628
629
630
                           /*sameLine=*/true,
                           /*expand=*/false,
                           captionFont,
                           textFont);
631
632
633
634
635
636
637
638
639
640
641
642

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

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

Laurent Montel's avatar
Laurent Montel committed
643
644
CalPrintDay::CalPrintDay()
    : CalPrintPluginBase()
645
646
647
648
649
650
651
652
653
654
655
656
657
658
{
}

CalPrintDay::~CalPrintDay()
{
}

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

void CalPrintDay::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
659
    auto cfg = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
    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();
677
        mIncludeCategories = cfg->mIncludeCategories->isChecked();
678
679
680
681
682
683
684
685
686
687
688
689
690
        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()
{
Laurent Montel's avatar
Laurent Montel committed
691
    auto cfg = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
692
693
694
695
696
697
698
699
700
701
702
703
704
    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);
705
        cfg->mIncludeCategories->setChecked(mIncludeCategories);
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
        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);
728
        mIncludeCategories = grp.readEntry("Include categories", false);
729
730
        mIncludeTodos = grp.readEntry("Include todos", false);
        mIncludeAllEvents = grp.readEntry("Include all events", false);
Laurent Montel's avatar
Laurent Montel committed
731
        mDayPrintType = static_cast<eDayPrintType>(grp.readEntry("Print type", static_cast<int>(Timetable)));
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
        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);
752
        grp.writeEntry("Include categories", mIncludeCategories);
753
754
755
756
757
758
759
760
761
762
763
764
765
766
        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
767
    auto cfg = dynamic_cast<CalPrintDayConfig *>((QWidget *)mConfigWidget);
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
    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
786
    case SingleTimetable: {
787
788
789
790
791
792
        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;
793
        if (orientation() == QPageLayout::Landscape) {
794
795
796
797
798
799
            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) {
Laurent Montel's avatar
Laurent Montel committed
800
801
802
803
804
805
806
807
808
            drawDays(p,
                     mFromDate,
                     mToDate,
                     mStartTime,
                     mEndTime,
                     daysBox,
                     mSingleLineLimit,
                     mShowNoteLines,
                     mIncludeDescription,
809
810
                     mIncludeCategories,
                     mUseColors,
Laurent Montel's avatar
Laurent Montel committed
811
812
                     mExcludeConfidential,
                     mExcludePrivate);
813
        } else if (mDayPrintType == SingleTimetable) {
Laurent Montel's avatar
Laurent Montel committed
814
815
816
817
818
819
820
821
            drawTimeTable(p,
                          mFromDate,
                          mToDate,
                          mIncludeAllEvents,
                          mStartTime,
                          mEndTime,
                          daysBox,
                          mIncludeDescription,
822
                          mIncludeCategories,
Laurent Montel's avatar
Laurent Montel committed
823
824
                          mExcludeTime,
                          mExcludeConfidential,
825
826
827
828
829
                          mExcludePrivate);
        }
        if (mPrintFooter) {
            drawFooter(p, footerBox);
        }
Laurent Montel's avatar
Laurent Montel committed
830
        break;
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
    }

    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);
Laurent Montel's avatar
Laurent Montel committed
847
848
            KCalendarCore::Event::List eventList =
                mCalendar->events(curDay, QTimeZone::systemTimeZone(), KCalendarCore::EventSortStartDate, KCalendarCore::SortDirectionAscending);
849
850

            // split out the all day events as they will be printed in a separate box
851
852
            KCalendarCore::Event::List alldayEvents, timedEvents;
            for (const KCalendarCore::Event::Ptr &event : qAsConst(eventList)) {
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
                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());
Laurent Montel's avatar
Laurent Montel committed
868
            QRect allDayBox(TIMELINE_WIDTH + padding(), headerBox.bottom() + padding(), width - TIMELINE_WIDTH - padding(), allDayHeight);
Laurent Montel's avatar
Laurent Montel committed
869
            if (!alldayEvents.isEmpty()) {
870
871
872
873
874
                // 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
875
                                QRect(0, headerBox.bottom() + padding(), TIMELINE_WIDTH, allDayHeight),
876
877
878
879
880
881
882
883
884
885
886
887
                                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;
888
                for (const KCalendarCore::Event::Ptr &event : qAsConst(alldayEvents)) {
889
890
891
892
893
894
                    if (count == maxAllDayEvents) {
                        break;
                    }
                    count++;
                    QString str;
                    if (event->location().isEmpty()) {
895
                        str = cleanString(event->summary());
896
                    } else {
Laurent Montel's avatar
Laurent Montel committed
897
                        str = i18nc("summary, location", "%1, %2", cleanString(event->summary()), cleanString(event->location()));
898
                    }
899
900
901
                    if (mIncludeCategories && !event->categoriesStr().isEmpty()) {
                            str = i18nc("summary, categories", "%1, %2", str, cleanString(event->categoriesStr()));
                    }
902
903
904
905
906
907
908
909
910
911
912
913
                    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);
Laurent Montel's avatar
Laurent Montel committed
914
915
916
917
918
919
920
921
            drawAgendaDayBox(p,
                             timedEvents,
                             curDay,
                             mIncludeAllEvents,
                             curStartTime,
                             curEndTime,
                             dayBox,
                             mIncludeDescription,
922
                             mIncludeCategories,
Laurent Montel's avatar
Laurent Montel committed
923
924
925
                             mExcludeTime,
                             mExcludeConfidential,
                             mExcludePrivate,
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
                             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);
Laurent Montel's avatar
Laurent Montel committed
942
    } // switch
943
944
945
946
947
948
}

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

Laurent Montel's avatar
Laurent Montel committed
949
950
CalPrintWeek::CalPrintWeek()
    : CalPrintPluginBase()
951
952
953
954
955
956
957
958
959
960
961
962
963
964
{
}

CalPrintWeek::~CalPrintWeek()
{
}

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

void CalPrintWeek::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
965
    auto cfg = dynamic_cast<CalPrintWeekConfig *>((QWidget *)mConfigWidget);
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
    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();
989
        mIncludeCategories = cfg->mIncludeCategories->isChecked();
990
991
992
993
994
995
996
997
        mExcludeTime = cfg->mExcludeTime->isChecked();
        mExcludeConfidential = cfg->mExcludeConfidential->isChecked();
        mExcludePrivate = cfg->mExcludePrivate->isChecked();
    }
}

void CalPrintWeek::setSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
998
    auto cfg = dynamic_cast<CalPrintWeekConfig *>((QWidget *)mConfigWidget);
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
    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);
        cfg->mPrintFooter->setChecked(mPrintFooter);
        cfg->mIncludeDescription->setChecked(mIncludeDescription);
1016
        cfg->mIncludeCategories->setChecked(mIncludeCategories);
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
        cfg->mExcludeTime->setChecked(mExcludeTime);
        cfg->mExcludeConfidential->setChecked(mExcludeConfidential);
        cfg->mExcludePrivate->setChecked(mExcludePrivate);
    }
}

void CalPrintWeek::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(43200));
        mStartTime = grp.readEntry("Start time", startTm).time();
        mEndTime = grp.readEntry("End time", endTm).time();
        mShowNoteLines = grp.readEntry("Note Lines", false);
        mSingleLineLimit = grp.readEntry("Single line limit", false);
        mIncludeTodos = grp.readEntry("Include todos", false);
        mWeekPrintType = (eWeekPrintType)(grp.readEntry("Print type", (int)Filofax));
        mIncludeDescription = grp.readEntry("Include Description", false);
1038
        mIncludeCategories = grp.readEntry("Include categories", false);
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
        mExcludeTime = grp.readEntry("Exclude Time", false);
        mExcludeConfidential = grp.readEntry("Exclude confidential", true);
        mExcludePrivate = grp.readEntry("Exclude private", true);
    }
    setSettingsWidget();
}

void CalPrintWeek::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("Note Lines", mShowNoteLines);
        grp.writeEntry("Single line limit", mSingleLineLimit);
        grp.writeEntry("Include todos", mIncludeTodos);
        grp.writeEntry("Print type", int(mWeekPrintType));
        grp.writeEntry("Include Description", mIncludeDescription);
1061
        grp.writeEntry("Include categories", mIncludeCategories);
1062
1063
1064
1065
1066
1067
        grp.writeEntry("Exclude Time", mExcludeTime);
        grp.writeEntry("Exclude confidential", mExcludeConfidential);
        grp.writeEntry("Exclude private", mExcludePrivate);
    }
}

1068
QPageLayout::Orientation CalPrintWeek::defaultOrientation() const
1069
1070
{
    if (mWeekPrintType == Filofax) {
1071
        return QPageLayout::Portrait;
1072
    } else if (mWeekPrintType == SplitWeek) {
1073
        return QPageLayout::Portrait;
1074
    } else {
1075
        return QPageLayout::Landscape;
1076
1077
1078
1079
1080
1081
    }
}

void CalPrintWeek::setDateRange(const QDate &from, const QDate &to)
{
    CalPrintPluginBase::setDateRange(from, to);
Laurent Montel's avatar
Laurent Montel committed
1082
    auto cfg = dynamic_cast<CalPrintWeekConfig *>((QWidget *)mConfigWidget);
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
    if (cfg) {
        cfg->mFromDate->setDate(from);
        cfg->mToDate->setDate(to);
    }
}

void CalPrintWeek::print(QPainter &p, int width, int height)
{
    QDate curWeek, fromWeek, toWeek;

    // correct begin and end to first and last day of week
    int weekdayCol = weekdayColumn(mFromDate.dayOfWeek());
    fromWeek = mFromDate.addDays(-weekdayCol);
    weekdayCol = weekdayColumn(mToDate.dayOfWeek());
    toWeek = mToDate.addDays(6 - weekdayCol);

    curWeek = fromWeek.addDays(6);
    auto local = QLocale::system();

    QString line1, line2, title;
    QRect headerBox(0, 0, width, headerHeight());
    QRect footerBox(0, height - footerHeight(), width, footerHeight());
    height -= footerHeight();

    QRect weekBox(headerBox);
    weekBox.setTop(headerBox.bottom() + padding());
    weekBox.setBottom(height);

    switch (mWeekPrintType) {
    case Filofax:
        do {
            line1 = local.toString(curWeek.addDays(-6), QLocale::ShortFormat);
            line2 = local.toString(curWeek, QLocale::ShortFormat);
1116
            if (orientation() == QPageLayout::Landscape) {
1117
1118
1119
1120
1121
1122
                title = i18nc("date from-to", "%1 - %2", line1, line2);
            } else {
                title = i18nc("date from-\nto", "%1 -\n%2", line1, line2);
            }
            drawHeader(p, title, curWeek.addDays(-6), QDate(), headerBox);

1123
1124
            drawWeek(p, curWeek, mStartTime, mEndTime, weekBox, mSingleLineLimit, mShowNoteLines,
                      mIncludeDescription, mIncludeCategories, mUseColors, mExcludeConfidential, mExcludePrivate);
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141

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

            curWeek = curWeek.addDays(7);
            if (curWeek <= toWeek) {
                mPrinter->newPage();
            }
        } while (curWeek <= toWeek);
        break;

    case Timetable:
    default:
        do {
            line1 = local.toString(curWeek.addDays(-6), QLocale::ShortFormat);
            line2 = local.toString(curWeek, QLocale::ShortFormat);
1142
            if (orientation() == QPageLayout::Landscape) {
Laurent Montel's avatar
Laurent Montel committed
1143
                title = i18nc("date from - to (week number)", "%1 - %2 (Week %3)", line1, line2, curWeek.weekNumber());
1144
            } else {
Laurent Montel's avatar
Laurent Montel committed
1145
                title = i18nc("date from -\nto (week number)", "%1 -\n%2 (Week %3)", line1, line2, curWeek.weekNumber());
1146
1147
1148
            }
            drawHeader(p, title, curWeek, QDate(), headerBox);

1149
1150
            drawTimeTable(p, fromWeek, curWeek, false, mStartTime, mEndTime, weekBox, mIncludeDescription,
                           mIncludeCategories, mExcludeTime, mExcludeConfidential, mExcludePrivate);
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163

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

            fromWeek = fromWeek.addDays(7);
            curWeek = fromWeek.addDays(6);
            if (curWeek <= toWeek) {
                mPrinter->newPage();
            }
        } while (curWeek <= toWeek);
        break;

Laurent Montel's avatar
Laurent Montel committed
1164
    case SplitWeek: {
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
        QRect weekBox1(weekBox);
        // On the left side there are four days (mo-th) plus the timeline,
        // on the right there are only three days (fr-su) plus the timeline. Don't
        // use the whole width, but rather give them the same width as on the left.
        weekBox1.setRight(int((width - TIMELINE_WIDTH) * 3. / 4. + TIMELINE_WIDTH));
        do {
            QDate endLeft(fromWeek.addDays(3));
            int hh = headerHeight();

            drawSplitHeaderRight(p, fromWeek, curWeek, QDate(), width, hh);
1175
1176
            drawTimeTable(p, fromWeek, endLeft, false, mStartTime, mEndTime, weekBox, mIncludeDescription,
                           mIncludeCategories, mExcludeTime, mExcludeConfidential, mExcludePrivate);
1177
1178
1179
1180
1181
            if (mPrintFooter) {
                drawFooter(p, weekBox1);
            }
            mPrinter->newPage();
            drawSplitHeaderRight(p, fromWeek, curWeek, QDate(), width, hh);
Laurent Montel's avatar
Laurent Montel committed
1182
1183
1184
1185
1186
1187
1188
1189
            drawTimeTable(p,
                          endLeft.addDays(1),
                          curWeek,
                          false,
                          mStartTime,
                          mEndTime,
                          weekBox1,
                          mIncludeDescription,
1190
                          mIncludeCategories,
Laurent Montel's avatar
Laurent Montel committed
1191
1192
1193
                          mExcludeTime,
                          mExcludeConfidential,
                          mExcludePrivate);
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204

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

            fromWeek = fromWeek.addDays(7);
            curWeek = fromWeek.addDays(6);
            if (curWeek <= toWeek) {
                mPrinter->newPage();
            }
        } while (curWeek <= toWeek);
Laurent Montel's avatar
Laurent Montel committed
1205
        break;
1206
1207
1208
1209
1210
1211
1212
1213
    }
    }
}

/**************************************************************
 *           Print Month
 **************************************************************/

Laurent Montel's avatar
Laurent Montel committed
1214
1215
CalPrintMonth::CalPrintMonth()
    : CalPrintPluginBase()
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
{
}

CalPrintMonth::~CalPrintMonth()
{
}

QWidget *CalPrintMonth::createConfigWidget(QWidget *w)
{
    return new CalPrintMonthConfig(w);
}

void CalPrintMonth::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
1230
    auto cfg = dynamic_cast<CalPrintMonthConfig *>((QWidget *)mConfigWidget);
1231
1232
1233
1234
1235

    if (cfg) {
        mFromDate = QDate(cfg->mFromYear->value(), cfg->mFromMonth->currentIndex() + 1, 1);
        mToDate = QDate(cfg->mToYear->value(), cfg->mToMonth->currentIndex() + 1, 1);

Laurent Montel's avatar
Laurent Montel committed
1236
        mWeekNumbers = cfg->mWeekNumbers->isChecked();
1237
1238
1239
1240
1241
1242
1243
1244
        mRecurDaily = cfg->mRecurDaily->isChecked();
        mRecurWeekly = cfg->mRecurWeekly->isChecked();
        mIncludeTodos = cfg->mIncludeTodos->isChecked();
        mShowNoteLines = cfg->mShowNoteLines->isChecked();
        mSingleLineLimit = cfg->mSingleLineLimit->isChecked();
        mUseColors = cfg->mColors->isChecked();
        mPrintFooter = cfg->mPrintFooter->isChecked();
        mIncludeDescription = cfg->mIncludeDescription->isChecked();
1245
        mIncludeCategories = cfg->mIncludeCategories->isChecked();
1246
1247
1248
1249
1250
1251
1252
        mExcludeConfidential = cfg->mExcludeConfidential->isChecked();
        mExcludePrivate = cfg->mExcludePrivate->isChecked();
    }
}

void CalPrintMonth::setSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
1253
    auto cfg = dynamic_cast<CalPrintMonthConfig *>((QWidget *)mConfigWidget);
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266

    if (cfg) {
        setDateRange(mFromDate, mToDate);

        cfg->mWeekNumbers->setChecked(mWeekNumbers);
        cfg->mRecurDaily->setChecked(mRecurDaily);
        cfg->mRecurWeekly->setChecked(mRecurWeekly);
        cfg->mIncludeTodos->setChecked(mIncludeTodos);
        cfg->mShowNoteLines->setChecked(mShowNoteLines);
        cfg->mSingleLineLimit->setChecked(mSingleLineLimit);
        cfg->mColors->setChecked(mUseColors);
        cfg->mPrintFooter->setChecked(mPrintFooter);
        cfg->mIncludeDescription->setChecked(mIncludeDescription);
1267
        cfg->mIncludeCategories->setChecked(mIncludeCategories);
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
        cfg->mExcludeConfidential->setChecked(mExcludeConfidential);
        cfg->mExcludePrivate->setChecked(mExcludePrivate);
    }
}

void CalPrintMonth::loadConfig()
{
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        mWeekNumbers = grp.readEntry("Print week numbers", true);
        mRecurDaily = grp.readEntry("Print daily incidences", true);
        mRecurWeekly = grp.readEntry("Print weekly incidences", true);
        mIncludeTodos = grp.readEntry("Include todos", false);
        mSingleLineLimit = grp.readEntry("Single line limit", false);
        mShowNoteLines = grp.readEntry("Note Lines", false);
        mIncludeDescription = grp.readEntry("Include description", false);
1284
        mIncludeCategories = grp.readEntry("Include categories", false);
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
        mExcludeConfidential = grp.readEntry("Exclude confidential", true);
        mExcludePrivate = grp.readEntry("Exclude private", true);
    }
    setSettingsWidget();
}

void CalPrintMonth::saveConfig()
{
    readSettingsWidget();
    if (mConfig) {
        KConfigGroup grp(mConfig, groupName());
        grp.writeEntry("Print week numbers", mWeekNumbers);
        grp.writeEntry("Print daily incidences", mRecurDaily);
        grp.writeEntry("Print weekly incidences", mRecurWeekly);
        grp.writeEntry("Include todos", mIncludeTodos);
        grp.writeEntry("Single line limit", mSingleLineLimit);
        grp.writeEntry("Note Lines", mShowNoteLines);
        grp.writeEntry("Include description", mIncludeDescription);
1303
        grp.writeEntry("Include categories", mIncludeCategories);
1304
1305
1306
1307
1308
1309
1310
1311
        grp.writeEntry("Exclude confidential", mExcludeConfidential);
        grp.writeEntry("Exclude private", mExcludePrivate);
    }
}

void CalPrintMonth::setDateRange(const QDate &from, const QDate &to)
{
    CalPrintPluginBase::setDateRange(from, to);
Laurent Montel's avatar
Laurent Montel committed
1312
    auto cfg = dynamic_cast<CalPrintMonthConfig *>((QWidget *)mConfigWidget);
1313
    if (cfg) {
1314
        cfg->mFromMonth->clear();
1315
1316
        for (int i = 0; i < 12; ++i) {
            cfg->mFromMonth->addItem(QLocale().monthName(i + 1, QLocale::LongFormat));
1317
1318
        }
        cfg->mToMonth->clear();
1319
1320
        for (int i = 0; i < 12; ++i) {
            cfg->mToMonth->addItem(QLocale().monthName(i + 1, QLocale::LongFormat));
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
        }
        cfg->mFromMonth->setCurrentIndex(from.month() - 1);
        cfg->mFromYear->setValue(to.year());
        cfg->mToMonth->setCurrentIndex(mToDate.month() - 1);
        cfg->mToYear->setValue(mToDate.year());
    }
}

void CalPrintMonth::print(QPainter &p, int width, int height)
{
    QDate curMonth, fromMonth, toMonth;

    fromMonth = mFromDate.addDays(-(mFromDate.day() - 1));
    toMonth = mToDate.addDays(mToDate.daysInMonth() - mToDate.day());

    curMonth = fromMonth;

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

    QRect monthBox(0, 0, width, height);
    monthBox.setTop(headerBox.bottom() + padding());

    do {
Laurent Montel's avatar
Laurent Montel committed
1346
        QString title(i18nc("monthname year", "%1 %2", QLocale::system().monthName(curMonth.month()), QString::number(curMonth.year())));
1347
1348
1349
1350
        QDate tmp(fromMonth);
        int weekdayCol = weekdayColumn(tmp.dayOfWeek());
        tmp = tmp.addDays(-weekdayCol);

Laurent Montel's avatar
Laurent Montel committed
1351
        drawHeader(p, title, curMonth.addMonths(-1), curMonth.addMonths(1), headerBox);
1352
        drawMonthTable(p,
Laurent Montel's avatar
Laurent Montel committed
1353
1354
1355
                       curMonth,
                       QTime(),
                       QTime(),
1356
                       mWeekNumbers,
Laurent Montel's avatar
Laurent Montel committed
1357
1358
1359
1360
1361
                       mRecurDaily,
                       mRecurWeekly,
                       mSingleLineLimit,
                       mShowNoteLines,
                       mIncludeDescription,
1362
1363
                       mIncludeCategories,
                       mUseColors,
Laurent Montel's avatar
Laurent Montel committed
1364
1365
1366
                       mExcludeConfidential,
                       mExcludePrivate,
                       monthBox);
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382

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

        curMonth = curMonth.addDays(curMonth.daysInMonth());
        if (curMonth <= toMonth) {
            mPrinter->newPage();
        }
    } while (curMonth <= toMonth);
}

/**************************************************************
 *           Print Todos
 **************************************************************/

Laurent Montel's avatar
Laurent Montel committed
1383
1384
CalPrintTodos::CalPrintTodos()
    : CalPrintPluginBase()
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
{
    mTodoSortField = TodoFieldUnset;
    mTodoSortDirection = TodoDirectionUnset;
}

CalPrintTodos::~CalPrintTodos()
{
}

QWidget *CalPrintTodos::createConfigWidget(QWidget *w)
{
    return new CalPrintTodoConfig(w);
}

void CalPrintTodos::readSettingsWidget()
{
Laurent Montel's avatar
Laurent Montel committed
1401
    auto cfg = dynamic_cast<CalPrintTodoConfig *>((QWidget *)mConfigWidget);
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420

    if (cfg) {
        mPageTitle = cfg->mTitle->text();

        if (cfg->mPrintAll->isChecked()) {
            mTodoPrintType = TodosAll;
        } else if (cfg->mPrintUnfinished->isChecked()) {
            mTodoPrintType = TodosUnfinished;
        } else if (cfg->mPrintDueRange->isChecked()) {
            mTodoPrintType = TodosDueRange;
        } else {
            mTodoPrintType = TodosAll;
        }

        mFromDate = cfg->mFromDate->date();
        mToDate = cfg->mToDate->date();

        mIncludeDescription = cfg->mDescription->isChecked();
        mIncludePriority = cfg->mPriority->isChecked();
1421
1422
        mIncludeCategories = cfg->mCategories->isChecked();
        mIncludeStartDate = cfg->mStartDate->isChecked();
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
        mIncludeDueDate = cfg->mDueDate->isChecked();
        mIncludePercentComplete = cfg->mPercentComplete->isChecked();
        mConnectSubTodos = cfg->mConnectSubTodos->isChecked();
        mStrikeOutCompleted = cfg->mStrikeOutCompleted->isChecked();
        mExcludeConfidential = cfg->mExcludeConfidential->isChecked();
        mExcludePrivate = cfg->mExcludePrivate->isChecked();

        mTodoSortField = (eTodoSortField)cfg->mSortField->currentIndex();
        mTodoSortDirection = (eTodoSortDirection)cfg->mSortDirection->