The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1187 lines
45KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. extern juce::JUCEApplicationBase* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  20. namespace juce
  21. {
  22. //==============================================================================
  23. #if JUCE_PUSH_NOTIFICATIONS && JUCE_MODULE_AVAILABLE_juce_gui_extra
  24. // Returns true if the intent was handled.
  25. extern bool juce_handleNotificationIntent (void*);
  26. extern void juce_firebaseDeviceNotificationsTokenRefreshed (void*);
  27. extern void juce_firebaseRemoteNotificationReceived (void*);
  28. extern void juce_firebaseRemoteMessagesDeleted();
  29. extern void juce_firebaseRemoteMessageSent(void*);
  30. extern void juce_firebaseRemoteMessageSendError (void*, void*);
  31. #endif
  32. #if JUCE_IN_APP_PURCHASES && JUCE_MODULE_AVAILABLE_juce_product_unlocking
  33. extern void juce_inAppPurchaseCompleted (void*);
  34. #endif
  35. #if ! JUCE_DISABLE_NATIVE_FILECHOOSERS
  36. extern void juce_fileChooserCompleted (int, void*);
  37. #endif
  38. extern void juce_contentSharingCompleted (int);
  39. //==============================================================================
  40. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, launchApp, void, (JNIEnv* env, jobject activity,
  41. jstring appFile, jstring appDataDir))
  42. {
  43. setEnv (env);
  44. android.initialise (env, activity, appFile, appDataDir);
  45. DBG (SystemStats::getJUCEVersion());
  46. JUCEApplicationBase::createInstance = &juce_CreateApplication;
  47. initialiseJuce_GUI();
  48. if (JUCEApplicationBase* app = JUCEApplicationBase::createInstance())
  49. {
  50. if (! app->initialiseApp())
  51. exit (app->shutdownApp());
  52. }
  53. else
  54. {
  55. jassertfalse; // you must supply an application object for an android app!
  56. }
  57. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  58. }
  59. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, suspendApp, void, (JNIEnv* env, jobject))
  60. {
  61. setEnv (env);
  62. if (auto* app = JUCEApplicationBase::getInstance())
  63. app->suspended();
  64. }
  65. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, resumeApp, void, (JNIEnv* env, jobject))
  66. {
  67. setEnv (env);
  68. if (auto* app = JUCEApplicationBase::getInstance())
  69. app->resumed();
  70. }
  71. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, quitApp, void, (JNIEnv* env, jobject))
  72. {
  73. setEnv (env);
  74. JUCEApplicationBase::appWillTerminateByForce();
  75. android.shutdown (env);
  76. jclass systemClass = (jclass) env->FindClass ("java/lang/System");
  77. jmethodID exitMethod = env->GetStaticMethodID (systemClass, "exit", "(I)V");
  78. env->CallStaticVoidMethod (systemClass, exitMethod, 0);
  79. }
  80. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, appActivityResult, void, (JNIEnv* env, jobject, jint requestCode, jint resultCode, jobject intentData))
  81. {
  82. setEnv (env);
  83. #if JUCE_IN_APP_PURCHASES && JUCE_MODULE_AVAILABLE_juce_product_unlocking
  84. if (requestCode == 1001)
  85. juce_inAppPurchaseCompleted (intentData);
  86. #endif
  87. #if ! JUCE_DISABLE_NATIVE_FILECHOOSERS
  88. if (requestCode == /*READ_REQUEST_CODE*/42)
  89. juce_fileChooserCompleted (resultCode, intentData);
  90. #endif
  91. if (requestCode == 1003)
  92. juce_contentSharingCompleted (resultCode);
  93. ignoreUnused (intentData, requestCode);
  94. }
  95. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, appNewIntent, void, (JNIEnv* env, jobject, jobject intentData))
  96. {
  97. setEnv (env);
  98. #if JUCE_PUSH_NOTIFICATIONS && JUCE_MODULE_AVAILABLE_juce_gui_extra
  99. if (juce_handleNotificationIntent ((void *)intentData))
  100. return;
  101. // Add other functions processing intents here as needed.
  102. #else
  103. ignoreUnused (intentData);
  104. #endif
  105. }
  106. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  107. JUCE_JNI_CALLBACK (JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME, firebaseInstanceIdTokenRefreshed, void, (JNIEnv* env, jobject /*activity*/, jstring token))
  108. {
  109. setEnv (env);
  110. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  111. juce_firebaseDeviceNotificationsTokenRefreshed (token);
  112. #else
  113. ignoreUnused (token);
  114. #endif
  115. }
  116. JUCE_JNI_CALLBACK (JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME, firebaseRemoteMessageReceived, void, (JNIEnv* env, jobject /*activity*/, jobject remoteMessage))
  117. {
  118. setEnv (env);
  119. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  120. juce_firebaseRemoteNotificationReceived (remoteMessage);
  121. #else
  122. ignoreUnused (remoteMessage);
  123. #endif
  124. }
  125. JUCE_JNI_CALLBACK (JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME, firebaseRemoteMessagesDeleted, void, (JNIEnv* env, jobject /*activity*/))
  126. {
  127. setEnv (env);
  128. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  129. juce_firebaseRemoteMessagesDeleted();
  130. #endif
  131. }
  132. JUCE_JNI_CALLBACK (JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME, firebaseRemoteMessageSent, void, (JNIEnv* env, jobject /*activity*/, jstring messageId))
  133. {
  134. setEnv (env);
  135. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  136. juce_firebaseRemoteMessageSent (messageId);
  137. #else
  138. ignoreUnused (messageId);
  139. #endif
  140. }
  141. JUCE_JNI_CALLBACK (JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME, firebaseRemoteMessageSendError, void, (JNIEnv* env, jobject /*activity*/, jstring messageId, jstring error))
  142. {
  143. setEnv (env);
  144. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  145. juce_firebaseRemoteMessageSendError (messageId, error);
  146. #else
  147. ignoreUnused (messageId, error);
  148. #endif
  149. }
  150. #endif
  151. //==============================================================================
  152. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  153. METHOD (drawBitmap, "drawBitmap", "([IIIFFIIZLandroid/graphics/Paint;)V") \
  154. METHOD (getClipBounds, "getClipBounds", "()Landroid/graphics/Rect;")
  155. DECLARE_JNI_CLASS (CanvasMinimal, "android/graphics/Canvas");
  156. #undef JNI_CLASS_MEMBERS
  157. //==============================================================================
  158. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  159. METHOD (setViewName, "setViewName", "(Ljava/lang/String;)V") \
  160. METHOD (setVisible, "setVisible", "(Z)V") \
  161. METHOD (isVisible, "isVisible", "()Z") \
  162. METHOD (containsPoint, "containsPoint", "(II)Z") \
  163. METHOD (showKeyboard, "showKeyboard", "(Ljava/lang/String;)V") \
  164. METHOD (setSystemUiVisibilityCompat, "setSystemUiVisibilityCompat", "(I)V") \
  165. DECLARE_JNI_CLASS (ComponentPeerView, JUCE_ANDROID_ACTIVITY_CLASSPATH "$ComponentPeerView");
  166. #undef JNI_CLASS_MEMBERS
  167. //==============================================================================
  168. class AndroidComponentPeer : public ComponentPeer,
  169. private Timer
  170. {
  171. public:
  172. AndroidComponentPeer (Component& comp, const int windowStyleFlags)
  173. : ComponentPeer (comp, windowStyleFlags),
  174. fullScreen (false),
  175. navBarsHidden (false),
  176. sizeAllocated (0),
  177. scale ((float) Desktop::getInstance().getDisplays().getMainDisplay().scale)
  178. {
  179. // NB: must not put this in the initialiser list, as it invokes a callback,
  180. // which will fail if the peer is only half-constructed.
  181. view = GlobalRef (android.activity.callObjectMethod (JuceAppActivity.createNewView,
  182. (jboolean) component.isOpaque(),
  183. (jlong) this));
  184. if (isFocused())
  185. handleFocusGain();
  186. }
  187. ~AndroidComponentPeer()
  188. {
  189. if (MessageManager::getInstance()->isThisTheMessageThread())
  190. {
  191. frontWindow = nullptr;
  192. android.activity.callVoidMethod (JuceAppActivity.deleteView, view.get());
  193. }
  194. else
  195. {
  196. struct ViewDeleter : public CallbackMessage
  197. {
  198. ViewDeleter (const GlobalRef& view_) : view (view_) {}
  199. void messageCallback() override
  200. {
  201. android.activity.callVoidMethod (JuceAppActivity.deleteView, view.get());
  202. }
  203. private:
  204. GlobalRef view;
  205. };
  206. (new ViewDeleter (view))->post();
  207. }
  208. view.clear();
  209. }
  210. void* getNativeHandle() const override
  211. {
  212. return (void*) view.get();
  213. }
  214. void setVisible (bool shouldBeVisible) override
  215. {
  216. if (MessageManager::getInstance()->isThisTheMessageThread())
  217. {
  218. view.callVoidMethod (ComponentPeerView.setVisible, shouldBeVisible);
  219. }
  220. else
  221. {
  222. struct VisibilityChanger : public CallbackMessage
  223. {
  224. VisibilityChanger (const GlobalRef& view_, bool shouldBeVisible_)
  225. : view (view_), shouldBeVisible (shouldBeVisible_)
  226. {}
  227. void messageCallback() override
  228. {
  229. view.callVoidMethod (ComponentPeerView.setVisible, shouldBeVisible);
  230. }
  231. GlobalRef view;
  232. bool shouldBeVisible;
  233. };
  234. (new VisibilityChanger (view, shouldBeVisible))->post();
  235. }
  236. }
  237. void setTitle (const String& title) override
  238. {
  239. view.callVoidMethod (ComponentPeerView.setViewName, javaString (title).get());
  240. }
  241. void setBounds (const Rectangle<int>& userRect, bool isNowFullScreen) override
  242. {
  243. Rectangle<int> r = (userRect.toFloat() * scale).toNearestInt();
  244. if (MessageManager::getInstance()->isThisTheMessageThread())
  245. {
  246. fullScreen = isNowFullScreen;
  247. view.callVoidMethod (AndroidView.layout,
  248. r.getX(), r.getY(), r.getRight(), r.getBottom());
  249. }
  250. else
  251. {
  252. class ViewMover : public CallbackMessage
  253. {
  254. public:
  255. ViewMover (const GlobalRef& v, const Rectangle<int>& boundsToUse) : view (v), bounds (boundsToUse) {}
  256. void messageCallback() override
  257. {
  258. view.callVoidMethod (AndroidView.layout,
  259. bounds.getX(), bounds.getY(), bounds.getRight(), bounds.getBottom());
  260. }
  261. private:
  262. GlobalRef view;
  263. Rectangle<int> bounds;
  264. };
  265. (new ViewMover (view, r))->post();
  266. }
  267. }
  268. Rectangle<int> getBounds() const override
  269. {
  270. return (Rectangle<float> (view.callIntMethod (AndroidView.getLeft),
  271. view.callIntMethod (AndroidView.getTop),
  272. view.callIntMethod (AndroidView.getWidth),
  273. view.callIntMethod (AndroidView.getHeight)) / scale).toNearestInt();
  274. }
  275. void handleScreenSizeChange() override
  276. {
  277. ComponentPeer::handleScreenSizeChange();
  278. if (isFullScreen())
  279. setFullScreen (true);
  280. }
  281. Point<float> getScreenPosition() const
  282. {
  283. return Point<float> (view.callIntMethod (AndroidView.getLeft),
  284. view.callIntMethod (AndroidView.getTop)) / scale;
  285. }
  286. Point<float> localToGlobal (Point<float> relativePosition) override
  287. {
  288. return relativePosition + getScreenPosition();
  289. }
  290. Point<float> globalToLocal (Point<float> screenPosition) override
  291. {
  292. return screenPosition - getScreenPosition();
  293. }
  294. void setMinimised (bool /*shouldBeMinimised*/) override
  295. {
  296. // n/a
  297. }
  298. bool isMinimised() const override
  299. {
  300. return false;
  301. }
  302. bool shouldNavBarsBeHidden (bool shouldBeFullScreen) const
  303. {
  304. if (shouldBeFullScreen)
  305. if (Component* kiosk = Desktop::getInstance().getKioskModeComponent())
  306. if (kiosk->getPeer() == this)
  307. return true;
  308. return false;
  309. }
  310. void setNavBarsHidden (bool hidden)
  311. {
  312. enum
  313. {
  314. SYSTEM_UI_FLAG_VISIBLE = 0,
  315. SYSTEM_UI_FLAG_LOW_PROFILE = 1,
  316. SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2,
  317. SYSTEM_UI_FLAG_FULLSCREEN = 4,
  318. SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512,
  319. SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024,
  320. SYSTEM_UI_FLAG_IMMERSIVE = 2048,
  321. SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 4096
  322. };
  323. view.callVoidMethod (ComponentPeerView.setSystemUiVisibilityCompat,
  324. hidden ? (jint) (SYSTEM_UI_FLAG_HIDE_NAVIGATION | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
  325. : (jint) (SYSTEM_UI_FLAG_VISIBLE));
  326. navBarsHidden = hidden;
  327. }
  328. void setFullScreen (bool shouldBeFullScreen) override
  329. {
  330. // updating the nav bar visibility is a bit odd on Android - need to wait for
  331. if (shouldNavBarsBeHidden (shouldBeFullScreen))
  332. {
  333. if (! navBarsHidden && ! isTimerRunning())
  334. {
  335. startTimer (500);
  336. }
  337. }
  338. else
  339. {
  340. setNavBarsHidden (false);
  341. }
  342. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getDisplays().getMainDisplay().userArea
  343. : lastNonFullscreenBounds);
  344. if ((! shouldBeFullScreen) && r.isEmpty())
  345. r = getBounds();
  346. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  347. if (! r.isEmpty())
  348. setBounds (r, shouldBeFullScreen);
  349. component.repaint();
  350. }
  351. bool isFullScreen() const override
  352. {
  353. return fullScreen;
  354. }
  355. void timerCallback() override
  356. {
  357. setNavBarsHidden (shouldNavBarsBeHidden (fullScreen));
  358. setFullScreen (fullScreen);
  359. stopTimer();
  360. }
  361. void setIcon (const Image& /*newIcon*/) override
  362. {
  363. // n/a
  364. }
  365. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  366. {
  367. return isPositiveAndBelow (localPos.x, component.getWidth())
  368. && isPositiveAndBelow (localPos.y, component.getHeight())
  369. && ((! trueIfInAChildWindow) || view.callBooleanMethod (ComponentPeerView.containsPoint,
  370. localPos.x * scale,
  371. localPos.y * scale));
  372. }
  373. BorderSize<int> getFrameSize() const override
  374. {
  375. // TODO
  376. return BorderSize<int>();
  377. }
  378. bool setAlwaysOnTop (bool /*alwaysOnTop*/) override
  379. {
  380. // TODO
  381. return false;
  382. }
  383. void toFront (bool makeActive) override
  384. {
  385. // Avoid calling bringToFront excessively: it's very slow
  386. if (frontWindow != this)
  387. {
  388. view.callVoidMethod (AndroidView.bringToFront);
  389. frontWindow = this;
  390. }
  391. if (makeActive)
  392. grabFocus();
  393. handleBroughtToFront();
  394. }
  395. void toBehind (ComponentPeer*) override
  396. {
  397. // TODO
  398. }
  399. //==============================================================================
  400. void handleMouseDownCallback (int index, Point<float> sysPos, int64 time)
  401. {
  402. Point<float> pos = sysPos / scale;
  403. lastMousePos = localToGlobal (pos);
  404. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  405. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, currentModifiers.withoutMouseButtons(),
  406. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, index);
  407. if (isValidPeer (this))
  408. handleMouseDragCallback (index, sysPos, time);
  409. }
  410. void handleMouseDragCallback (int index, Point<float> pos, int64 time)
  411. {
  412. pos /= scale;
  413. lastMousePos = localToGlobal (pos);
  414. jassert (index < 64);
  415. touchesDown = (touchesDown | (1 << (index & 63)));
  416. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  417. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier),
  418. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, index);
  419. }
  420. void handleMouseUpCallback (int index, Point<float> pos, int64 time)
  421. {
  422. pos /= scale;
  423. lastMousePos = localToGlobal (pos);
  424. jassert (index < 64);
  425. touchesDown = (touchesDown & ~(1 << (index & 63)));
  426. if (touchesDown == 0)
  427. currentModifiers = currentModifiers.withoutMouseButtons();
  428. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, currentModifiers.withoutMouseButtons(), MouseInputSource::invalidPressure,
  429. MouseInputSource::invalidOrientation, time, {}, index);
  430. }
  431. void handleKeyDownCallback (int k, int kc)
  432. {
  433. handleKeyPress (k, static_cast<juce_wchar> (kc));
  434. }
  435. void handleKeyUpCallback (int /*k*/, int /*kc*/)
  436. {
  437. }
  438. void handleBackButtonCallback()
  439. {
  440. if (auto* app = JUCEApplicationBase::getInstance())
  441. app->backButtonPressed();
  442. }
  443. void handleAppResumedCallback()
  444. {
  445. if (Component* kiosk = Desktop::getInstance().getKioskModeComponent())
  446. if (kiosk->getPeer() == this)
  447. setNavBarsHidden (navBarsHidden);
  448. }
  449. //==============================================================================
  450. bool isFocused() const override
  451. {
  452. if (view != nullptr)
  453. return view.callBooleanMethod (AndroidView.hasFocus);
  454. return false;
  455. }
  456. void grabFocus() override
  457. {
  458. if (view != nullptr)
  459. view.callBooleanMethod (AndroidView.requestFocus);
  460. }
  461. void handleFocusChangeCallback (bool hasFocus)
  462. {
  463. if (hasFocus)
  464. handleFocusGain();
  465. else
  466. handleFocusLoss();
  467. }
  468. static const char* getVirtualKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  469. {
  470. switch (type)
  471. {
  472. case TextInputTarget::textKeyboard: return "text";
  473. case TextInputTarget::numericKeyboard: return "number";
  474. case TextInputTarget::decimalKeyboard: return "numberDecimal";
  475. case TextInputTarget::urlKeyboard: return "textUri";
  476. case TextInputTarget::emailAddressKeyboard: return "textEmailAddress";
  477. case TextInputTarget::phoneNumberKeyboard: return "phone";
  478. default: jassertfalse; break;
  479. }
  480. return "text";
  481. }
  482. void textInputRequired (Point<int>, TextInputTarget& target) override
  483. {
  484. view.callVoidMethod (ComponentPeerView.showKeyboard,
  485. javaString (getVirtualKeyboardType (target.getKeyboardType())).get());
  486. }
  487. void dismissPendingTextInput() override
  488. {
  489. view.callVoidMethod (ComponentPeerView.showKeyboard, javaString ("").get());
  490. }
  491. //==============================================================================
  492. void handlePaintCallback (JNIEnv* env, jobject canvas, jobject paint)
  493. {
  494. jobject rect = env->CallObjectMethod (canvas, CanvasMinimal.getClipBounds);
  495. const int left = env->GetIntField (rect, AndroidRectClass.left);
  496. const int top = env->GetIntField (rect, AndroidRectClass.top);
  497. const int right = env->GetIntField (rect, AndroidRectClass.right);
  498. const int bottom = env->GetIntField (rect, AndroidRectClass.bottom);
  499. env->DeleteLocalRef (rect);
  500. const Rectangle<int> clip (left, top, right - left, bottom - top);
  501. const int sizeNeeded = clip.getWidth() * clip.getHeight();
  502. if (sizeAllocated < sizeNeeded)
  503. {
  504. buffer.clear();
  505. sizeAllocated = sizeNeeded;
  506. buffer = GlobalRef (env->NewIntArray (sizeNeeded));
  507. }
  508. else if (sizeNeeded == 0)
  509. {
  510. return;
  511. }
  512. if (jint* dest = env->GetIntArrayElements ((jintArray) buffer.get(), 0))
  513. {
  514. {
  515. Image temp (new PreallocatedImage (clip.getWidth(), clip.getHeight(),
  516. dest, ! component.isOpaque()));
  517. {
  518. LowLevelGraphicsSoftwareRenderer g (temp);
  519. g.setOrigin (-clip.getPosition());
  520. g.addTransform (AffineTransform::scale (scale));
  521. handlePaint (g);
  522. }
  523. }
  524. env->ReleaseIntArrayElements ((jintArray) buffer.get(), dest, 0);
  525. env->CallVoidMethod (canvas, CanvasMinimal.drawBitmap, (jintArray) buffer.get(), 0, clip.getWidth(),
  526. (jfloat) clip.getX(), (jfloat) clip.getY(),
  527. clip.getWidth(), clip.getHeight(), true, paint);
  528. }
  529. }
  530. void repaint (const Rectangle<int>& userArea) override
  531. {
  532. Rectangle<int> area = userArea * scale;
  533. if (MessageManager::getInstance()->isThisTheMessageThread())
  534. {
  535. view.callVoidMethod (AndroidView.invalidate, area.getX(), area.getY(), area.getRight(), area.getBottom());
  536. }
  537. else
  538. {
  539. struct ViewRepainter : public CallbackMessage
  540. {
  541. ViewRepainter (const GlobalRef& view_, const Rectangle<int>& area_)
  542. : view (view_), area (area_) {}
  543. void messageCallback() override
  544. {
  545. view.callVoidMethod (AndroidView.invalidate, area.getX(), area.getY(),
  546. area.getRight(), area.getBottom());
  547. }
  548. private:
  549. GlobalRef view;
  550. const Rectangle<int> area;
  551. };
  552. (new ViewRepainter (view, area))->post();
  553. }
  554. }
  555. void performAnyPendingRepaintsNow() override
  556. {
  557. // TODO
  558. }
  559. void setAlpha (float /*newAlpha*/) override
  560. {
  561. // TODO
  562. }
  563. StringArray getAvailableRenderingEngines() override
  564. {
  565. return StringArray ("Software Renderer");
  566. }
  567. //==============================================================================
  568. static ModifierKeys currentModifiers;
  569. static Point<float> lastMousePos;
  570. static int64 touchesDown;
  571. private:
  572. //==============================================================================
  573. GlobalRef view;
  574. GlobalRef buffer;
  575. bool fullScreen;
  576. bool navBarsHidden;
  577. int sizeAllocated;
  578. float scale;
  579. static AndroidComponentPeer* frontWindow;
  580. struct PreallocatedImage : public ImagePixelData
  581. {
  582. PreallocatedImage (const int width_, const int height_, jint* data_, bool hasAlpha_)
  583. : ImagePixelData (Image::ARGB, width_, height_), data (data_), hasAlpha (hasAlpha_)
  584. {
  585. if (hasAlpha_)
  586. zeromem (data_, static_cast<size_t> (width * height) * sizeof (jint));
  587. }
  588. ~PreallocatedImage()
  589. {
  590. if (hasAlpha)
  591. {
  592. PixelARGB* pix = (PixelARGB*) data;
  593. for (int i = width * height; --i >= 0;)
  594. {
  595. pix->unpremultiply();
  596. ++pix;
  597. }
  598. }
  599. }
  600. ImageType* createType() const override { return new SoftwareImageType(); }
  601. LowLevelGraphicsContext* createLowLevelContext() override { return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
  602. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/) override
  603. {
  604. bm.lineStride = width * static_cast<int> (sizeof (jint));
  605. bm.pixelStride = static_cast<int> (sizeof (jint));
  606. bm.pixelFormat = Image::ARGB;
  607. bm.data = (uint8*) (data + x + y * width);
  608. }
  609. ImagePixelData::Ptr clone() override
  610. {
  611. PreallocatedImage* s = new PreallocatedImage (width, height, 0, hasAlpha);
  612. s->allocatedData.malloc (sizeof (jint) * static_cast<size_t> (width * height));
  613. s->data = s->allocatedData;
  614. memcpy (s->data, data, sizeof (jint) * static_cast<size_t> (width * height));
  615. return s;
  616. }
  617. private:
  618. jint* data;
  619. HeapBlock<jint> allocatedData;
  620. bool hasAlpha;
  621. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreallocatedImage)
  622. };
  623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer)
  624. };
  625. ModifierKeys AndroidComponentPeer::currentModifiers = 0;
  626. Point<float> AndroidComponentPeer::lastMousePos;
  627. int64 AndroidComponentPeer::touchesDown = 0;
  628. AndroidComponentPeer* AndroidComponentPeer::frontWindow = nullptr;
  629. //==============================================================================
  630. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  631. JUCE_JNI_CALLBACK (JUCE_JOIN_MACRO (JUCE_ANDROID_ACTIVITY_CLASSNAME, _00024ComponentPeerView), javaMethodName, returnType, params) \
  632. { \
  633. setEnv (env); \
  634. if (AndroidComponentPeer* peer = (AndroidComponentPeer*) (pointer_sized_uint) host) \
  635. peer->juceMethodInvocation; \
  636. }
  637. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject /*view*/, jlong host, jobject canvas, jobject paint), handlePaintCallback (env, canvas, paint))
  638. JUCE_VIEW_CALLBACK (void, handleMouseDown, (JNIEnv* env, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time), handleMouseDownCallback (i, Point<float> ((float) x, (float) y), (int64) time))
  639. JUCE_VIEW_CALLBACK (void, handleMouseDrag, (JNIEnv* env, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time), handleMouseDragCallback (i, Point<float> ((float) x, (float) y), (int64) time))
  640. JUCE_VIEW_CALLBACK (void, handleMouseUp, (JNIEnv* env, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time), handleMouseUpCallback (i, Point<float> ((float) x, (float) y), (int64) time))
  641. JUCE_VIEW_CALLBACK (void, viewSizeChanged, (JNIEnv* env, jobject /*view*/, jlong host), handleMovedOrResized())
  642. JUCE_VIEW_CALLBACK (void, focusChanged, (JNIEnv* env, jobject /*view*/, jlong host, jboolean hasFocus), handleFocusChangeCallback (hasFocus))
  643. JUCE_VIEW_CALLBACK (void, handleKeyDown, (JNIEnv* env, jobject /*view*/, jlong host, jint k, jint kc), handleKeyDownCallback ((int) k, (int) kc))
  644. JUCE_VIEW_CALLBACK (void, handleKeyUp, (JNIEnv* env, jobject /*view*/, jlong host, jint k, jint kc), handleKeyUpCallback ((int) k, (int) kc))
  645. JUCE_VIEW_CALLBACK (void, handleBackButton, (JNIEnv* env, jobject /*view*/, jlong host), handleBackButtonCallback())
  646. JUCE_VIEW_CALLBACK (void, handleAppResumed, (JNIEnv* env, jobject /*view*/, jlong host), handleAppResumedCallback())
  647. //==============================================================================
  648. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  649. {
  650. return new AndroidComponentPeer (*this, styleFlags);
  651. }
  652. //==============================================================================
  653. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  654. METHOD (getRotation, "getRotation", "()I")
  655. DECLARE_JNI_CLASS (Display, "android/view/Display");
  656. #undef JNI_CLASS_MEMBERS
  657. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  658. METHOD (getDefaultDisplay, "getDefaultDisplay", "()Landroid/view/Display;")
  659. DECLARE_JNI_CLASS (WindowManager, "android/view/WindowManager");
  660. #undef JNI_CLASS_MEMBERS
  661. bool Desktop::canUseSemiTransparentWindows() noexcept
  662. {
  663. return true;
  664. }
  665. double Desktop::getDefaultMasterScale()
  666. {
  667. return 1.0;
  668. }
  669. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  670. {
  671. enum
  672. {
  673. ROTATION_0 = 0,
  674. ROTATION_90 = 1,
  675. ROTATION_180 = 2,
  676. ROTATION_270 = 3
  677. };
  678. JNIEnv* env = getEnv();
  679. LocalRef<jstring> windowServiceString (javaString ("window"));
  680. LocalRef<jobject> windowManager = LocalRef<jobject> (env->CallObjectMethod (android.activity, JuceAppActivity.getSystemService, windowServiceString.get()));
  681. if (windowManager.get() != 0)
  682. {
  683. LocalRef<jobject> display = LocalRef<jobject> (env->CallObjectMethod (windowManager, WindowManager.getDefaultDisplay));
  684. if (display.get() != 0)
  685. {
  686. int rotation = env->CallIntMethod (display, Display.getRotation);
  687. switch (rotation)
  688. {
  689. case ROTATION_0: return upright;
  690. case ROTATION_90: return rotatedAntiClockwise;
  691. case ROTATION_180: return upsideDown;
  692. case ROTATION_270: return rotatedClockwise;
  693. }
  694. }
  695. }
  696. jassertfalse;
  697. return upright;
  698. }
  699. bool MouseInputSource::SourceList::addSource()
  700. {
  701. addSource (sources.size(), MouseInputSource::InputSourceType::touch);
  702. return true;
  703. }
  704. bool MouseInputSource::SourceList::canUseTouch()
  705. {
  706. return true;
  707. }
  708. Point<float> MouseInputSource::getCurrentRawMousePosition()
  709. {
  710. return AndroidComponentPeer::lastMousePos;
  711. }
  712. void MouseInputSource::setRawMousePosition (Point<float>)
  713. {
  714. // not needed
  715. }
  716. //==============================================================================
  717. bool KeyPress::isKeyCurrentlyDown (const int /*keyCode*/)
  718. {
  719. // TODO
  720. return false;
  721. }
  722. void ModifierKeys::updateCurrentModifiers() noexcept
  723. {
  724. currentModifiers = AndroidComponentPeer::currentModifiers;
  725. }
  726. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  727. {
  728. return AndroidComponentPeer::currentModifiers;
  729. }
  730. JUCE_API void JUCE_CALLTYPE Process::hide()
  731. {
  732. if (android.activity.callBooleanMethod (JuceAppActivity.moveTaskToBack, true) == 0)
  733. {
  734. auto* env = getEnv();
  735. GlobalRef intent (env->NewObject (AndroidIntent, AndroidIntent.constructor));
  736. env->CallObjectMethod (intent, AndroidIntent.setAction, javaString ("android.intent.action.MAIN") .get());
  737. env->CallObjectMethod (intent, AndroidIntent.addCategory, javaString ("android.intent.category.HOME").get());
  738. android.activity.callVoidMethod (JuceAppActivity.startActivity, intent.get());
  739. }
  740. }
  741. //==============================================================================
  742. // TODO
  743. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess() { return true; }
  744. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  745. //==============================================================================
  746. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType /*iconType*/,
  747. const String& title, const String& message,
  748. Component* /*associatedComponent*/,
  749. ModalComponentManager::Callback* callback)
  750. {
  751. android.activity.callVoidMethod (JuceAppActivity.showMessageBox, javaString (title).get(),
  752. javaString (message).get(), (jlong) (pointer_sized_int) callback);
  753. }
  754. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType /*iconType*/,
  755. const String& title, const String& message,
  756. Component* /*associatedComponent*/,
  757. ModalComponentManager::Callback* callback)
  758. {
  759. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  760. android.activity.callVoidMethod (JuceAppActivity.showOkCancelBox, javaString (title).get(),
  761. javaString (message).get(), (jlong) (pointer_sized_int) callback,
  762. javaString (TRANS ("OK")).get(), javaString (TRANS ("Cancel")).get());
  763. return false;
  764. }
  765. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType /*iconType*/,
  766. const String& title, const String& message,
  767. Component* /*associatedComponent*/,
  768. ModalComponentManager::Callback* callback)
  769. {
  770. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  771. android.activity.callVoidMethod (JuceAppActivity.showYesNoCancelBox, javaString (title).get(),
  772. javaString (message).get(), (jlong) (pointer_sized_int) callback);
  773. return 0;
  774. }
  775. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType /*iconType*/,
  776. const String& title, const String& message,
  777. Component* /*associatedComponent*/,
  778. ModalComponentManager::Callback* callback)
  779. {
  780. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  781. android.activity.callVoidMethod (JuceAppActivity.showOkCancelBox, javaString (title).get(),
  782. javaString (message).get(), (jlong) (pointer_sized_int) callback,
  783. javaString (TRANS ("Yes")).get(), javaString (TRANS ("No")).get());
  784. return 0;
  785. }
  786. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, alertDismissed, void, (JNIEnv* env, jobject /*activity*/,
  787. jlong callbackAsLong, jint result))
  788. {
  789. setEnv (env);
  790. if (ModalComponentManager::Callback* callback = (ModalComponentManager::Callback*) callbackAsLong)
  791. {
  792. callback->modalStateFinished (result);
  793. delete callback;
  794. }
  795. }
  796. //==============================================================================
  797. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  798. {
  799. android.activity.callVoidMethod (JuceAppActivity.setScreenSaver, isEnabled);
  800. }
  801. bool Desktop::isScreenSaverEnabled()
  802. {
  803. return android.activity.callBooleanMethod (JuceAppActivity.getScreenSaver);
  804. }
  805. //==============================================================================
  806. void Desktop::setKioskComponent (Component* kioskComp, bool enableOrDisable, bool allowMenusAndBars)
  807. {
  808. ignoreUnused (allowMenusAndBars);
  809. if (AndroidComponentPeer* peer = dynamic_cast<AndroidComponentPeer*> (kioskComp->getPeer()))
  810. peer->setFullScreen (enableOrDisable);
  811. else
  812. jassertfalse; // (this should have been checked by the caller)
  813. }
  814. //==============================================================================
  815. static jint getAndroidOrientationFlag (int orientations) noexcept
  816. {
  817. enum
  818. {
  819. SCREEN_ORIENTATION_LANDSCAPE = 0,
  820. SCREEN_ORIENTATION_PORTRAIT = 1,
  821. SCREEN_ORIENTATION_USER = 2,
  822. SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8,
  823. SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9,
  824. SCREEN_ORIENTATION_USER_LANDSCAPE = 11,
  825. SCREEN_ORIENTATION_USER_PORTRAIT = 12,
  826. };
  827. switch (orientations)
  828. {
  829. case Desktop::upright: return (jint) SCREEN_ORIENTATION_PORTRAIT;
  830. case Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_REVERSE_PORTRAIT;
  831. case Desktop::upright + Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_USER_PORTRAIT;
  832. case Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_LANDSCAPE;
  833. case Desktop::rotatedClockwise: return (jint) SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
  834. case Desktop::rotatedClockwise + Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_USER_LANDSCAPE;
  835. default: return (jint) SCREEN_ORIENTATION_USER;
  836. }
  837. }
  838. void Desktop::allowedOrientationsChanged()
  839. {
  840. android.activity.callVoidMethod (JuceAppActivity.setRequestedOrientation,
  841. getAndroidOrientationFlag (allowedOrientations));
  842. }
  843. //==============================================================================
  844. bool juce_areThereAnyAlwaysOnTopWindows()
  845. {
  846. return false;
  847. }
  848. //==============================================================================
  849. void Desktop::Displays::findDisplays (float masterScale)
  850. {
  851. Display d;
  852. d.isMain = true;
  853. d.dpi = android.dpi;
  854. d.scale = masterScale * (d.dpi / 150.);
  855. d.userArea = d.totalArea = Rectangle<int> (android.screenWidth,
  856. android.screenHeight) / d.scale;
  857. displays.add (d);
  858. }
  859. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, setScreenSize, void, (JNIEnv* env, jobject /*activity*/,
  860. jint screenWidth, jint screenHeight,
  861. jint dpi))
  862. {
  863. setEnv (env);
  864. android.screenWidth = screenWidth;
  865. android.screenHeight = screenHeight;
  866. android.dpi = dpi;
  867. const_cast<Desktop::Displays&> (Desktop::getInstance().getDisplays()).refresh();
  868. }
  869. //==============================================================================
  870. Image juce_createIconForFile (const File& /*file*/)
  871. {
  872. return Image();
  873. }
  874. //==============================================================================
  875. void* CustomMouseCursorInfo::create() const { return nullptr; }
  876. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType) { return nullptr; }
  877. void MouseCursor::deleteMouseCursor (void* const /*cursorHandle*/, const bool /*isStandard*/) {}
  878. //==============================================================================
  879. void MouseCursor::showInWindow (ComponentPeer*) const {}
  880. void MouseCursor::showInAllWindows() const {}
  881. //==============================================================================
  882. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& /*files*/, const bool /*canMove*/,
  883. Component* /*srcComp*/)
  884. {
  885. return false;
  886. }
  887. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/, Component* /*srcComp*/)
  888. {
  889. return false;
  890. }
  891. //==============================================================================
  892. void LookAndFeel::playAlertSound()
  893. {
  894. }
  895. //==============================================================================
  896. void SystemClipboard::copyTextToClipboard (const String& text)
  897. {
  898. const LocalRef<jstring> t (javaString (text));
  899. android.activity.callVoidMethod (JuceAppActivity.setClipboardContent, t.get());
  900. }
  901. String SystemClipboard::getTextFromClipboard()
  902. {
  903. const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (JuceAppActivity.getClipboardContent));
  904. return juceString (text);
  905. }
  906. //==============================================================================
  907. const int extendedKeyModifier = 0x10000;
  908. const int KeyPress::spaceKey = ' ';
  909. const int KeyPress::returnKey = 66;
  910. const int KeyPress::escapeKey = 4;
  911. const int KeyPress::backspaceKey = 67;
  912. const int KeyPress::leftKey = extendedKeyModifier + 1;
  913. const int KeyPress::rightKey = extendedKeyModifier + 2;
  914. const int KeyPress::upKey = extendedKeyModifier + 3;
  915. const int KeyPress::downKey = extendedKeyModifier + 4;
  916. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  917. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  918. const int KeyPress::endKey = extendedKeyModifier + 7;
  919. const int KeyPress::homeKey = extendedKeyModifier + 8;
  920. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  921. const int KeyPress::insertKey = -1;
  922. const int KeyPress::tabKey = 61;
  923. const int KeyPress::F1Key = extendedKeyModifier + 10;
  924. const int KeyPress::F2Key = extendedKeyModifier + 11;
  925. const int KeyPress::F3Key = extendedKeyModifier + 12;
  926. const int KeyPress::F4Key = extendedKeyModifier + 13;
  927. const int KeyPress::F5Key = extendedKeyModifier + 14;
  928. const int KeyPress::F6Key = extendedKeyModifier + 16;
  929. const int KeyPress::F7Key = extendedKeyModifier + 17;
  930. const int KeyPress::F8Key = extendedKeyModifier + 18;
  931. const int KeyPress::F9Key = extendedKeyModifier + 19;
  932. const int KeyPress::F10Key = extendedKeyModifier + 20;
  933. const int KeyPress::F11Key = extendedKeyModifier + 21;
  934. const int KeyPress::F12Key = extendedKeyModifier + 22;
  935. const int KeyPress::F13Key = extendedKeyModifier + 23;
  936. const int KeyPress::F14Key = extendedKeyModifier + 24;
  937. const int KeyPress::F15Key = extendedKeyModifier + 25;
  938. const int KeyPress::F16Key = extendedKeyModifier + 26;
  939. const int KeyPress::F17Key = extendedKeyModifier + 50;
  940. const int KeyPress::F18Key = extendedKeyModifier + 51;
  941. const int KeyPress::F19Key = extendedKeyModifier + 52;
  942. const int KeyPress::F20Key = extendedKeyModifier + 53;
  943. const int KeyPress::F21Key = extendedKeyModifier + 54;
  944. const int KeyPress::F22Key = extendedKeyModifier + 55;
  945. const int KeyPress::F23Key = extendedKeyModifier + 56;
  946. const int KeyPress::F24Key = extendedKeyModifier + 57;
  947. const int KeyPress::F25Key = extendedKeyModifier + 58;
  948. const int KeyPress::F26Key = extendedKeyModifier + 59;
  949. const int KeyPress::F27Key = extendedKeyModifier + 60;
  950. const int KeyPress::F28Key = extendedKeyModifier + 61;
  951. const int KeyPress::F29Key = extendedKeyModifier + 62;
  952. const int KeyPress::F30Key = extendedKeyModifier + 63;
  953. const int KeyPress::F31Key = extendedKeyModifier + 64;
  954. const int KeyPress::F32Key = extendedKeyModifier + 65;
  955. const int KeyPress::F33Key = extendedKeyModifier + 66;
  956. const int KeyPress::F34Key = extendedKeyModifier + 67;
  957. const int KeyPress::F35Key = extendedKeyModifier + 68;
  958. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  959. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  960. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  961. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  962. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  963. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  964. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  965. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  966. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  967. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  968. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  969. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  970. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  971. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  972. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  973. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  974. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  975. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  976. const int KeyPress::playKey = extendedKeyModifier + 45;
  977. const int KeyPress::stopKey = extendedKeyModifier + 46;
  978. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  979. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  980. } // namespace juce