emojier.cpp 13 KB
Newer Older
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 *  Copyright (C) 2019 Aleix Pol Gonzalez <aleixpol@kde.org>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2 of
 *  the License or (at your option) version 3 or any later version
 *  accepted by the membership of KDE e.V. (or its successor approved
 *  by the membership of KDE e.V.), which shall act as a proxy
 *  defined in Section 14 of version 3 of the license.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QApplication>
#include <QLocale>
#include <QByteArray>
#include <QStandardPaths>
#include <QAbstractListModel>
#include <QVector>
#include <QIcon>
#include <QQmlApplicationEngine>
#include <QSortFilterProxyModel>
#include <QQuickImageProvider>
#include <QCommandLineParser>
#include <QFontMetrics>
#include <QPainter>
#include <QClipboard>
#include <QQuickWindow>
#include <KLocalizedString>
#include <KAboutData>
#include <KQuickAddons/QtQuickSettings>
#include <KCrash>
#include <KDBusService>
41
#include <KWindowConfig>
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
42
#include <QDebug>
43
44
45
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusConnectionInterface>
46
#include <QSessionManager>
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

#include "emojiersettings.h"
#include "config-workspace.h"

#undef signals
#include <ibus.h>

struct Emoji {
    QString content;
    QString description;
    QString category;
};

class TextImageProvider : public QQuickImageProvider
{
public:
    TextImageProvider()
        : QQuickImageProvider(QQuickImageProvider::Pixmap)
    {
    }

    QPixmap requestPixmap(const QString &id, QSize *_size, const QSize &requestedSize) override
    {
        QPixmap dummy;

        const QString renderString = id.mid(1); //drop initial /

        QSize size = requestedSize;
        QFont font;
        if (!size.isValid()) {
            QFontMetrics fm(font, &dummy);
            size = { fm.horizontalAdvance(renderString), fm.height() };
        } else {
            font.setPointSize((requestedSize.height() * 3) / 4);
        }
        if (_size) {
            *_size = size;
        }

        QPixmap pixmap(size.width(), size.height());
        pixmap.fill(Qt::transparent);
        QPainter p;
        p.begin(&pixmap);
        p.setFont(font);
        p.drawText(QRect(0, 0, size.width(), size.height()), Qt::AlignCenter, renderString);
        p.end();
        return pixmap;
    }
};

class AbstractEmojiModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum EmojiRole { CategoryRole = Qt::UserRole + 1 };

    int rowCount(const QModelIndex & parent = {}) const override { return parent.isValid() ? 0 : m_emoji.count(); }
    QVariant data(const QModelIndex & index, int role) const override {
        if (!checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid | QAbstractItemModel::CheckIndexOption::ParentIsInvalid | QAbstractItemModel::CheckIndexOption::DoNotUseParent)  || index.column() != 0)
            return {};

        const auto &emoji = m_emoji[index.row()];
        switch(role) {
            case Qt::DisplayRole:
                return emoji.content;
            case Qt::ToolTipRole:
                return emoji.description;
            case CategoryRole:
                return emoji.category;
        }
        return {};
    }

protected:
    QVector<Emoji> m_emoji;
};

class EmojiModel : public AbstractEmojiModel
{
    Q_OBJECT
    Q_PROPERTY(QStringList categories MEMBER m_categories CONSTANT)
public:
    enum EmojiRole { CategoryRole = Qt::UserRole + 1 };

    EmojiModel() {
        QLocale locale;
133
134
        const auto bcp = locale.bcp47Name();
        const QString dictName = "ibus/dicts/emoji-" + QString(bcp).replace(QLatin1Char('-'), QLatin1Char('_')) + ".dict";
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
135
136
137
138
139
140
        const QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, dictName);
        if (path.isEmpty()) {
            qWarning() << "could not find" << dictName;
            return;
        }

141
142
143
144
145
146
147
148
        const QString genericDictName = "ibus/dicts/emoji-" + bcp.left(bcp.indexOf(QLatin1Char('-'))) + ".dict";
        const QString genericPath = QStandardPaths::locate(QStandardPaths::GenericDataLocation, genericDictName);

