summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/android/androidjnimenu.cpp
blob: 8f41d411abd1a399ded62a132e1e97a3a428a164 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
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
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
329
330
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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
432
433
434
435
/****************************************************************************
**
** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "androidjnimenu.h"
#include "androidjnimain.h"
#include "qandroidplatformmenubar.h"
#include "qandroidplatformmenu.h"
#include "qandroidplatformmenuitem.h"

#include <QMutex>
#include <QSet>
#include <QQueue>
#include <QWindow>

QT_BEGIN_NAMESPACE

using namespace QtAndroid;

namespace QtAndroidMenu
{
    static QQueue<QAndroidPlatformMenu *> pendingContextMenus;
    static QAndroidPlatformMenu *visibleMenu = 0;
    static QMutex visibleMenuMutex(QMutex::Recursive);

    static QSet<QAndroidPlatformMenuBar *> menuBars;
    static QAndroidPlatformMenuBar *visibleMenuBar = 0;
    static QWindow *activeTopLevelWindow = 0;
    static QMutex menuBarMutex(QMutex::Recursive);

    static jmethodID openContextMenuMethodID = 0;
    static jmethodID closeContextMenuMethodID = 0;
    static jmethodID resetOptionsMenuMethodID = 0;
    static jmethodID openOptionsMenuMethodID = 0;

    static jmethodID clearMenuMethodID = 0;
    static jmethodID addMenuItemMethodID = 0;
    static int menuNoneValue = 0;
    static jmethodID setHeaderTitleContextMenuMethodID = 0;

    static jmethodID setCheckableMenuItemMethodID = 0;
    static jmethodID setCheckedMenuItemMethodID = 0;
    static jmethodID setEnabledMenuItemMethodID = 0;
    static jmethodID setIconMenuItemMethodID = 0;
    static jmethodID setVisibleMenuItemMethodID = 0;

    void resetMenuBar()
    {
        AttachedJNIEnv env;
        if (env.jniEnv)
            env.jniEnv->CallStaticVoidMethod(applicationClass(), resetOptionsMenuMethodID);
    }

    void openOptionsMenu()
    {
        AttachedJNIEnv env;
        if (env.jniEnv)
            env.jniEnv->CallStaticVoidMethod(applicationClass(), openOptionsMenuMethodID);
    }

    void showContextMenu(QAndroidPlatformMenu *menu, JNIEnv *env)
    {
        QMutexLocker lock(&visibleMenuMutex);
        if (visibleMenu) {
            pendingContextMenus.enqueue(menu);
        } else {
            visibleMenu = menu;
            menu->aboutToShow();
            if (env) {
                env->CallStaticVoidMethod(applicationClass(), openContextMenuMethodID);
            } else {
                AttachedJNIEnv aenv;
                if (aenv.jniEnv)
                    aenv.jniEnv->CallStaticVoidMethod(applicationClass(), openContextMenuMethodID);
            }
        }
    }

    void hideContextMenu(QAndroidPlatformMenu *menu)
    {
        QMutexLocker lock(&visibleMenuMutex);
        if (visibleMenu == menu) {
            AttachedJNIEnv env;
            if (env.jniEnv)
                env.jniEnv->CallStaticVoidMethod(applicationClass(), openContextMenuMethodID);
        } else {
            pendingContextMenus.removeOne(menu);
        }
    }

    void syncMenu(QAndroidPlatformMenu */*menu*/)
    {
//        QMutexLocker lock(&visibleMenuMutex);
//        if (visibleMenu == menu)
//        {
//            hideContextMenu(menu);
//            showContextMenu(menu);
//        }
    }

    void androidPlatformMenuDestroyed(QAndroidPlatformMenu *menu)
    {
        QMutexLocker lock(&visibleMenuMutex);
        if (visibleMenu == menu)
            visibleMenu = 0;
    }

    void setMenuBar(QAndroidPlatformMenuBar *menuBar, QWindow *window)
    {
        if (activeTopLevelWindow == window && visibleMenuBar != menuBar) {
            visibleMenuBar = menuBar;
            resetMenuBar();
        }
    }

    void setActiveTopLevelWindow(QWindow *window)
    {
        Qt::WindowFlags flags = window ? window->flags() : Qt::WindowFlags();
        if (!window)
            return;

        bool isNonRegularWindow = flags & (Qt::Desktop | Qt::Popup | Qt::Dialog | Qt::Sheet) & ~Qt::Window;
        if (isNonRegularWindow)
            return;

        QMutexLocker lock(&menuBarMutex);
        if (activeTopLevelWindow == window)
            return;

        visibleMenuBar = 0;
        activeTopLevelWindow = window;
        foreach (QAndroidPlatformMenuBar *menuBar, menuBars) {
            if (menuBar->parentWindow() == window) {
                visibleMenuBar = menuBar;
                resetMenuBar();
                break;
            }
        }

    }

    void addMenuBar(QAndroidPlatformMenuBar *menuBar)
    {
        QMutexLocker lock(&menuBarMutex);
        menuBars.insert(menuBar);
    }

    void removeMenuBar(QAndroidPlatformMenuBar *menuBar)
    {
        QMutexLocker lock(&menuBarMutex);
        menuBars.remove(menuBar);
        if (visibleMenuBar == menuBar) {
            visibleMenuBar = 0;
            resetMenuBar();
        }
    }

    static QString removeAmpersandEscapes(QString s)
    {
        int i = 0;
        while (i < s.size()) {
            ++i;
            if (s.at(i-1) != QLatin1Char('&'))
                continue;
            if (i < s.size() && s.at(i) == QLatin1Char('&'))
                ++i;
            s.remove(i-1,1);
        }
        return s.trimmed();
    }

    static void fillMenuItem(JNIEnv *env, jobject menuItem, bool checkable, bool checked, bool enabled, bool visible, const QIcon &icon=QIcon())
    {
        env->DeleteLocalRef(env->CallObjectMethod(menuItem, setCheckableMenuItemMethodID, checkable));
        env->DeleteLocalRef(env->CallObjectMethod(menuItem, setCheckedMenuItemMethodID, checked));
        env->DeleteLocalRef(env->CallObjectMethod(menuItem, setEnabledMenuItemMethodID, enabled));

        if (!icon.isNull()) { // isNull() only checks the d pointer, not the actual image data.
            int sz = qMax(36, qgetenv("QT_ANDROID_APP_ICON_SIZE").toInt());
            QImage img = icon.pixmap(QSize(sz,sz),
                                     enabled
                                        ? QIcon::Normal
                                        : QIcon::Disabled,
                                     QIcon::On).toImage();
            if (!img.isNull()) { // Make sure we have a valid image.
                env->DeleteLocalRef(env->CallObjectMethod(menuItem,
                                                          setIconMenuItemMethodID,
                                                          createBitmapDrawable(createBitmap(img, env), env)));
            }
        }

        env->DeleteLocalRef(env->CallObjectMethod(menuItem, setVisibleMenuItemMethodID, visible));
    }

    static int addAllMenuItemsToMenu(JNIEnv *env, jobject menu, QAndroidPlatformMenu *platformMenu) {
         int order = 0;
         QMutexLocker lock(platformMenu->menuItemsMutex());
         foreach (QAndroidPlatformMenuItem *item, platformMenu->menuItems()) {
             if (item->isSeparator())
                 continue;
             QString itemText = removeAmpersandEscapes(item->text());
             jstring jtext = env->NewString(reinterpret_cast<const jchar *>(itemText.data()),
                                           itemText.length());
             jobject menuItem = env->CallObjectMethod(menu,
                                                      addMenuItemMethodID,
                                                      menuNoneValue,
                                                      int(item->tag()),
                                                      order++,
                                                      jtext);
             env->DeleteLocalRef(jtext);
             fillMenuItem(env,
                          menuItem,
                          item->isCheckable(),
                          item->isChecked(),
                          item->isEnabled(),
                          item->isVisible(),
                          item->icon());
             env->DeleteLocalRef(menuItem);
         }

         return order;
    }

    static jboolean onPrepareOptionsMenu(JNIEnv *env, jobject /*thiz*/, jobject menu)
    {
        env->CallVoidMethod(menu, clearMenuMethodID);
        QMutexLocker lock(&menuBarMutex);
        if (!visibleMenuBar)
            return JNI_FALSE;

        const QAndroidPlatformMenuBar::PlatformMenusType &menus = visibleMenuBar->menus();
        int order = 0;
        QMutexLocker lockMenuBarMutex(visibleMenuBar->menusListMutex());
        if (menus.size() == 1) { // Expand the menu
            order = addAllMenuItemsToMenu(env, menu, static_cast<QAndroidPlatformMenu *>(menus.front()));
        } else {
            foreach (QAndroidPlatformMenu *item, menus) {
                QString itemText = removeAmpersandEscapes(item->text());
                jstring jtext = env->NewString(reinterpret_cast<const jchar *>(itemText.data()),
                                               itemText.length());
                jobject menuItem = env->CallObjectMethod(menu,
                                                         addMenuItemMethodID,
                                                         menuNoneValue,
                                                         int(item->tag()),
                                                         order++,
                                                         jtext);
                env->DeleteLocalRef(jtext);

                fillMenuItem(env,
                             menuItem,
                             false,
                             false,
                             item->isEnabled(),
                             item->isVisible(),
                             item->icon());
            }
        }
        return order ? JNI_TRUE : JNI_FALSE;
    }

    static jboolean onOptionsItemSelected(JNIEnv *env, jobject /*thiz*/, jint menuId, jboolean checked)
    {
        QMutexLocker lock(&menuBarMutex);
        if (!visibleMenuBar)
            return JNI_FALSE;

        const QAndroidPlatformMenuBar::PlatformMenusType &menus = visibleMenuBar->menus();
        if (menus.size() == 1) { // Expanded menu
            QAndroidPlatformMenuItem *item = static_cast<QAndroidPlatformMenuItem *>(menus.front()->menuItemForTag(menuId));
            if (item) {
                if (item->menu()) {
                    showContextMenu(item->menu(), env);
                } else {
                    if (item->isCheckable())
                        item->setChecked(checked);
                    item->activated();
                }
            }
        } else {
            QAndroidPlatformMenu *menu = static_cast<QAndroidPlatformMenu *>(visibleMenuBar->menuForTag(menuId));
            if (menu)
                showContextMenu(menu, env);
        }

        return JNI_TRUE;
    }

    static void onOptionsMenuClosed(JNIEnv */*env*/, jobject /*thiz*/, jobject /*menu*/)
    {
    }

    static void onCreateContextMenu(JNIEnv *env, jobject /*thiz*/, jobject menu)
    {
        env->CallVoidMethod(menu, clearMenuMethodID);
        QMutexLocker lock(&visibleMenuMutex);
        if (!visibleMenu)
            return;

        QString menuText = removeAmpersandEscapes(visibleMenu->text());
        jstring jtext = env->NewString(reinterpret_cast<const jchar*>(menuText.data()),
                                       menuText.length());
        env->CallObjectMethod(menu, setHeaderTitleContextMenuMethodID, jtext);
        env->DeleteLocalRef(jtext);
        addAllMenuItemsToMenu(env, menu, visibleMenu);
    }

    static jboolean onContextItemSelected(JNIEnv *env, jobject /*thiz*/, jint menuId, jboolean checked)
    {
        QMutexLocker lock(&visibleMenuMutex);
        QAndroidPlatformMenuItem * item = static_cast<QAndroidPlatformMenuItem *>(visibleMenu->menuItemForTag(menuId));
        if (item) {
            if (item->menu()) {
                showContextMenu(item->menu(), env);
            } else {
                if (item->isCheckable())
                    item->setChecked(checked);
                item->activated();
            }
        }
        return JNI_TRUE;
    }

    static void onContextMenuClosed(JNIEnv *env, jobject /*thiz*/, jobject /*menu*/)
    {
        QMutexLocker lock(&visibleMenuMutex);
        if (!visibleMenu)
            return;
        visibleMenu->aboutToHide();
        visibleMenu = 0;
        if (!pendingContextMenus.empty())
            showContextMenu(pendingContextMenus.dequeue(), env);
    }

    static JNINativeMethod methods[] = {
        {"onPrepareOptionsMenu", "(Landroid/view/Menu;)Z", (void *)onPrepareOptionsMenu},
        {"onOptionsItemSelected", "(IZ)Z", (void *)onOptionsItemSelected},
        {"onOptionsMenuClosed", "(Landroid/view/Menu;)V", (void*)onOptionsMenuClosed},
        {"onCreateContextMenu", "(Landroid/view/ContextMenu;)V", (void *)onCreateContextMenu},
        {"onContextItemSelected", "(IZ)Z", (void *)onContextItemSelected},
        {"onContextMenuClosed", "(Landroid/view/Menu;)V", (void*)onContextMenuClosed},
    };

