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.

1185 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, ModifierKeys::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. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  417. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, ModifierKeys::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. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  428. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, ModifierKeys::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. if (Component* kiosk = Desktop::getInstance().getKioskModeComponent())
  443. if (kiosk->getPeer() == this)
  444. setNavBarsHidden (navBarsHidden);
  445. }
  446. void handleKeyboardHiddenCallback()
  447. {
  448. Component::unfocusAllComponents();
  449. }
  450. void handleAppPausedCallback() {}
  451. void handleAppResumedCallback()
  452. {
  453. if (Component* kiosk = Desktop::getInstance().getKioskModeComponent())
  454. if (kiosk->getPeer() == this)
  455. setNavBarsHidden (navBarsHidden);
  456. }
  457. //==============================================================================
  458. bool isFocused() const override
  459. {
  460. if (view != nullptr)
  461. return view.callBooleanMethod (AndroidView.hasFocus);
  462. return false;
  463. }
  464. void grabFocus() override
  465. {
  466. if (view != nullptr)
  467. view.callBooleanMethod (AndroidView.requestFocus);
  468. }
  469. void handleFocusChangeCallback (bool hasFocus)
  470. {
  471. if (hasFocus)
  472. handleFocusGain();
  473. else
  474. handleFocusLoss();
  475. }
  476. static const char* getVirtualKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  477. {
  478. switch (type)
  479. {
  480. case TextInputTarget::textKeyboard: return "text";
  481. case TextInputTarget::numericKeyboard: return "number";
  482. case TextInputTarget::decimalKeyboard: return "numberDecimal";
  483. case TextInputTarget::urlKeyboard: return "textUri";
  484. case TextInputTarget::emailAddressKeyboard: return "textEmailAddress";
  485. case TextInputTarget::phoneNumberKeyboard: return "phone";
  486. default: jassertfalse; break;
  487. }
  488. return "text";
  489. }
  490. void textInputRequired (Point<int>, TextInputTarget& target) override
  491. {
  492. view.callVoidMethod (ComponentPeerView.showKeyboard,
  493. javaString (getVirtualKeyboardType (target.getKeyboardType())).get());
  494. }
  495. void dismissPendingTextInput() override
  496. {
  497. view.callVoidMethod (ComponentPeerView.showKeyboard, javaString ("").get());
  498. // updating the nav bar visibility is a bit odd on Android - need to wait for
  499. if (! isTimerRunning())
  500. hideNavBarDelayed();
  501. }
  502. void hideNavBarDelayed()
  503. {
  504. startTimer (500);
  505. }
  506. //==============================================================================
  507. void handlePaintCallback (JNIEnv* env, jobject canvas, jobject paint)
  508. {
  509. jobject rect = env->CallObjectMethod (canvas, CanvasMinimal.getClipBounds);
  510. const int left = env->GetIntField (rect, AndroidRect.left);
  511. const int top = env->GetIntField (rect, AndroidRect.top);
  512. const int right = env->GetIntField (rect, AndroidRect.right);
  513. const int bottom = env->GetIntField (rect, AndroidRect.bottom);
  514. env->DeleteLocalRef (rect);
  515. const Rectangle<int> clip (left, top, right - left, bottom - top);
  516. const int sizeNeeded = clip.getWidth() * clip.getHeight();
  517. if (sizeAllocated < sizeNeeded)
  518. {
  519. buffer.clear();
  520. sizeAllocated = sizeNeeded;
  521. buffer = GlobalRef (env->NewIntArray (sizeNeeded));
  522. }
  523. else if (sizeNeeded == 0)
  524. {
  525. return;
  526. }
  527. if (jint* dest = env->GetIntArrayElements ((jintArray) buffer.get(), 0))
  528. {
  529. {
  530. Image temp (new PreallocatedImage (clip.getWidth(), clip.getHeight(),
  531. dest, ! component.isOpaque()));
  532. {
  533. LowLevelGraphicsSoftwareRenderer g (temp);
  534. g.setOrigin (-clip.getPosition());
  535. g.addTransform (AffineTransform::scale (scale));
  536. handlePaint (g);
  537. }
  538. }
  539. env->ReleaseIntArrayElements ((jintArray) buffer.get(), dest, 0);
  540. env->CallVoidMethod (canvas, CanvasMinimal.drawBitmap, (jintArray) buffer.get(), 0, clip.getWidth(),
  541. (jfloat) clip.getX(), (jfloat) clip.getY(),
  542. clip.getWidth(), clip.getHeight(), true, paint);
  543. }
  544. }
  545. void repaint (const Rectangle<int>& userArea) override
  546. {
  547. Rectangle<int> area = userArea * scale;
  548. if (MessageManager::getInstance()->isThisTheMessageThread())
  549. {
  550. view.callVoidMethod (AndroidView.invalidate, area.getX(), area.getY(), area.getRight(), area.getBottom());
  551. }
  552. else
  553. {
  554. struct ViewRepainter : public CallbackMessage
  555. {
  556. ViewRepainter (const GlobalRef& view_, const Rectangle<int>& area_)
  557. : view (view_), area (area_) {}
  558. void messageCallback() override
  559. {
  560. view.callVoidMethod (AndroidView.invalidate, area.getX(), area.getY(),
  561. area.getRight(), area.getBottom());
  562. }
  563. private:
  564. GlobalRef view;
  565. const Rectangle<int> area;
  566. };
  567. (new ViewRepainter (view, area))->post();
  568. }
  569. }
  570. void performAnyPendingRepaintsNow() override
  571. {
  572. // TODO
  573. }
  574. void setAlpha (float /*newAlpha*/) override
  575. {
  576. // TODO
  577. }
  578. StringArray getAvailableRenderingEngines() override
  579. {
  580. return StringArray ("Software Renderer");
  581. }
  582. //==============================================================================
  583. static Point<float> lastMousePos;
  584. static int64 touchesDown;
  585. private:
  586. //==============================================================================
  587. GlobalRef view;
  588. GlobalRef buffer;
  589. bool fullScreen;
  590. bool navBarsHidden;
  591. int sizeAllocated;
  592. float scale;
  593. static AndroidComponentPeer* frontWindow;
  594. struct PreallocatedImage : public ImagePixelData
  595. {
  596. PreallocatedImage (const int width_, const int height_, jint* data_, bool hasAlpha_)
  597. : ImagePixelData (Image::ARGB, width_, height_), data (data_), hasAlpha (hasAlpha_)
  598. {
  599. if (hasAlpha_)
  600. zeromem (data_, static_cast<size_t> (width * height) * sizeof (jint));
  601. }
  602. ~PreallocatedImage()
  603. {
  604. if (hasAlpha)
  605. {
  606. PixelARGB* pix = (PixelARGB*) data;
  607. for (int i = width * height; --i >= 0;)
  608. {
  609. pix->unpremultiply();
  610. ++pix;
  611. }
  612. }
  613. }
  614. ImageType* createType() const override { return new SoftwareImageType(); }
  615. LowLevelGraphicsContext* createLowLevelContext() override { return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
  616. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/) override
  617. {
  618. bm.lineStride = width * static_cast<int> (sizeof (jint));
  619. bm.pixelStride = static_cast<int> (sizeof (jint));
  620. bm.pixelFormat = Image::ARGB;
  621. bm.data = (uint8*) (data + x + y * width);
  622. }
  623. ImagePixelData::Ptr clone() override
  624. {
  625. PreallocatedImage* s = new PreallocatedImage (width, height, 0, hasAlpha);
  626. s->allocatedData.malloc (sizeof (jint) * static_cast<size_t> (width * height));
  627. s->data = s->allocatedData;
  628. memcpy (s->data, data, sizeof (jint) * static_cast<size_t> (width * height));
  629. return s;
  630. }
  631. private:
  632. jint* data;
  633. HeapBlock<jint> allocatedData;
  634. bool hasAlpha;
  635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreallocatedImage)
  636. };
  637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer)
  638. };
  639. Point<float> AndroidComponentPeer::lastMousePos;
  640. int64 AndroidComponentPeer::touchesDown = 0;
  641. AndroidComponentPeer* AndroidComponentPeer::frontWindow = nullptr;
  642. //==============================================================================
  643. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  644. JUCE_JNI_CALLBACK (JUCE_JOIN_MACRO (JUCE_ANDROID_ACTIVITY_CLASSNAME, _00024ComponentPeerView), javaMethodName, returnType, params) \
  645. { \
  646. setEnv (env); \
  647. if (AndroidComponentPeer* peer = (AndroidComponentPeer*) (pointer_sized_uint) host) \
  648. peer->juceMethodInvocation; \
  649. }
  650. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject /*view*/, jlong host, jobject canvas, jobject paint), handlePaintCallback (env, canvas, paint))
  651. 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))
  652. 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))
  653. 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))
  654. JUCE_VIEW_CALLBACK (void, viewSizeChanged, (JNIEnv* env, jobject /*view*/, jlong host), handleMovedOrResized())
  655. JUCE_VIEW_CALLBACK (void, focusChanged, (JNIEnv* env, jobject /*view*/, jlong host, jboolean hasFocus), handleFocusChangeCallback (hasFocus))
  656. JUCE_VIEW_CALLBACK (void, handleKeyDown, (JNIEnv* env, jobject /*view*/, jlong host, jint k, jint kc), handleKeyDownCallback ((int) k, (int) kc))
  657. JUCE_VIEW_CALLBACK (void, handleKeyUp, (JNIEnv* env, jobject /*view*/, jlong host, jint k, jint kc), handleKeyUpCallback ((int) k, (int) kc))
  658. JUCE_VIEW_CALLBACK (void, handleBackButton, (JNIEnv* env, jobject /*view*/, jlong host), handleBackButtonCallback())
  659. JUCE_VIEW_CALLBACK (void, handleKeyboardHidden, (JNIEnv* env, jobject /*view*/, jlong host), handleKeyboardHiddenCallback())
  660. JUCE_VIEW_CALLBACK (void, handleAppPaused, (JNIEnv* env, jobject /*view*/, jlong host), handleAppPausedCallback())
  661. JUCE_VIEW_CALLBACK (void, handleAppResumed, (JNIEnv* env, jobject /*view*/, jlong host), handleAppResumedCallback())
  662. //==============================================================================
  663. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  664. {
  665. return new AndroidComponentPeer (*this, styleFlags);
  666. }
  667. //==============================================================================
  668. bool Desktop::canUseSemiTransparentWindows() noexcept
  669. {
  670. return true;
  671. }
  672. double Desktop::getDefaultMasterScale()
  673. {
  674. return 1.0;
  675. }
  676. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  677. {
  678. enum
  679. {
  680. ROTATION_0 = 0,
  681. ROTATION_90 = 1,
  682. ROTATION_180 = 2,
  683. ROTATION_270 = 3
  684. };
  685. JNIEnv* env = getEnv();
  686. LocalRef<jstring> windowServiceString (javaString ("window"));
  687. LocalRef<jobject> windowManager = LocalRef<jobject> (env->CallObjectMethod (android.activity, JuceAppActivity.getSystemService, windowServiceString.get()));
  688. if (windowManager.get() != 0)
  689. {
  690. LocalRef<jobject> display = LocalRef<jobject> (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));
  691. if (display.get() != 0)
  692. {
  693. int rotation = env->CallIntMethod (display, AndroidDisplay.getRotation);
  694. switch (rotation)
  695. {
  696. case ROTATION_0: return upright;
  697. case ROTATION_90: return rotatedAntiClockwise;
  698. case ROTATION_180: return upsideDown;
  699. case ROTATION_270: return rotatedClockwise;
  700. }
  701. }
  702. }
  703. jassertfalse;
  704. return upright;
  705. }
  706. bool MouseInputSource::SourceList::addSource()
  707. {
  708. addSource (sources.size(), MouseInputSource::InputSourceType::touch);
  709. return true;
  710. }
  711. bool MouseInputSource::SourceList::canUseTouch()
  712. {
  713. return true;
  714. }
  715. Point<float> MouseInputSource::getCurrentRawMousePosition()
  716. {
  717. return AndroidComponentPeer::lastMousePos;
  718. }
  719. void MouseInputSource::setRawMousePosition (Point<float>)
  720. {
  721. // not needed
  722. }
  723. //==============================================================================
  724. bool KeyPress::isKeyCurrentlyDown (const int /*keyCode*/)
  725. {
  726. // TODO
  727. return false;
  728. }
  729. JUCE_API void JUCE_CALLTYPE Process::hide()
  730. {
  731. if (android.activity.callBooleanMethod (JuceAppActivity.moveTaskToBack, true) == 0)
  732. {
  733. auto* env = getEnv();
  734. GlobalRef intent (env->NewObject (AndroidIntent, AndroidIntent.constructor));
  735. env->CallObjectMethod (intent, AndroidIntent.setAction, javaString ("android.intent.action.MAIN") .get());
  736. env->CallObjectMethod (intent, AndroidIntent.addCategory, javaString ("android.intent.category.HOME").get());
  737. android.activity.callVoidMethod (JuceAppActivity.startActivity, intent.get());
  738. }
  739. }
  740. //==============================================================================
  741. // TODO
  742. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess() { return true; }
  743. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  744. //==============================================================================
  745. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType /*iconType*/,
  746. const String& title, const String& message,
  747. Component* /*associatedComponent*/,
  748. ModalComponentManager::Callback* callback)
  749. {
  750. android.activity.callVoidMethod (JuceAppActivity.showMessageBox, javaString (title).get(),
  751. javaString (message).get(), (jlong) (pointer_sized_int) callback);
  752. }
  753. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType /*iconType*/,
  754. const String& title, const String& message,
  755. Component* /*associatedComponent*/,
  756. ModalComponentManager::Callback* callback)
  757. {
  758. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  759. android.activity.callVoidMethod (JuceAppActivity.showOkCancelBox, javaString (title).get(),
  760. javaString (message).get(), (jlong) (pointer_sized_int) callback,
  761. javaString (TRANS ("OK")).get(), javaString (TRANS ("Cancel")).get());
  762. return false;
  763. }
  764. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType /*iconType*/,
  765. const String& title, const String& message,
  766. Component* /*associatedComponent*/,
  767. ModalComponentManager::Callback* callback)
  768. {
  769. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  770. android.activity.callVoidMethod (JuceAppActivity.showYesNoCancelBox, javaString (title).get(),
  771. javaString (message).get(), (jlong) (pointer_sized_int) callback);
  772. return 0;
  773. }
  774. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType /*iconType*/,
  775. const String& title, const String& message,
  776. Component* /*associatedComponent*/,
  777. ModalComponentManager::Callback* callback)
  778. {
  779. jassert (callback != nullptr); // on android, all alerts must be non-modal!!
  780. android.activity.callVoidMethod (JuceAppActivity.showOkCancelBox, javaString (title).get(),
  781. javaString (message).get(), (jlong) (pointer_sized_int) callback,
  782. javaString (TRANS ("Yes")).get(), javaString (TRANS ("No")).get());
  783. return 0;
  784. }
  785. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, alertDismissed, void, (JNIEnv* env, jobject /*activity*/,
  786. jlong callbackAsLong, jint result))
  787. {
  788. setEnv (env);
  789. if (ModalComponentManager::Callback* callback = (ModalComponentManager::Callback*) callbackAsLong)
  790. {
  791. callback->modalStateFinished (result);
  792. delete callback;
  793. }
  794. }
  795. //==============================================================================
  796. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  797. {
  798. android.activity.callVoidMethod (JuceAppActivity.setScreenSaver, isEnabled);
  799. }
  800. bool Desktop::isScreenSaverEnabled()
  801. {
  802. return android.activity.callBooleanMethod (JuceAppActivity.getScreenSaver);
  803. }
  804. //==============================================================================
  805. void Desktop::setKioskComponent (Component* kioskComp, bool enableOrDisable, bool allowMenusAndBars)
  806. {
  807. ignoreUnused (allowMenusAndBars);
  808. if (AndroidComponentPeer* peer = dynamic_cast<AndroidComponentPeer*> (kioskComp->getPeer()))
  809. peer->setFullScreen (enableOrDisable);
  810. else
  811. jassertfalse; // (this should have been checked by the caller)
  812. }
  813. //==============================================================================
  814. static jint getAndroidOrientationFlag (int orientations) noexcept
  815. {
  816. enum
  817. {
  818. SCREEN_ORIENTATION_LANDSCAPE = 0,
  819. SCREEN_ORIENTATION_PORTRAIT = 1,
  820. SCREEN_ORIENTATION_USER = 2,
  821. SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8,
  822. SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9,
  823. SCREEN_ORIENTATION_USER_LANDSCAPE = 11,
  824. SCREEN_ORIENTATION_USER_PORTRAIT = 12,
  825. };
  826. switch (orientations)
  827. {
  828. case Desktop::upright: return (jint) SCREEN_ORIENTATION_PORTRAIT;
  829. case Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_REVERSE_PORTRAIT;
  830. case Desktop::upright + Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_USER_PORTRAIT;
  831. case Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_LANDSCAPE;
  832. case Desktop::rotatedClockwise: return (jint) SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
  833. case Desktop::rotatedClockwise + Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_USER_LANDSCAPE;
  834. default: return (jint) SCREEN_ORIENTATION_USER;
  835. }
  836. }
  837. void Desktop::allowedOrientationsChanged()
  838. {
  839. android.activity.callVoidMethod (JuceAppActivity.setRequestedOrientation,
  840. getAndroidOrientationFlag (allowedOrientations));
  841. }
  842. //==============================================================================
  843. bool juce_areThereAnyAlwaysOnTopWindows()
  844. {
  845. return false;
  846. }
  847. //==============================================================================
  848. void Desktop::Displays::findDisplays (float masterScale)
  849. {
  850. Display d;
  851. d.isMain = true;
  852. d.dpi = android.dpi;
  853. d.scale = masterScale * (d.dpi / 150.);
  854. d.userArea = d.totalArea = Rectangle<int> (android.screenWidth,
  855. android.screenHeight) / d.scale;
  856. displays.add (d);
  857. }
  858. JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, setScreenSize, void, (JNIEnv* env, jobject /*activity*/,
  859. jint screenWidth, jint screenHeight,
  860. jint dpi))
  861. {
  862. setEnv (env);
  863. android.screenWidth = screenWidth;
  864. android.screenHeight = screenHeight;
  865. android.dpi = dpi;
  866. const_cast<Desktop::Displays&> (Desktop::getInstance().getDisplays()).refresh();
  867. }
  868. //==============================================================================
  869. Image juce_createIconForFile (const File& /*file*/)
  870. {
  871. return Image();
  872. }
  873. //==============================================================================
  874. void* CustomMouseCursorInfo::create() const { return nullptr; }
  875. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType) { return nullptr; }
  876. void MouseCursor::deleteMouseCursor (void* const /*cursorHandle*/, const bool /*isStandard*/) {}
  877. //==============================================================================
  878. void MouseCursor::showInWindow (ComponentPeer*) const {}
  879. void MouseCursor::showInAllWindows() const {}
  880. //==============================================================================
  881. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& /*files*/, const bool /*canMove*/,
  882. Component* /*srcComp*/)
  883. {
  884. return false;
  885. }
  886. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/, Component* /*srcComp*/)
  887. {
  888. return false;
  889. }
  890. //==============================================================================
  891. void LookAndFeel::playAlertSound()
  892. {
  893. }
  894. //==============================================================================
  895. void SystemClipboard::copyTextToClipboard (const String& text)
  896. {
  897. const LocalRef<jstring> t (javaString (text));
  898. android.activity.callVoidMethod (JuceAppActivity.setClipboardContent, t.get());
  899. }
  900. String SystemClipboard::getTextFromClipboard()
  901. {
  902. const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (JuceAppActivity.getClipboardContent));
  903. return juceString (text);
  904. }
  905. //==============================================================================
  906. const int extendedKeyModifier = 0x10000;
  907. const int KeyPress::spaceKey = ' ';
  908. const int KeyPress::returnKey = 66;
  909. const int KeyPress::escapeKey = 4;
  910. const int KeyPress::backspaceKey = 67;
  911. const int KeyPress::leftKey = extendedKeyModifier + 1;
  912. const int KeyPress::rightKey = extendedKeyModifier + 2;
  913. const int KeyPress::upKey = extendedKeyModifier + 3;
  914. const int KeyPress::downKey = extendedKeyModifier + 4;
  915. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  916. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  917. const int KeyPress::endKey = extendedKeyModifier + 7;
  918. const int KeyPress::homeKey = extendedKeyModifier + 8;
  919. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  920. const int KeyPress::insertKey = -1;
  921. const int KeyPress::tabKey = 61;
  922. const int KeyPress::F1Key = extendedKeyModifier + 10;
  923. const int KeyPress::F2Key = extendedKeyModifier + 11;
  924. const int KeyPress::F3Key = extendedKeyModifier + 12;
  925. const int KeyPress::F4Key = extendedKeyModifier + 13;
  926. const int KeyPress::F5Key = extendedKeyModifier + 14;
  927. const int KeyPress::F6Key = extendedKeyModifier + 16;
  928. const int KeyPress::F7Key = extendedKeyModifier + 17;
  929. const int KeyPress::F8Key = extendedKeyModifier + 18;
  930. const int KeyPress::F9Key = extendedKeyModifier + 19;
  931. const int KeyPress::F10Key = extendedKeyModifier + 20;
  932. const int KeyPress::F11Key = extendedKeyModifier + 21;
  933. const int KeyPress::F12Key = extendedKeyModifier + 22;
  934. const int KeyPress::F13Key = extendedKeyModifier + 23;
  935. const int KeyPress::F14Key = extendedKeyModifier + 24;
  936. const int KeyPress::F15Key = extendedKeyModifier + 25;
  937. const int KeyPress::F16Key = extendedKeyModifier + 26;
  938. const int KeyPress::F17Key = extendedKeyModifier + 50;
  939. const int KeyPress::F18Key = extendedKeyModifier + 51;
  940. const int KeyPress::F19Key = extendedKeyModifier + 52;
  941. const int KeyPress::F20Key = extendedKeyModifier + 53;
  942. const int KeyPress::F21Key = extendedKeyModifier + 54;
  943. const int KeyPress::F22Key = extendedKeyModifier + 55;
  944. const int KeyPress::F23Key = extendedKeyModifier + 56;
  945. const int KeyPress::F24Key = extendedKeyModifier + 57;
  946. const int KeyPress::F25Key = extendedKeyModifier + 58;
  947. const int KeyPress::F26Key = extendedKeyModifier + 59;
  948. const int KeyPress::F27Key = extendedKeyModifier + 60;
  949. const int KeyPress::F28Key = extendedKeyModifier + 61;
  950. const int KeyPress::F29Key = extendedKeyModifier + 62;
  951. const int KeyPress::F30Key = extendedKeyModifier + 63;
  952. const int KeyPress::F31Key = extendedKeyModifier + 64;
  953. const int KeyPress::F32Key = extendedKeyModifier + 65;
  954. const int KeyPress::F33Key = extendedKeyModifier + 66;
  955. const int KeyPress::F34Key = extendedKeyModifier + 67;
  956. const int KeyPress::F35Key = extendedKeyModifier + 68;
  957. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  958. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  959. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  960. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  961. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  962. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  963. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  964. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  965. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  966. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  967. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  968. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  969. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  970. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  971. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  972. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  973. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  974. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  975. const int KeyPress::playKey = extendedKeyModifier + 45;
  976. const int KeyPress::stopKey = extendedKeyModifier + 46;
  977. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  978. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  979. } // namespace juce