        QVector<QString> dicts = {path};
        if (!genericPath.isEmpty()) {
            dicts << genericPath;
        }

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
149
        QSet<QString> categories;
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        QSet<QString> processedEmoji;
        for (const auto &dictPath : qAsConst(dicts)) {
            GSList *list = ibus_emoji_data_load (dictPath.toUtf8().constData());
            m_emoji.reserve(g_slist_length(list));
            for (GSList *l = list; l; l = l->next) {
                IBusEmojiData *data = (IBusEmojiData *) l->data;
                if (!IBUS_IS_EMOJI_DATA (data)) {
                    qWarning() << "Your dict format is no longer supported.\n"
                                "Need to create the dictionaries again.";
                    g_slist_free (list);
                    return;
                }

                const QString emoji = QString::fromUtf8(ibus_emoji_data_get_emoji(data));
                const QString description = ibus_emoji_data_get_description(data);
                qDebug() << "ooo" << dictPath << emoji << description << processedEmoji.contains(emoji);
                if (description == QString::fromUtf8("↑↑↑") || description.isEmpty() || processedEmoji.contains(emoji)) {
                    continue;
                }

                const QString category = QString::fromUtf8(ibus_emoji_data_get_category(data));
                categories.insert(category);
                m_emoji += { emoji, description, category };
                processedEmoji << emoji;
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
174
            }
175
            g_slist_free (list);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
176
        }
177

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
178
        categories.remove({});
179
        m_categories = categories.values();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        m_categories.sort();
        m_categories.prepend({});
        m_categories.prepend(QStringLiteral(":recent:"));
    }

    Q_SCRIPTABLE QString findFirstEmojiForCategory(const QString &category) {
        for (const Emoji &emoji : m_emoji) {
            if (emoji.category == category)
                return emoji.content;
        }
        return {};
    }

private:
    QStringList m_categories;
};

class RecentEmojiModel : public AbstractEmojiModel
{
    Q_OBJECT
    Q_PROPERTY(int count READ rowCount CONSTANT)
public:
    RecentEmojiModel()
    {
204
        refresh();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
205
206
207
    }

    Q_SCRIPTABLE void includeRecent(const QString &emoji, const QString &emojiDescription) {
208
209
210
211
212
213
214
215
        QStringList recent = m_settings.recent();
        QStringList recentDescriptions = m_settings.recentDescriptions();

        const int idx = recent.indexOf(emoji);
        if (idx >= 0) {
            recent.removeAt(idx);
            recentDescriptions.removeAt(idx);
        }
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
216
217
        recent.prepend(emoji);
        recent = recent.mid(0, 50);
218
        m_settings.setRecent(recent);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
219
220
221

        recentDescriptions.prepend(emojiDescription);
        recentDescriptions = recentDescriptions.mid(0, 50);
222
223
        m_settings.setRecentDescriptions(recentDescriptions);
        m_settings.save();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
224

225
        refresh();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
226
227
228
    }

private:
229
230
231
232
233
234
235
236
237
238
239
240
241
242
    void refresh()
    {
        beginResetModel();
        auto recent = m_settings.recent();
        auto recentDescriptions = m_settings.recentDescriptions();
        int i = 0;
        m_emoji.clear();
        for (const QString &c : recent) {
            m_emoji += { c, recentDescriptions.at(i++), QString{} };
        }
        endResetModel();
    }

    EmojierSettings m_settings;
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
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
};

class CategoryModelFilter : public QSortFilterProxyModel
{
    Q_OBJECT
    Q_PROPERTY(QString category READ category WRITE setCategory)
public:
    QString category() const { return m_category; }
    void setCategory(const QString &category) {
        if (m_category != category) {
            m_category = category;
            invalidateFilter();
        }
    }

    bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override {
        return m_category.isEmpty() || sourceModel()->index(source_row, 0, source_parent).data(EmojiModel::CategoryRole).toString() == m_category;
    }

private:
    QString m_category;
};

class SearchModelFilter : public QSortFilterProxyModel
{
    Q_OBJECT
    Q_PROPERTY(QString search READ search WRITE setSearch)
public:
    QString search() const { return m_search; }
    void setSearch(const QString &search) {
        if (m_search != search) {
            m_search = search;
            invalidateFilter();
        }
    }

    bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override {
        return sourceModel()->index(source_row, 0, source_parent).data(Qt::ToolTipRole).toString().contains(m_search, Qt::CaseInsensitive);
    }

private:
    QString m_search;
};