#define FIND_AND_CHECK_CLASS(CLASS_NAME) \
    clazz = env->FindClass(CLASS_NAME); \
    if (!clazz) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), classErrorMsgFmt(), CLASS_NAME); \
        return false; \
    }

#define GET_AND_CHECK_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) \
    VAR = env->GetMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); \
    if (!VAR) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), methodErrorMsgFmt(), METHOD_NAME, METHOD_SIGNATURE); \
        return false; \
    }

#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) \
    VAR = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); \
    if (!VAR) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), methodErrorMsgFmt(), METHOD_NAME, METHOD_SIGNATURE); \
        return false; \
    }

#define GET_AND_CHECK_STATIC_FIELD(VAR, CLASS, FIELD_NAME, FIELD_SIGNATURE) \
    VAR = env->GetStaticFieldID(CLASS, FIELD_NAME, FIELD_SIGNATURE); \
    if (!VAR) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), methodErrorMsgFmt(), FIELD_NAME, FIELD_SIGNATURE); \
        return false; \
    }

    bool registerNatives(JNIEnv *env)
    {
        jclass appClass = applicationClass();

        if (env->RegisterNatives(appClass, methods,  sizeof(methods) / sizeof(methods[0])) < 0) {
            __android_log_print(ANDROID_LOG_FATAL,"Qt", "RegisterNatives failed");
            return false;
        }

        GET_AND_CHECK_STATIC_METHOD(openContextMenuMethodID, appClass, "openContextMenu", "()V");
        GET_AND_CHECK_STATIC_METHOD(closeContextMenuMethodID, appClass, "closeContextMenu", "()V");
        GET_AND_CHECK_STATIC_METHOD(resetOptionsMenuMethodID, appClass, "resetOptionsMenu", "()V");
        GET_AND_CHECK_STATIC_METHOD(openOptionsMenuMethodID, appClass, "openOptionsMenu", "()V");

        jclass clazz;
        FIND_AND_CHECK_CLASS("android/view/Menu");
        GET_AND_CHECK_METHOD(clearMenuMethodID, clazz, "clear", "()V");
        GET_AND_CHECK_METHOD(addMenuItemMethodID, clazz, "add", "(IIILjava/lang/CharSequence;)Landroid/view/MenuItem;");
        jfieldID menuNoneFiledId;
        GET_AND_CHECK_STATIC_FIELD(menuNoneFiledId, clazz, "NONE", "I");
        menuNoneValue = env->GetStaticIntField(clazz, menuNoneFiledId);

        FIND_AND_CHECK_CLASS("android/view/ContextMenu");
        GET_AND_CHECK_METHOD(setHeaderTitleContextMenuMethodID, clazz, "setHeaderTitle","(Ljava/lang/CharSequence;)Landroid/view/ContextMenu;");

        FIND_AND_CHECK_CLASS("android/view/MenuItem");
        GET_AND_CHECK_METHOD(setCheckableMenuItemMethodID, clazz, "setCheckable", "(Z)Landroid/view/MenuItem;");
        GET_AND_CHECK_METHOD(setCheckedMenuItemMethodID, clazz, "setChecked", "(Z)Landroid/view/MenuItem;");
        GET_AND_CHECK_METHOD(setEnabledMenuItemMethodID, clazz, "setEnabled", "(Z)Landroid/view/MenuItem;");
        GET_AND_CHECK_METHOD(setIconMenuItemMethodID, clazz, "setIcon", "(Landroid/graphics/drawable/Drawable;)Landroid/view/MenuItem;");
        GET_AND_CHECK_METHOD(setVisibleMenuItemMethodID, clazz, "setVisible", "(Z)Landroid/view/MenuItem;");
        return true;
    }
}

QT_END_NAMESPACE