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.

1092 lines
42KB

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