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.

1161 lines
44KB

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