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.

673 lines
21KB

  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. ImagePixelData::ImagePixelData (const Image::PixelFormat format, const int w, const int h)
  20. : pixelFormat (format), width (w), height (h)
  21. {
  22. jassert (format == Image::RGB || format == Image::ARGB || format == Image::SingleChannel);
  23. jassert (w > 0 && h > 0); // It's illegal to create a zero-sized image!
  24. }
  25. ImagePixelData::~ImagePixelData()
  26. {
  27. listeners.call (&Listener::imageDataBeingDeleted, this);
  28. }
  29. void ImagePixelData::sendDataChangeMessage()
  30. {
  31. listeners.call (&Listener::imageDataChanged, this);
  32. }
  33. int ImagePixelData::getSharedCount() const noexcept
  34. {
  35. return getReferenceCount();
  36. }
  37. //==============================================================================
  38. ImageType::ImageType() {}
  39. ImageType::~ImageType() {}
  40. Image ImageType::convert (const Image& source) const
  41. {
  42. if (source.isNull() || getTypeID() == (ScopedPointer<ImageType> (source.getPixelData()->createType())->getTypeID()))
  43. return source;
  44. const Image::BitmapData src (source, Image::BitmapData::readOnly);
  45. Image newImage (create (src.pixelFormat, src.width, src.height, false));
  46. Image::BitmapData dest (newImage, Image::BitmapData::writeOnly);
  47. if (src.pixelStride == dest.pixelStride && src.pixelFormat == dest.pixelFormat)
  48. {
  49. for (int y = 0; y < dest.height; ++y)
  50. memcpy (dest.getLinePointer (y), src.getLinePointer (y), (size_t) dest.lineStride);
  51. }
  52. else
  53. {
  54. for (int y = 0; y < dest.height; ++y)
  55. for (int x = 0; x < dest.width; ++x)
  56. dest.setPixelColour (x, y, src.getPixelColour (x, y));
  57. }
  58. return newImage;
  59. }
  60. //==============================================================================
  61. class SoftwarePixelData : public ImagePixelData
  62. {
  63. public:
  64. SoftwarePixelData (const Image::PixelFormat format_, const int w, const int h, const bool clearImage)
  65. : ImagePixelData (format_, w, h),
  66. pixelStride (format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1)),
  67. lineStride ((pixelStride * jmax (1, w) + 3) & ~3)
  68. {
  69. imageData.allocate ((size_t) (lineStride * jmax (1, h)), clearImage);
  70. }
  71. LowLevelGraphicsContext* createLowLevelContext() override
  72. {
  73. sendDataChangeMessage();
  74. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  75. }
  76. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  77. {
  78. bitmap.data = imageData + x * pixelStride + y * lineStride;
  79. bitmap.pixelFormat = pixelFormat;
  80. bitmap.lineStride = lineStride;
  81. bitmap.pixelStride = pixelStride;
  82. if (mode != Image::BitmapData::readOnly)
  83. sendDataChangeMessage();
  84. }
  85. ImagePixelData::Ptr clone() override
  86. {
  87. SoftwarePixelData* s = new SoftwarePixelData (pixelFormat, width, height, false);
  88. memcpy (s->imageData, imageData, (size_t) (lineStride * height));
  89. return s;
  90. }
  91. ImageType* createType() const override { return new SoftwareImageType(); }
  92. private:
  93. HeapBlock<uint8> imageData;
  94. const int pixelStride, lineStride;
  95. JUCE_LEAK_DETECTOR (SoftwarePixelData)
  96. };
  97. SoftwareImageType::SoftwareImageType() {}
  98. SoftwareImageType::~SoftwareImageType() {}
  99. ImagePixelData::Ptr SoftwareImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  100. {
  101. return new SoftwarePixelData (format, width, height, clearImage);
  102. }
  103. int SoftwareImageType::getTypeID() const
  104. {
  105. return 2;
  106. }
  107. //==============================================================================
  108. NativeImageType::NativeImageType() {}
  109. NativeImageType::~NativeImageType() {}
  110. int NativeImageType::getTypeID() const
  111. {
  112. return 1;
  113. }
  114. #if JUCE_WINDOWS || JUCE_LINUX
  115. ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  116. {
  117. return new SoftwarePixelData (format, width, height, clearImage);
  118. }
  119. #endif
  120. //==============================================================================
  121. class SubsectionPixelData : public ImagePixelData
  122. {
  123. public:
  124. SubsectionPixelData (ImagePixelData* const im, const Rectangle<int>& r)
  125. : ImagePixelData (im->pixelFormat, r.getWidth(), r.getHeight()),
  126. sourceImage (im), area (r)
  127. {
  128. }
  129. LowLevelGraphicsContext* createLowLevelContext() override
  130. {
  131. LowLevelGraphicsContext* g = sourceImage->createLowLevelContext();
  132. g->clipToRectangle (area);
  133. g->setOrigin (area.getPosition());
  134. return g;
  135. }
  136. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  137. {
  138. sourceImage->initialiseBitmapData (bitmap, x + area.getX(), y + area.getY(), mode);
  139. if (mode != Image::BitmapData::readOnly)
  140. sendDataChangeMessage();
  141. }
  142. ImagePixelData::Ptr clone() override
  143. {
  144. jassert (getReferenceCount() > 0); // (This method can't be used on an unowned pointer, as it will end up self-deleting)
  145. const ScopedPointer<ImageType> type (createType());
  146. Image newImage (type->create (pixelFormat, area.getWidth(), area.getHeight(), pixelFormat != Image::RGB));
  147. {
  148. Graphics g (newImage);
  149. g.drawImageAt (Image (this), 0, 0);
  150. }
  151. return newImage.getPixelData();
  152. }
  153. ImageType* createType() const override { return sourceImage->createType(); }
  154. /* as we always hold a reference to image, don't double count */
  155. int getSharedCount() const noexcept override { return getReferenceCount() + sourceImage->getSharedCount() - 1; }
  156. private:
  157. friend class Image;
  158. const ImagePixelData::Ptr sourceImage;
  159. const Rectangle<int> area;
  160. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionPixelData)
  161. };
  162. Image Image::getClippedImage (const Rectangle<int>& area) const
  163. {
  164. if (area.contains (getBounds()))
  165. return *this;
  166. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  167. return Image (validArea.isEmpty() ? nullptr : new SubsectionPixelData (image, validArea));
  168. }
  169. //==============================================================================
  170. Image::Image() noexcept
  171. {
  172. }
  173. Image::Image (ImagePixelData* const instance) noexcept
  174. : image (instance)
  175. {
  176. }
  177. Image::Image (const PixelFormat format, int width, int height, bool clearImage)
  178. : image (NativeImageType().create (format, width, height, clearImage))
  179. {
  180. }
  181. Image::Image (const PixelFormat format, int width, int height, bool clearImage, const ImageType& type)
  182. : image (type.create (format, width, height, clearImage))
  183. {
  184. }
  185. Image::Image (const Image& other) noexcept
  186. : image (other.image)
  187. {
  188. }
  189. Image& Image::operator= (const Image& other)
  190. {
  191. image = other.image;
  192. return *this;
  193. }
  194. Image::Image (Image&& other) noexcept
  195. : image (static_cast<ImagePixelData::Ptr&&> (other.image))
  196. {
  197. }
  198. Image& Image::operator= (Image&& other) noexcept
  199. {
  200. image = static_cast<ImagePixelData::Ptr&&> (other.image);
  201. return *this;
  202. }
  203. Image::~Image()
  204. {
  205. }
  206. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  207. const Image Image::null;
  208. #endif
  209. int Image::getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getSharedCount(); }
  210. int Image::getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  211. int Image::getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  212. Rectangle<int> Image::getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  213. Image::PixelFormat Image::getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->pixelFormat; }
  214. bool Image::isARGB() const noexcept { return getFormat() == ARGB; }
  215. bool Image::isRGB() const noexcept { return getFormat() == RGB; }
  216. bool Image::isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  217. bool Image::hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  218. LowLevelGraphicsContext* Image::createLowLevelContext() const
  219. {
  220. return image == nullptr ? nullptr : image->createLowLevelContext();
  221. }
  222. void Image::duplicateIfShared()
  223. {
  224. if (getReferenceCount() > 1)
  225. image = image->clone();
  226. }
  227. Image Image::createCopy() const
  228. {
  229. if (image != nullptr)
  230. return Image (image->clone());
  231. return Image();
  232. }
  233. Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  234. {
  235. if (image == nullptr || (image->width == newWidth && image->height == newHeight))
  236. return *this;
  237. const ScopedPointer<ImageType> type (image->createType());
  238. Image newImage (type->create (image->pixelFormat, newWidth, newHeight, hasAlphaChannel()));
  239. Graphics g (newImage);
  240. g.setImageResamplingQuality (quality);
  241. g.drawImageTransformed (*this, AffineTransform::scale (newWidth / (float) image->width,
  242. newHeight / (float) image->height), false);
  243. return newImage;
  244. }
  245. Image Image::convertedToFormat (PixelFormat newFormat) const
  246. {
  247. if (image == nullptr || newFormat == image->pixelFormat)
  248. return *this;
  249. const int w = image->width, h = image->height;
  250. const ScopedPointer<ImageType> type (image->createType());
  251. Image newImage (type->create (newFormat, w, h, false));
  252. if (newFormat == SingleChannel)
  253. {
  254. if (! hasAlphaChannel())
  255. {
  256. newImage.clear (getBounds(), Colours::black);
  257. }
  258. else
  259. {
  260. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  261. const BitmapData srcData (*this, 0, 0, w, h);
  262. for (int y = 0; y < h; ++y)
  263. {
  264. const PixelARGB* const src = (const PixelARGB*) srcData.getLinePointer (y);
  265. uint8* const dst = destData.getLinePointer (y);
  266. for (int x = 0; x < w; ++x)
  267. dst[x] = src[x].getAlpha();
  268. }
  269. }
  270. }
  271. else if (image->pixelFormat == SingleChannel && newFormat == Image::ARGB)
  272. {
  273. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  274. const BitmapData srcData (*this, 0, 0, w, h);
  275. for (int y = 0; y < h; ++y)
  276. {
  277. const PixelAlpha* const src = (const PixelAlpha*) srcData.getLinePointer (y);
  278. PixelARGB* const dst = (PixelARGB*) destData.getLinePointer (y);
  279. for (int x = 0; x < w; ++x)
  280. dst[x].set (src[x]);
  281. }
  282. }
  283. else
  284. {
  285. if (hasAlphaChannel())
  286. newImage.clear (getBounds());
  287. Graphics g (newImage);
  288. g.drawImageAt (*this, 0, 0);
  289. }
  290. return newImage;
  291. }
  292. NamedValueSet* Image::getProperties() const
  293. {
  294. return image == nullptr ? nullptr : &(image->userData);
  295. }
  296. //==============================================================================
  297. Image::BitmapData::BitmapData (Image& im, const int x, const int y, const int w, const int h, BitmapData::ReadWriteMode mode)
  298. : width (w), height (h)
  299. {
  300. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  301. jassert (im.image != nullptr);
  302. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= im.getWidth() && y + h <= im.getHeight());
  303. im.image->initialiseBitmapData (*this, x, y, mode);
  304. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  305. }
  306. Image::BitmapData::BitmapData (const Image& im, const int x, const int y, const int w, const int h)
  307. : width (w), height (h)
  308. {
  309. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  310. jassert (im.image != nullptr);
  311. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= im.getWidth() && y + h <= im.getHeight());
  312. im.image->initialiseBitmapData (*this, x, y, readOnly);
  313. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  314. }
  315. Image::BitmapData::BitmapData (const Image& im, BitmapData::ReadWriteMode mode)
  316. : width (im.getWidth()),
  317. height (im.getHeight())
  318. {
  319. // The BitmapData class must be given a valid image!
  320. jassert (im.image != nullptr);
  321. im.image->initialiseBitmapData (*this, 0, 0, mode);
  322. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  323. }
  324. Image::BitmapData::~BitmapData()
  325. {
  326. }
  327. Colour Image::BitmapData::getPixelColour (const int x, const int y) const noexcept
  328. {
  329. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  330. const uint8* const pixel = getPixelPointer (x, y);
  331. switch (pixelFormat)
  332. {
  333. case Image::ARGB: return Colour ( ((const PixelARGB*) pixel)->getUnpremultiplied());
  334. case Image::RGB: return Colour (*((const PixelRGB*) pixel));
  335. case Image::SingleChannel: return Colour (*((const PixelAlpha*) pixel));
  336. default: jassertfalse; break;
  337. }
  338. return Colour();
  339. }
  340. void Image::BitmapData::setPixelColour (const int x, const int y, Colour colour) const noexcept
  341. {
  342. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  343. uint8* const pixel = getPixelPointer (x, y);
  344. const PixelARGB col (colour.getPixelARGB());
  345. switch (pixelFormat)
  346. {
  347. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  348. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  349. case Image::SingleChannel: ((PixelAlpha*) pixel)->set (col); break;
  350. default: jassertfalse; break;
  351. }
  352. }
  353. //==============================================================================
  354. void Image::clear (const Rectangle<int>& area, Colour colourToClearTo)
  355. {
  356. const ScopedPointer<LowLevelGraphicsContext> g (image->createLowLevelContext());
  357. g->setFill (colourToClearTo);
  358. g->fillRect (area, true);
  359. }
  360. //==============================================================================
  361. Colour Image::getPixelAt (const int x, const int y) const
  362. {
  363. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  364. {
  365. const BitmapData srcData (*this, x, y, 1, 1);
  366. return srcData.getPixelColour (0, 0);
  367. }
  368. return Colour();
  369. }
  370. void Image::setPixelAt (const int x, const int y, Colour colour)
  371. {
  372. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  373. {
  374. const BitmapData destData (*this, x, y, 1, 1, BitmapData::writeOnly);
  375. destData.setPixelColour (0, 0, colour);
  376. }
  377. }
  378. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  379. {
  380. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  381. && hasAlphaChannel())
  382. {
  383. const BitmapData destData (*this, x, y, 1, 1, BitmapData::readWrite);
  384. if (isARGB())
  385. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  386. else
  387. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  388. }
  389. }
  390. template <class PixelType>
  391. struct PixelIterator
  392. {
  393. template <class PixelOperation>
  394. static void iterate (const Image::BitmapData& data, const PixelOperation& pixelOp)
  395. {
  396. for (int y = 0; y < data.height; ++y)
  397. {
  398. uint8* p = data.getLinePointer (y);
  399. for (int x = 0; x < data.width; ++x)
  400. {
  401. pixelOp (*(PixelType*) p);
  402. p += data.pixelStride;
  403. }
  404. }
  405. }
  406. };
  407. template <class PixelOperation>
  408. static void performPixelOp (const Image::BitmapData& data, const PixelOperation& pixelOp)
  409. {
  410. switch (data.pixelFormat)
  411. {
  412. case Image::ARGB: PixelIterator<PixelARGB> ::iterate (data, pixelOp); break;
  413. case Image::RGB: PixelIterator<PixelRGB> ::iterate (data, pixelOp); break;
  414. case Image::SingleChannel: PixelIterator<PixelAlpha>::iterate (data, pixelOp); break;
  415. default: jassertfalse; break;
  416. }
  417. }
  418. struct AlphaMultiplyOp
  419. {
  420. float alpha;
  421. template <class PixelType>
  422. void operator() (PixelType& pixel) const
  423. {
  424. pixel.multiplyAlpha (alpha);
  425. }
  426. };
  427. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  428. {
  429. jassert (hasAlphaChannel());
  430. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  431. performPixelOp (destData, AlphaMultiplyOp { amountToMultiplyBy });
  432. }
  433. struct DesaturateOp
  434. {
  435. template <class PixelType>
  436. void operator() (PixelType& pixel) const
  437. {
  438. pixel.desaturate();
  439. }
  440. };
  441. void Image::desaturate()
  442. {
  443. if (isARGB() || isRGB())
  444. {
  445. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  446. performPixelOp (destData, DesaturateOp());
  447. }
  448. }
  449. void Image::createSolidAreaMask (RectangleList<int>& result, const float alphaThreshold) const
  450. {
  451. if (hasAlphaChannel())
  452. {
  453. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  454. SparseSet<int> pixelsOnRow;
  455. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  456. for (int y = 0; y < srcData.height; ++y)
  457. {
  458. pixelsOnRow.clear();
  459. const uint8* lineData = srcData.getLinePointer (y);
  460. if (isARGB())
  461. {
  462. for (int x = 0; x < srcData.width; ++x)
  463. {
  464. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  465. pixelsOnRow.addRange (Range<int> (x, x + 1));
  466. lineData += srcData.pixelStride;
  467. }
  468. }
  469. else
  470. {
  471. for (int x = 0; x < srcData.width; ++x)
  472. {
  473. if (*lineData >= threshold)
  474. pixelsOnRow.addRange (Range<int> (x, x + 1));
  475. lineData += srcData.pixelStride;
  476. }
  477. }
  478. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  479. {
  480. const Range<int> range (pixelsOnRow.getRange (i));
  481. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  482. }
  483. result.consolidate();
  484. }
  485. }
  486. else
  487. {
  488. result.add (0, 0, getWidth(), getHeight());
  489. }
  490. }
  491. void Image::moveImageSection (int dx, int dy,
  492. int sx, int sy,
  493. int w, int h)
  494. {
  495. if (dx < 0)
  496. {
  497. w += dx;
  498. sx -= dx;
  499. dx = 0;
  500. }
  501. if (dy < 0)
  502. {
  503. h += dy;
  504. sy -= dy;
  505. dy = 0;
  506. }
  507. if (sx < 0)
  508. {
  509. w += sx;
  510. dx -= sx;
  511. sx = 0;
  512. }
  513. if (sy < 0)
  514. {
  515. h += sy;
  516. dy -= sy;
  517. sy = 0;
  518. }
  519. const int minX = jmin (dx, sx);
  520. const int minY = jmin (dy, sy);
  521. w = jmin (w, getWidth() - jmax (sx, dx));
  522. h = jmin (h, getHeight() - jmax (sy, dy));
  523. if (w > 0 && h > 0)
  524. {
  525. const int maxX = jmax (dx, sx) + w;
  526. const int maxY = jmax (dy, sy) + h;
  527. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, BitmapData::readWrite);
  528. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  529. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  530. const size_t lineSize = (size_t) (destData.pixelStride * w);
  531. if (dy > sy)
  532. {
  533. while (--h >= 0)
  534. {
  535. const int offset = h * destData.lineStride;
  536. memmove (dst + offset, src + offset, lineSize);
  537. }
  538. }
  539. else if (dst != src)
  540. {
  541. while (--h >= 0)
  542. {
  543. memmove (dst, src, lineSize);
  544. dst += destData.lineStride;
  545. src += destData.lineStride;
  546. }
  547. }
  548. }
  549. }