File indexing completed on 2024-11-24 04:50:40

0001 // SPDX-FileCopyrightText: 2021 Claudio Cambra <claudio.cambra@gmail.com>
0002 // SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
0003 // SPDX-License-Identifier: LGPL-2.1-or-later
0004 
0005 #include "utils.h"
0006 #include <KLocalizedString>
0007 #include <QDate>
0008 #include <QLocale>
0009 #include <QtMath>
0010 #include <chrono>
0011 
0012 using namespace std::chrono_literals;
0013 
0014 namespace
0015 {
0016 QString numAndUnit(const qint64 seconds)
0017 {
0018     std::chrono::seconds secs{seconds};
0019     if (secs >= 24h * 2) {
0020         // 2 days +
0021         return i18nc("%1 is 2 or more", "%1 days", std::chrono::round<std::chrono::days>(secs).count());
0022     } else if (secs >= 24h) {
0023         return i18n("1 day");
0024     } else if (secs >= (2h)) {
0025         return i18nc("%1 is 2 or mores", "%1 hours", std::chrono::round<std::chrono::hours>(secs).count()); // 2 hours +
0026     } else if (secs >= (1h)) {
0027         return i18n("1 hour");
0028     } else {
0029         return i18n("%1 minutes", std::chrono::round<std::chrono::minutes>(secs).count());
0030     }
0031 };
0032 }
0033 
0034 Utils::Utils(QObject *parent)
0035     : QObject(parent)
0036 {
0037     QTime time;
0038     for (int i = 1; i < 24; i++) {
0039         time.setHMS(i, 0, 0);
0040         m_hourlyViewLocalisedHourLabels.append(QLocale::system().toString(time, QLocale::NarrowFormat));
0041     }
0042 }
0043 
0044 QString Utils::secondsToReminderLabel(const qint64 seconds) const
0045 {
0046     if (seconds < 0) {
0047         return i18n("%1 before start of event", numAndUnit(seconds * -1));
0048     } else if (seconds > 0) {
0049         return i18n("%1 after start of event", numAndUnit(seconds));
0050     } else {
0051         return i18n("On event start");
0052     }
0053 }
0054 
0055 QString Utils::formatSpelloutDuration(const KCalendarCore::Duration &duration, const KFormat &format, const bool allDay)
0056 {
0057     if (duration.asSeconds() == 0) {
0058         return QString();
0059     } else {
0060         if (allDay) {
0061             return format.formatSpelloutDuration(duration.asSeconds() * 1000 + 24 * 60 * 60 * 1000);
0062         } else {
0063             return format.formatSpelloutDuration(duration.asSeconds() * 1000);
0064         }
0065     }
0066 }
0067 
0068 QDateTime Utils::addDaysToDate(const QDateTime &date, const int days)
0069 {
0070     return date.addDays(days);
0071 }
0072 
0073 int Utils::weekNumber(const QDate &date) const
0074 {
0075     return date.weekNumber();
0076 }
0077 
0078 QStringList Utils::hourlyViewLocalisedHourLabels() const
0079 {
0080     return m_hourlyViewLocalisedHourLabels;
0081 }
0082 
0083 #include "moc_utils.cpp"