class CopyHelperPrivate : public QObject
{
    Q_OBJECT
    public:
        Q_INVOKABLE static void copyTextToClipboard(const QString& text)
        {
            qGuiApp->clipboard()->setText(text);
        }
};

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
class EngineWatcher : public QObject
{
public:
    EngineWatcher(QQmlApplicationEngine* engine)
        : QObject(engine)
    {
        connect(engine, &QQmlApplicationEngine::objectCreated, this, &EngineWatcher::integrateObject);
    }

    void integrateObject(QObject* object) {
        QWindow* window = qobject_cast<QWindow*>(object);

        auto conf = KSharedConfig::openConfig();
        KWindowConfig::restoreWindowSize(window, conf->group("Window"));

        object->installEventFilter(this);
    }

    bool eventFilter(QObject * object, QEvent * event)
    {
        if (event->type() == QEvent::Close) {
            QWindow* window = qobject_cast<QWindow*>(object);

            auto conf = KSharedConfig::openConfig();
            auto group = conf->group("Window");
            KWindowConfig::saveWindowSize(window, group);
            group.sync();
        }
        return false;
    }
};

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
329
330
int main(int argc, char** argv)
{
331
    QGuiApplication::setFallbackSessionManagementEnabled(false);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
332
333
334
335
336
337
    QApplication app(argc, argv);
    app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);
    app.setWindowIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-emoticons")));
    KCrash::initialize();
    KQuickAddons::QtQuickSettings::init();

338
    KLocalizedString::setApplicationDomain("plasma.emojier");
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
339

340
    KAboutData about(QStringLiteral("plasma.emojier"), i18n("Emoji Picker"), QStringLiteral(WORKSPACE_VERSION_STRING), i18n("Emoji Picker"),
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
341
342
343
344
345
346
347
             KAboutLicense::GPL, i18n("(C) 2019 Aleix Pol i Gonzalez"));
    about.addAuthor( QStringLiteral("Aleix Pol i Gonzalez"), QString(), QStringLiteral("aleixpol@kde.org") );
    about.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));
//     about.setProductName("");
    about.setProgramLogo(app.windowIcon());
    KAboutData::setApplicationData(about);

348
349
350
351
352
353
    auto disableSessionManagement = [](QSessionManager &sm) {
        sm.setRestartHint(QSessionManager::RestartNever);
    };
    QObject::connect(&app, &QGuiApplication::commitDataRequest, disableSessionManagement);
    QObject::connect(&app, &QGuiApplication::saveStateRequest, disableSessionManagement);

354
    KDBusService::StartupOptions startup = nullptr;
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
355
356
    {
        QCommandLineParser parser;
357
358
359
360

        QCommandLineOption replaceOption({QStringLiteral("replace")},
                                 i18n("Replace an existing instance"));
        parser.addOption(replaceOption);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
361
362
363
        about.setupCommandLine(&parser);
        parser.process(app);
        about.processCommandLine(&parser);
364
365

        if (parser.isSet(replaceOption)) {
366
            startup |= KDBusService::Replace;
367
        }
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
368
369
    }

370
    KDBusService* service = new KDBusService(KDBusService::Unique | startup, &app);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
371
372
373
374
375
376
377

    qmlRegisterType<EmojiModel>("org.kde.plasma.emoji", 1, 0, "EmojiModel");
    qmlRegisterType<CategoryModelFilter>("org.kde.plasma.emoji", 1, 0, "CategoryModelFilter");
    qmlRegisterType<SearchModelFilter>("org.kde.plasma.emoji", 1, 0, "SearchModelFilter");
    qmlRegisterType<RecentEmojiModel>("org.kde.plasma.emoji", 1, 0, "RecentEmojiModel");
    qmlRegisterSingletonType<CopyHelperPrivate>("org.kde.plasma.emoji", 1, 0, "CopyHelper", [] (QQmlEngine*, QJSEngine*) -> QObject* { return new CopyHelperPrivate; });

378
379
    QQmlApplicationEngine engine;
    new EngineWatcher(&engine);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
380
    engine.addImageProvider(QLatin1String("text"), new TextImageProvider);
381
    engine.load(QUrl(QStringLiteral("qrc:/ui/emojier.qml")));
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

    QObject::connect(service, &KDBusService::activateRequested, &engine, [&engine](const QStringList &/*arguments*/, const QString &/*workingDirectory*/) {
        for (QObject* object : engine.rootObjects()) {
            auto w = qobject_cast<QQuickWindow*>(object);
            if (!w)
                continue;
            w->setVisible(true);
            w->raise();
        }
    });

    return app.exec();
}

#include "emojier.moc"