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.

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