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.

932 lines
36KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. namespace GraphicsHelpers
  19. {
  20. jobject createPaint (Graphics::ResamplingQuality quality)
  21. {
  22. jint constructorFlags = 1 /*ANTI_ALIAS_FLAG*/
  23. | 4 /*DITHER_FLAG*/
  24. | 128 /*SUBPIXEL_TEXT_FLAG*/;
  25. if (quality > Graphics::lowResamplingQuality)
  26. constructorFlags |= 2; /*FILTER_BITMAP_FLAG*/
  27. return getEnv()->NewObject (Paint, Paint.constructor, constructorFlags);
  28. }
  29. const jobject createMatrix (JNIEnv* env, const AffineTransform& t)
  30. {
  31. jobject m = env->NewObject (Matrix, Matrix.constructor);
  32. jfloat values[9] = { t.mat00, t.mat01, t.mat02,
  33. t.mat10, t.mat11, t.mat12,
  34. 0.0f, 0.0f, 1.0f };
  35. jfloatArray javaArray = env->NewFloatArray (9);
  36. env->SetFloatArrayRegion (javaArray, 0, 9, values);
  37. env->CallVoidMethod (m, Matrix.setValues, javaArray);
  38. env->DeleteLocalRef (javaArray);
  39. return m;
  40. }
  41. }
  42. #if USE_ANDROID_CANVAS
  43. //==============================================================================
  44. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  45. METHOD (constructor, "<init>", "(Landroid/graphics/Bitmap;)V") \
  46. METHOD (drawRect, "drawRect", "(FFFFLandroid/graphics/Paint;)V") \
  47. METHOD (translate, "translate", "(FF)V") \
  48. METHOD (clipPath, "clipPath", "(Landroid/graphics/Path;)Z") \
  49. METHOD (clipRect, "clipRect", "(FFFF)Z") \
  50. METHOD (clipRegion, "clipRegion", "(Landroid/graphics/Region;)Z") \
  51. METHOD (concat, "concat", "(Landroid/graphics/Matrix;)V") \
  52. METHOD (drawBitmap, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Matrix;Landroid/graphics/Paint;)V") \
  53. METHOD (drawBitmapAt, "drawBitmap", "(Landroid/graphics/Bitmap;FFLandroid/graphics/Paint;)V") \
  54. METHOD (drawMemoryBitmap, "drawBitmap", "([IIIFFIIZLandroid/graphics/Paint;)V") \
  55. METHOD (drawLine, "drawLine", "(FFFFLandroid/graphics/Paint;)V") \
  56. METHOD (drawPath, "drawPath", "(Landroid/graphics/Path;Landroid/graphics/Paint;)V") \
  57. METHOD (drawText, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V") \
  58. METHOD (getClipBounds, "getClipBounds", "(Landroid/graphics/Rect;)Z") \
  59. METHOD (getClipBounds2, "getClipBounds", "()Landroid/graphics/Rect;") \
  60. METHOD (getMatrix, "getMatrix", "()Landroid/graphics/Matrix;") \
  61. METHOD (save, "save", "()I") \
  62. METHOD (restore, "restore", "()V") \
  63. METHOD (saveLayerAlpha, "saveLayerAlpha", "(FFFFII)I")
  64. DECLARE_JNI_CLASS (Canvas, "android/graphics/Canvas");
  65. #undef JNI_CLASS_MEMBERS
  66. //==============================================================================
  67. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  68. METHOD (constructor, "<init>", "()V") \
  69. METHOD (moveTo, "moveTo", "(FF)V") \
  70. METHOD (lineTo, "lineTo", "(FF)V") \
  71. METHOD (quadTo, "quadTo", "(FFFF)V") \
  72. METHOD (cubicTo, "cubicTo", "(FFFFFF)V") \
  73. METHOD (closePath, "close", "()V") \
  74. METHOD (computeBounds, "computeBounds", "(Landroid/graphics/RectF;Z)V") \
  75. DECLARE_JNI_CLASS (PathClass, "android/graphics/Path");
  76. #undef JNI_CLASS_MEMBERS
  77. //==============================================================================
  78. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  79. METHOD (constructor, "<init>", "()V"); \
  80. METHOD (regionUnion, "union", "(Landroid/graphics/Rect;)Z"); \
  81. DECLARE_JNI_CLASS (RegionClass, "android/graphics/Region");
  82. #undef JNI_CLASS_MEMBERS
  83. //==============================================================================
  84. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  85. STATICMETHOD (createBitmap, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;") \
  86. METHOD (bitmapCopy, "copy", "(Landroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;") \
  87. METHOD (getPixels, "getPixels", "([IIIIIII)V") \
  88. METHOD (setPixels, "setPixels", "([IIIIIII)V") \
  89. METHOD (recycle, "recycle", "()V") \
  90. DECLARE_JNI_CLASS (BitmapClass, "android/graphics/Bitmap");
  91. #undef JNI_CLASS_MEMBERS
  92. //==============================================================================
  93. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  94. STATICFIELD (ARGB_8888, "ARGB_8888", "Landroid/graphics/Bitmap$Config;") \
  95. STATICFIELD (ALPHA_8, "ALPHA_8", "Landroid/graphics/Bitmap$Config;") \
  96. DECLARE_JNI_CLASS (BitmapConfig, "android/graphics/Bitmap$Config");
  97. #undef JNI_CLASS_MEMBERS
  98. //==============================================================================
  99. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  100. METHOD (constructor, "<init>", "(Landroid/graphics/Bitmap;Landroid/graphics/Shader$TileMode;Landroid/graphics/Shader$TileMode;)V")
  101. DECLARE_JNI_CLASS (BitmapShader, "android/graphics/BitmapShader");
  102. #undef JNI_CLASS_MEMBERS
  103. //==============================================================================
  104. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  105. METHOD (setLocalMatrix, "setLocalMatrix", "(Landroid/graphics/Matrix;)V")
  106. DECLARE_JNI_CLASS (ShaderClass, "android/graphics/Shader");
  107. #undef JNI_CLASS_MEMBERS
  108. //==============================================================================
  109. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  110. STATICFIELD (CLAMP, "CLAMP", "Landroid/graphics/Shader$TileMode;")
  111. DECLARE_JNI_CLASS (ShaderTileMode, "android/graphics/Shader$TileMode");
  112. #undef JNI_CLASS_MEMBERS
  113. //==============================================================================
  114. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  115. METHOD (constructor, "<init>", "(FFFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  116. DECLARE_JNI_CLASS (LinearGradientClass, "android/graphics/LinearGradient");
  117. #undef JNI_CLASS_MEMBERS
  118. //==============================================================================
  119. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  120. METHOD (constructor, "<init>", "(FFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  121. DECLARE_JNI_CLASS (RadialGradientClass, "android/graphics/RadialGradient");
  122. #undef JNI_CLASS_MEMBERS
  123. //==============================================================================
  124. class AndroidImage : public ImagePixelData
  125. {
  126. public:
  127. AndroidImage (const int width_, const int height_, const bool clearImage)
  128. : ImagePixelData (Image::ARGB, width_, height_),
  129. bitmap (createBitmap (width_, height_, false))
  130. {
  131. }
  132. AndroidImage (const int width_, const int height_, const GlobalRef& bitmap_)
  133. : ImagePixelData (Image::ARGB, width_, height_),
  134. bitmap (bitmap_)
  135. {
  136. }
  137. ~AndroidImage()
  138. {
  139. if (bitmap != 0)
  140. bitmap.callVoidMethod (BitmapClass.recycle);
  141. }
  142. LowLevelGraphicsContext* createLowLevelContext();
  143. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode mode)
  144. {
  145. bm.lineStride = width * sizeof (jint);
  146. bm.pixelStride = sizeof (jint);
  147. bm.pixelFormat = Image::ARGB;
  148. bm.dataReleaser = new CopyHandler (*this, bm, x, y, mode);
  149. }
  150. ImagePixelData* clone()
  151. {
  152. JNIEnv* env = getEnv();
  153. jobject mode = env->GetStaticObjectField (BitmapConfig, BitmapConfig.ARGB_8888);
  154. GlobalRef newCopy (bitmap.callObjectMethod (BitmapClass.bitmapCopy, mode, true));
  155. env->DeleteLocalRef (mode);
  156. return new AndroidImage (width, height, newCopy);
  157. }
  158. ImageType* createType() const { return new NativeImageType(); }
  159. static jobject createBitmap (int width, int height, bool asSingleChannel)
  160. {
  161. JNIEnv* env = getEnv();
  162. jobject mode = env->GetStaticObjectField (BitmapConfig, asSingleChannel ? BitmapConfig.ALPHA_8
  163. : BitmapConfig.ARGB_8888);
  164. jobject result = env->CallStaticObjectMethod (BitmapClass, BitmapClass.createBitmap, width, height, mode);
  165. env->DeleteLocalRef (mode);
  166. return result;
  167. }
  168. //==============================================================================
  169. GlobalRef bitmap;
  170. private:
  171. class CopyHandler : public Image::BitmapData::BitmapDataReleaser
  172. {
  173. public:
  174. CopyHandler (AndroidImage& owner_, Image::BitmapData& bitmapData_,
  175. const int x_, const int y_, const Image::BitmapData::ReadWriteMode mode_)
  176. : owner (owner_), bitmapData (bitmapData_), mode (mode_), x (x_), y (y_)
  177. {
  178. JNIEnv* env = getEnv();
  179. intArray = env->NewIntArray (bitmapData.width * bitmapData.height);
  180. if (mode != Image::BitmapData::writeOnly)
  181. owner_.bitmap.callVoidMethod (BitmapClass.getPixels, intArray, 0, bitmapData.width, x_, y_,
  182. bitmapData.width, bitmapData.height);
  183. bitmapData.data = (uint8*) env->GetIntArrayElements (intArray, 0);
  184. if (mode != Image::BitmapData::writeOnly)
  185. {
  186. for (int yy = 0; yy < bitmapData.height; ++yy)
  187. {
  188. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  189. for (int xx = 0; xx < bitmapData.width; ++xx)
  190. p[xx].premultiply();
  191. }
  192. }
  193. }
  194. ~CopyHandler()
  195. {
  196. JNIEnv* env = getEnv();
  197. if (mode != Image::BitmapData::readOnly)
  198. {
  199. for (int yy = 0; yy < bitmapData.height; ++yy)
  200. {
  201. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  202. for (int xx = 0; xx < bitmapData.width; ++xx)
  203. p[xx].unpremultiply();
  204. }
  205. }
  206. env->ReleaseIntArrayElements (intArray, (jint*) bitmapData.data, 0);
  207. if (mode != Image::BitmapData::readOnly)
  208. owner.bitmap.callVoidMethod (BitmapClass.setPixels, intArray, 0, bitmapData.width, x, y,
  209. bitmapData.width, bitmapData.height);
  210. env->DeleteLocalRef (intArray);
  211. }
  212. private:
  213. AndroidImage& owner;
  214. Image::BitmapData& bitmapData;
  215. jintArray intArray;
  216. const Image::BitmapData::ReadWriteMode mode;
  217. const int x, y;
  218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CopyHandler);
  219. };
  220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidImage);
  221. };
  222. #endif
  223. ImagePixelData* NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  224. {
  225. #if USE_ANDROID_CANVAS
  226. if (pixelFormat != Image::SingleChannel)
  227. return new AndroidImage (width, height, clearImage);
  228. #endif
  229. return SoftwareImageType().create (format, width, height, clearImage);
  230. }
  231. #if USE_ANDROID_CANVAS
  232. //==============================================================================
  233. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  234. {
  235. public:
  236. AndroidLowLevelGraphicsContext (jobject canvas_)
  237. : originalCanvas (canvas_),
  238. currentState (new SavedState (canvas_))
  239. {
  240. setFill (Colours::black);
  241. }
  242. ~AndroidLowLevelGraphicsContext()
  243. {
  244. while (stateStack.size() > 0)
  245. restoreState();
  246. currentState->flattenImageClippingLayer (originalCanvas);
  247. }
  248. bool isVectorDevice() const { return false; }
  249. //==============================================================================
  250. void setOrigin (int x, int y)
  251. {
  252. getCanvas().callVoidMethod (Canvas.translate, (float) x, (float) y);
  253. }
  254. void addTransform (const AffineTransform& transform)
  255. {
  256. getCanvas().callVoidMethod (Canvas.concat, createMatrixRef (getEnv(), transform).get());
  257. }
  258. float getScaleFactor()
  259. {
  260. return 1.0f;
  261. }
  262. bool clipToRectangle (const Rectangle<int>& r)
  263. {
  264. return getCanvas().callBooleanMethod (Canvas.clipRect, (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  265. }
  266. bool clipToRectangleList (const RectangleList& clipRegion)
  267. {
  268. RectangleList excluded (getClipBounds());
  269. excluded.subtract (clipRegion);
  270. const int numRects = excluded.getNumRectangles();
  271. for (int i = 0; i < numRects; ++i)
  272. excludeClipRectangle (excluded.getRectangle(i));
  273. }
  274. void excludeClipRectangle (const Rectangle<int>& r)
  275. {
  276. android.activity.callVoidMethod (JuceAppActivity.excludeClipRegion, getCanvas().get(),
  277. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  278. }
  279. void clipToPath (const Path& path, const AffineTransform& transform)
  280. {
  281. (void) getCanvas().callBooleanMethod (Canvas.clipPath, createPath (getEnv(), path, transform).get());
  282. }
  283. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  284. {
  285. // XXX couldn't get image clipping to work...
  286. JNIEnv* env = getEnv();
  287. {
  288. Path p;
  289. p.addRectangle (sourceImage.getBounds().toFloat());
  290. clipToPath (p, transform);
  291. }
  292. Rectangle<int> bounds (getClipBounds());
  293. jobject temporaryLayerBitmap = AndroidImage::createBitmap (bounds.getWidth(), bounds.getHeight(), false);
  294. jobject temporaryCanvas = env->NewObject (Canvas, Canvas.constructor, temporaryLayerBitmap);
  295. setFill (Colours::red);
  296. env->CallVoidMethod (temporaryCanvas, Canvas.drawRect,
  297. (jfloat) 20, (jfloat) 20, (jfloat) 300, (jfloat) 200,
  298. getCurrentPaint());
  299. env->CallVoidMethod (temporaryCanvas, Canvas.translate,
  300. (jfloat) -bounds.getX(), (jfloat) -bounds.getY());
  301. Image maskImage (Image::SingleChannel, bounds.getWidth(), bounds.getHeight(), true);
  302. {
  303. Graphics g (maskImage);
  304. g.setOrigin (-bounds.getWidth(), -bounds.getHeight());
  305. g.drawImageTransformed (sourceImage, transform);
  306. }
  307. SavedState* const top = stateStack.getLast();
  308. currentState->clipToImage (top != nullptr ? top->canvas.get() : originalCanvas,
  309. temporaryCanvas, temporaryLayerBitmap, maskImage,
  310. bounds.getX(), bounds.getY());
  311. }
  312. bool clipRegionIntersects (const Rectangle<int>& r)
  313. {
  314. return getClipBounds().intersects (r);
  315. }
  316. Rectangle<int> getClipBounds() const
  317. {
  318. JNIEnv* env = getEnv();
  319. jobject rect = getCanvas().callObjectMethod (Canvas.getClipBounds2);
  320. const int left = env->GetIntField (rect, RectClass.left);
  321. const int top = env->GetIntField (rect, RectClass.top);
  322. const int right = env->GetIntField (rect, RectClass.right);
  323. const int bottom = env->GetIntField (rect, RectClass.bottom);
  324. env->DeleteLocalRef (rect);
  325. return Rectangle<int> (left, top, right - left, bottom - top);
  326. }
  327. bool isClipEmpty() const
  328. {
  329. LocalRef<jobject> tempRect (getEnv()->NewObject (RectClass, RectClass.constructor, 0, 0, 0, 0));
  330. return ! getCanvas().callBooleanMethod (Canvas.getClipBounds, tempRect.get());
  331. }
  332. //==============================================================================
  333. void setFill (const FillType& fillType)
  334. {
  335. currentState->setFillType (fillType);
  336. }
  337. void setOpacity (float newOpacity)
  338. {
  339. currentState->setAlpha (newOpacity);
  340. }
  341. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  342. {
  343. currentState->setInterpolationQuality (quality);
  344. }
  345. //==============================================================================
  346. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  347. {
  348. getCanvas().callVoidMethod (Canvas.drawRect,
  349. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom(),
  350. getCurrentPaint());
  351. }
  352. void fillPath (const Path& path, const AffineTransform& transform)
  353. {
  354. getCanvas().callVoidMethod (Canvas.drawPath, createPath (getEnv(), path, transform).get(),
  355. getCurrentPaint());
  356. }
  357. void drawImage (const Image& sourceImage, const AffineTransform& transform)
  358. {
  359. AndroidImage* androidImage = dynamic_cast <AndroidImage*> (sourceImage.getPixelData());
  360. if (androidImage != 0)
  361. {
  362. JNIEnv* env = getEnv();
  363. getCanvas().callVoidMethod (Canvas.drawBitmap, androidImage->bitmap.get(),
  364. createMatrixRef (env, transform).get(), getImagePaint());
  365. }
  366. else
  367. {
  368. if (transform.isOnlyTranslation())
  369. {
  370. JNIEnv* env = getEnv();
  371. Image::BitmapData bm (sourceImage, Image::BitmapData::readOnly);
  372. jintArray imageData = env->NewIntArray (bm.width * bm.height);
  373. jint* dest = env->GetIntArrayElements (imageData, 0);
  374. if (dest != 0)
  375. {
  376. const uint8* srcLine = bm.getLinePointer (0);
  377. jint* dstLine = dest;
  378. for (int y = 0; y < bm.height; ++y)
  379. {
  380. switch (bm.pixelFormat)
  381. {
  382. case Image::ARGB: copyPixels (dstLine, (PixelARGB*) srcLine, bm.width, bm.pixelStride); break;
  383. case Image::RGB: copyPixels (dstLine, (PixelRGB*) srcLine, bm.width, bm.pixelStride); break;
  384. case Image::SingleChannel: copyPixels (dstLine, (PixelAlpha*) srcLine, bm.width, bm.pixelStride); break;
  385. default: jassertfalse; break;
  386. }
  387. srcLine += bm.lineStride;
  388. dstLine += bm.width;
  389. }
  390. env->ReleaseIntArrayElements (imageData, dest, 0);
  391. getCanvas().callVoidMethod (Canvas.drawMemoryBitmap, imageData, 0, bm.width,
  392. transform.getTranslationX(), transform.getTranslationY(),
  393. bm.width, bm.height, true, getImagePaint());
  394. env->DeleteLocalRef (imageData);
  395. }
  396. }
  397. else
  398. {
  399. saveState();
  400. addTransform (transform);
  401. drawImage (sourceImage, AffineTransform::identity);
  402. restoreState();
  403. }
  404. }
  405. }
  406. void drawLine (const Line <float>& line)
  407. {
  408. getCanvas().callVoidMethod (Canvas.drawLine, line.getStartX(), line.getStartY(),
  409. line.getEndX(), line.getEndY(), getCurrentPaint());
  410. }
  411. void drawVerticalLine (int x, float top, float bottom)
  412. {
  413. getCanvas().callVoidMethod (Canvas.drawRect, (float) x, top, x + 1.0f, bottom, getCurrentPaint());
  414. }
  415. void drawHorizontalLine (int y, float left, float right)
  416. {
  417. getCanvas().callVoidMethod (Canvas.drawRect, left, (float) y, right, y + 1.0f, getCurrentPaint());
  418. }
  419. void setFont (const Font& newFont)
  420. {
  421. if (currentState->font != newFont)
  422. {
  423. currentState->font = newFont;
  424. currentState->typefaceNeedsUpdate = true;
  425. }
  426. }
  427. Font getFont()
  428. {
  429. return currentState->font;
  430. }
  431. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  432. {
  433. if (transform.isOnlyTranslation())
  434. {
  435. getCanvas().callVoidMethod (Canvas.drawText, javaStringFromChar ((juce_wchar) glyphNumber).get(),
  436. transform.getTranslationX(), transform.getTranslationY(),
  437. currentState->getPaintForTypeface());
  438. }
  439. else
  440. {
  441. saveState();
  442. addTransform (transform);
  443. drawGlyph (glyphNumber, AffineTransform::identity);
  444. restoreState();
  445. }
  446. }
  447. //==============================================================================
  448. void saveState()
  449. {
  450. (void) getCanvas().callIntMethod (Canvas.save);
  451. stateStack.add (new SavedState (*currentState));
  452. }
  453. void restoreState()
  454. {
  455. SavedState* const top = stateStack.getLast();
  456. if (top != 0)
  457. {
  458. currentState->flattenImageClippingLayer (top->canvas);
  459. currentState = top;
  460. stateStack.removeLast (1, false);
  461. }
  462. else
  463. {
  464. jassertfalse; // trying to pop with an empty stack!
  465. }
  466. getCanvas().callVoidMethod (Canvas.restore);
  467. }
  468. void beginTransparencyLayer (float opacity)
  469. {
  470. Rectangle<int> clip (getClipBounds());
  471. (void) getCanvas().callIntMethod (Canvas.saveLayerAlpha,
  472. (float) clip.getX(),
  473. (float) clip.getY(),
  474. (float) clip.getRight(),
  475. (float) clip.getBottom(),
  476. jlimit (0, 255, roundToInt (opacity * 255.0f)),
  477. 31 /*ALL_SAVE_FLAG*/);
  478. stateStack.add (new SavedState (*currentState));
  479. }
  480. void endTransparencyLayer()
  481. {
  482. restoreState();
  483. }
  484. //==============================================================================
  485. class SavedState
  486. {
  487. public:
  488. SavedState (jobject canvas_)
  489. : canvas (canvas_), font (1.0f), quality (Graphics::highResamplingQuality),
  490. fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  491. {
  492. }
  493. SavedState (const SavedState& other)
  494. : canvas (other.canvas), fillType (other.fillType), font (other.font),
  495. quality (other.quality), fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  496. {
  497. }
  498. void setFillType (const FillType& newType)
  499. {
  500. fillNeedsUpdate = true;
  501. fillType = newType;
  502. }
  503. void setAlpha (float alpha)
  504. {
  505. fillNeedsUpdate = true;
  506. fillType.colour = fillType.colour.withAlpha (alpha);
  507. }
  508. void setInterpolationQuality (Graphics::ResamplingQuality quality_)
  509. {
  510. if (quality != quality_)
  511. {
  512. quality = quality_;
  513. fillNeedsUpdate = true;
  514. paint.clear();
  515. }
  516. }
  517. jobject getPaint()
  518. {
  519. if (fillNeedsUpdate)
  520. {
  521. JNIEnv* env = getEnv();
  522. if (paint.get() == 0)
  523. paint = GlobalRef (GraphicsHelpers::createPaint (quality));
  524. if (fillType.isColour())
  525. {
  526. env->DeleteLocalRef (paint.callObjectMethod (Paint.setShader, (jobject) 0));
  527. paint.callVoidMethod (Paint.setColor, colourToInt (fillType.colour));
  528. }
  529. else if (fillType.isGradient())
  530. {
  531. const ColourGradient& g = *fillType.gradient;
  532. const Point<float> p1 (g.point1);
  533. const Point<float> p2 (g.point2);
  534. const int numColours = g.getNumColours();
  535. jintArray coloursArray = env->NewIntArray (numColours);
  536. jfloatArray positionsArray = env->NewFloatArray (numColours);
  537. {
  538. HeapBlock<int> colours (numColours);
  539. HeapBlock<float> positions (numColours);
  540. for (int i = 0; i < numColours; ++i)
  541. {
  542. colours[i] = colourToInt (g.getColour (i));
  543. positions[i] = (float) g.getColourPosition(i);
  544. }
  545. env->SetIntArrayRegion (coloursArray, 0, numColours, colours.getData());
  546. env->SetFloatArrayRegion (positionsArray, 0, numColours, positions.getData());
  547. }
  548. jobject tileMode = env->GetStaticObjectField (ShaderTileMode, ShaderTileMode.CLAMP);
  549. jobject shader;
  550. if (fillType.gradient->isRadial)
  551. {
  552. shader = env->NewObject (RadialGradientClass,
  553. RadialGradientClass.constructor,
  554. p1.getX(), p1.getY(),
  555. p1.getDistanceFrom (p2),
  556. coloursArray, positionsArray,
  557. tileMode);
  558. }
  559. else
  560. {
  561. shader = env->NewObject (LinearGradientClass,
  562. LinearGradientClass.constructor,
  563. p1.getX(), p1.getY(), p2.getX(), p2.getY(),
  564. coloursArray, positionsArray,
  565. tileMode);
  566. }
  567. env->DeleteLocalRef (tileMode);
  568. env->DeleteLocalRef (coloursArray);
  569. env->DeleteLocalRef (positionsArray);
  570. env->CallVoidMethod (shader, ShaderClass.setLocalMatrix, createMatrixRef (env, fillType.transform).get());
  571. env->DeleteLocalRef (paint.callObjectMethod (Paint.setShader, shader));
  572. env->DeleteLocalRef (shader);
  573. }
  574. else
  575. {
  576. // TODO xxx
  577. }
  578. }
  579. return paint.get();
  580. }
  581. jobject getPaintForTypeface()
  582. {
  583. jobject p = getPaint();
  584. if (typefaceNeedsUpdate)
  585. {
  586. typefaceNeedsUpdate = false;
  587. const Typeface::Ptr t (font.getTypeface());
  588. AndroidTypeface* atf = dynamic_cast <AndroidTypeface*> (t.getObject());
  589. if (atf != 0)
  590. {
  591. paint.callObjectMethod (Paint.setTypeface, atf->typeface.get());
  592. paint.callVoidMethod (Paint.setTextSize, font.getHeight());
  593. const float hScale = font.getHorizontalScale();
  594. if (hScale < 0.99f || hScale > 1.01f)
  595. paint.callVoidMethod (Paint.setTextScaleX, hScale);
  596. }
  597. fillNeedsUpdate = true;
  598. paint.callVoidMethod (Paint.setAlpha, (jint) fillType.colour.getAlpha());
  599. }
  600. return p;
  601. }
  602. jobject getImagePaint()
  603. {
  604. jobject p = getPaint();
  605. paint.callVoidMethod (Paint.setAlpha, (jint) fillType.colour.getAlpha());
  606. fillNeedsUpdate = true;
  607. return p;
  608. }
  609. void flattenImageClippingLayer (jobject previousCanvas)
  610. {
  611. // XXX couldn't get image clipping to work...
  612. if (temporaryLayerBitmap != 0)
  613. {
  614. JNIEnv* env = getEnv();
  615. jobject tileMode = env->GetStaticObjectField (ShaderTileMode, ShaderTileMode.CLAMP);
  616. jobject shader = env->NewObject (BitmapShader, BitmapShader.constructor,
  617. temporaryLayerBitmap.get(), tileMode, tileMode);
  618. env->DeleteLocalRef (tileMode);
  619. jobject compositingPaint = GraphicsHelpers::createPaint (quality);
  620. env->CallObjectMethod (compositingPaint, Paint.setShader, shader);
  621. env->DeleteLocalRef (shader);
  622. LocalRef<jobject> maskBitmap (createAlphaBitmap (env, maskImage));
  623. maskImage = Image::null;
  624. env->CallVoidMethod (previousCanvas, Canvas.drawBitmapAt,
  625. maskBitmap.get(), (jfloat) maskLayerX, (jfloat) maskLayerY, compositingPaint);
  626. env->DeleteLocalRef (compositingPaint);
  627. canvas = GlobalRef (previousCanvas);
  628. env->CallVoidMethod (temporaryLayerBitmap.get(), BitmapClass.recycle);
  629. env->CallVoidMethod (maskBitmap.get(), BitmapClass.recycle);
  630. temporaryLayerBitmap.clear();
  631. }
  632. }
  633. void clipToImage (jobject previousCanvas,
  634. jobject temporaryCanvas, jobject temporaryLayerBitmap_,
  635. const Image& maskImage_,
  636. int maskLayerX_, int maskLayerY_)
  637. {
  638. // XXX couldn't get image clipping to work...
  639. flattenImageClippingLayer (previousCanvas);
  640. maskLayerX = maskLayerX_;
  641. maskLayerY = maskLayerY_;
  642. canvas = GlobalRef (temporaryCanvas);
  643. temporaryLayerBitmap = GlobalRef (temporaryLayerBitmap_);
  644. maskImage = maskImage_;
  645. }
  646. static jobject createAlphaBitmap (JNIEnv* env, const Image& image)
  647. {
  648. Image::BitmapData bm (image, Image::BitmapData::readOnly);
  649. jobject bitmap = AndroidImage::createBitmap (bm.width, bm.height, true);
  650. jintArray intArray = env->NewIntArray (bm.width * bm.height);
  651. jint* const dest = env->GetIntArrayElements (intArray, 0);
  652. for (int yy = 0; yy < bm.height; ++yy)
  653. {
  654. PixelAlpha* src = (PixelAlpha*) bm.getLinePointer (yy);
  655. jint* destLine = dest + yy * bm.width;
  656. for (int xx = 0; xx < bm.width; ++xx)
  657. {
  658. destLine[xx] = src->getAlpha();
  659. src = addBytesToPointer (src, bm.pixelStride);
  660. }
  661. }
  662. env->ReleaseIntArrayElements (intArray, (jint*) dest, 0);
  663. env->CallVoidMethod (bitmap, BitmapClass.setPixels, intArray, 0, bm.width, 0, 0, bm.width, bm.height);
  664. env->DeleteLocalRef (intArray);
  665. return bitmap;
  666. }
  667. GlobalRef canvas, temporaryLayerBitmap;
  668. FillType fillType;
  669. Font font;
  670. GlobalRef paint;
  671. bool fillNeedsUpdate, typefaceNeedsUpdate;
  672. Graphics::ResamplingQuality quality;
  673. Image maskImage;
  674. int maskLayerX, maskLayerY;
  675. };
  676. private:
  677. //==============================================================================
  678. GlobalRef originalCanvas;
  679. ScopedPointer <SavedState> currentState;
  680. OwnedArray <SavedState> stateStack;
  681. GlobalRef& getCanvas() const noexcept { return currentState->canvas; }
  682. jobject getCurrentPaint() const { return currentState->getPaint(); }
  683. jobject getImagePaint() const { return currentState->getImagePaint(); }
  684. static LocalRef<jobject> createPath (JNIEnv* env, const Path& path)
  685. {
  686. jobject p = env->NewObject (PathClass, PathClass.constructor);
  687. Path::Iterator i (path);
  688. while (i.next())
  689. {
  690. switch (i.elementType)
  691. {
  692. case Path::Iterator::startNewSubPath: env->CallVoidMethod (p, PathClass.moveTo, i.x1, i.y1); break;
  693. case Path::Iterator::lineTo: env->CallVoidMethod (p, PathClass.lineTo, i.x1, i.y1); break;
  694. case Path::Iterator::quadraticTo: env->CallVoidMethod (p, PathClass.quadTo, i.x1, i.y1, i.x2, i.y2); break;
  695. case Path::Iterator::cubicTo: env->CallVoidMethod (p, PathClass.cubicTo, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  696. case Path::Iterator::closePath: env->CallVoidMethod (p, PathClass.closePath); break;
  697. default: jassertfalse; break;
  698. }
  699. }
  700. return LocalRef<jobject> (p);
  701. }
  702. static LocalRef<jobject> createPath (JNIEnv* env, const Path& path, const AffineTransform& transform)
  703. {
  704. if (transform.isIdentity())
  705. return createPath (env, path);
  706. Path tempPath (path);
  707. tempPath.applyTransform (transform);
  708. return createPath (env, tempPath);
  709. }
  710. static LocalRef<jobject> createMatrixRef (JNIEnv* env, const AffineTransform& t)
  711. {
  712. return LocalRef<jobject> (GraphicsHelpers::createMatrix (env, t));
  713. }
  714. static LocalRef<jobject> createRect (JNIEnv* env, const Rectangle<int>& r)
  715. {
  716. return LocalRef<jobject> (env->NewObject (RectClass, RectClass.constructor,
  717. r.getX(), r.getY(), r.getRight(), r.getBottom()));
  718. }
  719. static LocalRef<jobject> createRegion (JNIEnv* env, const RectangleList& list)
  720. {
  721. jobject region = env->NewObject (RegionClass, RegionClass.constructor);
  722. const int numRects = list.getNumRectangles();
  723. for (int i = 0; i < numRects; ++i)
  724. env->CallBooleanMethod (region, RegionClass.regionUnion, createRect (env, list.getRectangle(i)).get());
  725. return LocalRef<jobject> (region);
  726. }
  727. static int colourToInt (const Colour& col) noexcept
  728. {
  729. return col.getARGB();
  730. }
  731. template <class PixelType>
  732. static void copyPixels (jint* const dest, const PixelType* src, const int width, const int pixelStride) noexcept
  733. {
  734. for (int x = 0; x < width; ++x)
  735. {
  736. dest[x] = src->getUnpremultipliedARGB();
  737. src = addBytesToPointer (src, pixelStride);
  738. }
  739. }
  740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  741. };
  742. LowLevelGraphicsContext* AndroidImage::createLowLevelContext()
  743. {
  744. jobject canvas = getEnv()->NewObject (Canvas, Canvas.constructor, bitmap.get());
  745. return new AndroidLowLevelGraphicsContext (canvas);
  746. }
  747. #endif