адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
@@ -0,0 +1,147 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
namespace detail
{
using ColorSpacePtr = CFUniquePtr<CGColorSpaceRef>;
using ContextPtr = CFUniquePtr<CGContextRef>;
using DataProviderPtr = CFUniquePtr<CGDataProviderRef>;
using ImagePtr = CFUniquePtr<CGImageRef>;
using GradientPtr = CFUniquePtr<CGGradientRef>;
using ColorPtr = CFUniquePtr<CGColorRef>;
using PathPtr = CFUniquePtr<CGPathRef>;
using MutablePathPtr = CFUniquePtr<CGMutablePathRef>;
}
//==============================================================================
class CoreGraphicsContext : public LowLevelGraphicsContext
{
public:
CoreGraphicsContext (CGContextRef context, float flipHeight);
~CoreGraphicsContext() override;
//==============================================================================
bool isVectorDevice() const override { return false; }
void setOrigin (Point<int>) override;
void addTransform (const AffineTransform&) override;
float getPhysicalPixelScaleFactor() const override;
bool clipToRectangle (const Rectangle<int>&) override;
bool clipToRectangleList (const RectangleList<int>&) override;
void excludeClipRectangle (const Rectangle<int>&) override;
void clipToPath (const Path&, const AffineTransform&) override;
void clipToImageAlpha (const Image&, const AffineTransform&) override;
bool clipRegionIntersects (const Rectangle<int>&) override;
Rectangle<int> getClipBounds() const override;
bool isClipEmpty() const override;
//==============================================================================
void saveState() override;
void restoreState() override;
void beginTransparencyLayer (float opacity) override;
void endTransparencyLayer() override;
//==============================================================================
void setFill (const FillType&) override;
void setOpacity (float) override;
void setImageBlendMode (BlendMode) override;
void setInterpolationQuality (Graphics::ResamplingQuality) override;
//==============================================================================
void fillAll() override;
void fillRect (const Rectangle<int>&, bool replaceExistingContents) override;
void fillRect (const Rectangle<float>&) override;
void fillRectList (const RectangleList<float>&) override;
void fillPath (const Path&, const AffineTransform&) override;
void strokePath (const Path& path, const PathStrokeType& strokeType, const AffineTransform& transform) override;
void drawImage (const Image& sourceImage, const AffineTransform&) override;
//==============================================================================
void drawLine (const Line<float>&) override;
void setFont (const Font&) override;
const Font& getFont() override;
void drawGlyphs (Span<const uint16_t>,
Span<const Point<float>>,
const AffineTransform&) override;
uint64_t getFrameId() const override { return 0; }
std::unique_ptr<ImageType> getPreferredImageTypeForTemporaryImages() const override
{
return std::make_unique<NativeImageType>();
}
void drawEllipse (const Rectangle<float>& area, float lineThickness) override;
void fillEllipse (const Rectangle<float>& area) override;
void drawRoundedRectangle (const Rectangle<float>& r, float cornerSize, float lineThickness) override;
void fillRoundedRectangle (const Rectangle<float>& r, float cornerSize) override;
void drawLineWithThickness (const Line<float>& line, float lineThickness) override;
private:
//==============================================================================
BlendMode activateBlendMode (BlendMode mode);
detail::ContextPtr context;
const CGFloat flipHeight;
detail::ColorSpacePtr rgbColourSpace, greyColourSpace;
mutable std::optional<Rectangle<int>> lastClipRect;
struct SavedState;
std::unique_ptr<SavedState> state;
OwnedArray<SavedState> stateStack;
BlendMode lastBlendMode = BlendMode::sourceOver;
template <class RectType>
CGRect convertToCGRectFlipped (RectType r) const noexcept;
void setContextClipToCurrentPath (bool useNonZeroWinding);
void drawCurrentPath (CGPathDrawingMode mode);
void dispatchDrawGradient();
void drawGradient();
void createPath (const Path&, const AffineTransform&) const;
void flip() const;
void applyTransform (const AffineTransform&) const;
void drawImage (const Image&, const AffineTransform&, bool fillEntireClipAsTiles);
bool clipToRectangleListWithoutTest (const RectangleList<float>&);
void fillCGRect (const CGRect&, bool replaceExistingContents);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext)
};
} // namespace juce
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,117 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
namespace
{
template <class RectType>
Rectangle<int> convertToRectInt (RectType r) noexcept
{
return { (int) r.origin.x,
(int) r.origin.y,
(int) r.size.width,
(int) r.size.height };
}
template <class RectType>
Rectangle<float> convertToRectFloat (RectType r) noexcept
{
return { (float) r.origin.x,
(float) r.origin.y,
(float) r.size.width,
(float) r.size.height };
}
template <class RectType>
CGRect convertToCGRect (RectType r) noexcept
{
return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
}
template <class PointType>
Point<float> convertToPointFloat (PointType p) noexcept
{
return { (float) p.x, (float) p.y };
}
template <typename PointType>
CGPoint convertToCGPoint (PointType p) noexcept
{
return CGPointMake ((CGFloat) p.x, (CGFloat) p.y);
}
template <class PointType>
Point<int> roundToIntPoint (PointType p) noexcept
{
return { roundToInt (p.x), roundToInt (p.y) };
}
#if JUCE_MAC
inline CGFloat getMainScreenHeight() noexcept
{
if ([[NSScreen screens] count] == 0)
return 0.0f;
return [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
}
inline NSRect flippedScreenRect (NSRect r) noexcept
{
r.origin.y = getMainScreenHeight() - (r.origin.y + r.size.height);
return r;
}
inline NSPoint flippedScreenPoint (NSPoint p) noexcept
{
p.y = getMainScreenHeight() - p.y;
return p;
}
#endif
}
CGImageRef juce_createCoreGraphicsImage (const Image&, CGColorSpaceRef);
CGContextRef juce_getImageContext (const Image&);
#if JUCE_IOS
Image juce_createImageFromUIImage (UIImage*);
#endif
#if JUCE_MAC
NSImage* imageToNSImage (const ScaledImage& image);
#endif
} // namespace juce
@@ -0,0 +1,800 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/* ScopedGeometryWithSink creates an ID2D1PathGeometry object with an open sink. */
struct ScopedGeometryWithSink
{
ScopedGeometryWithSink (ID2D1Factory* factory, D2D1_FILL_MODE fillMode)
{
if (const auto hr = factory->CreatePathGeometry (geometry.resetAndGetPointerAddress()); FAILED (hr))
return;
if (const auto hr = geometry->Open (sink.resetAndGetPointerAddress()); FAILED (hr))
return;
sink->SetFillMode (fillMode);
}
~ScopedGeometryWithSink()
{
if (sink == nullptr)
return;
const auto hr = sink->Close();
jassertquiet (SUCCEEDED (hr));
}
ComSmartPtr<ID2D1PathGeometry> geometry;
ComSmartPtr<ID2D1GeometrySink> sink;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScopedGeometryWithSink)
};
struct ScopedBlendCopy
{
explicit ScopedBlendCopy (ComSmartPtr<ID2D1DeviceContext1> c)
: ctx (c)
{
ctx->SetPrimitiveBlend (D2D1_PRIMITIVE_BLEND_COPY);
}
~ScopedBlendCopy()
{
ctx->SetPrimitiveBlend (blend);
}
ComSmartPtr<ID2D1DeviceContext1> ctx;
D2D1_PRIMITIVE_BLEND blend = ctx->GetPrimitiveBlend();
};
class PushedLayers
{
public:
PushedLayers() { pushedLayers.reserve (32); }
PushedLayers (const PushedLayers&) { pushedLayers.reserve (32); }
#if JUCE_DEBUG
~PushedLayers()
{
jassert (pushedLayers.empty());
}
#endif
void push (ComSmartPtr<ID2D1DeviceContext1> context, const D2D1_LAYER_PARAMETERS1& layerParameters)
{
pushedLayers.emplace_back (OwningLayer { layerParameters });
pushedLayers.back().push (context);
}
void push (ComSmartPtr<ID2D1DeviceContext1> context, const Rectangle<float>& r)
{
pushedLayers.emplace_back (r);
pushedLayers.back().push (context);
}
void popOne (ComSmartPtr<ID2D1DeviceContext1> context)
{
if (pushedLayers.empty())
return;
pushedLayers.back().pop (context);
pushedLayers.pop_back();
}
bool isEmpty() const
{
return pushedLayers.empty();
}
void fillGeometryWithNoLayersActive (ComSmartPtr<ID2D1DeviceContext1> ctx,
ComSmartPtr<ID2D1Geometry> geo,
ComSmartPtr<ID2D1Brush> brush)
{
ComSmartPtr<ID2D1Factory> factory;
ctx->GetFactory (factory.resetAndGetPointerAddress());
const auto hasGeoLayer = std::any_of (pushedLayers.begin(),
pushedLayers.end(),
[] (const auto& x) { return std::holds_alternative<OwningLayer> (x.var); });
const auto intersection = [&]() -> ComSmartPtr<ID2D1Geometry>
{
if (! hasGeoLayer)
return {};
const auto contextSize = ctx->GetPixelSize();
ComSmartPtr<ID2D1RectangleGeometry> rect;
factory->CreateRectangleGeometry (D2D1::RectF (0.0f,
0.0f,
(float) contextSize.width,
(float) contextSize.height),
rect.resetAndGetPointerAddress());
ComSmartPtr<ID2D1Geometry> clip = rect;
for (const auto& layer : pushedLayers)
{
ScopedGeometryWithSink scope { factory, D2D1_FILL_MODE_WINDING };
if (auto* l = std::get_if<OwningLayer> (&layer.var))
{
clip->CombineWithGeometry (l->geometry,
D2D1_COMBINE_MODE_INTERSECT,
l->params.maskTransform,
scope.sink);
}
else if (auto* r = std::get_if<Rectangle<float>> (&layer.var))
{
ComSmartPtr<ID2D1RectangleGeometry> temporaryRect;
factory->CreateRectangleGeometry (D2DUtilities::toRECT_F (*r),
temporaryRect.resetAndGetPointerAddress());
clip->CombineWithGeometry (temporaryRect,
D2D1_COMBINE_MODE_INTERSECT,
D2D1::Matrix3x2F::Identity(),
scope.sink);
}
clip = scope.geometry;
}
return clip;
}();
const auto clipWithGeo = [&]() -> ComSmartPtr<ID2D1Geometry>
{
if (intersection == nullptr)
return geo;
ScopedGeometryWithSink scope { factory, D2D1_FILL_MODE_WINDING };
intersection->CombineWithGeometry (geo,
D2D1_COMBINE_MODE_INTERSECT,
D2D1::Matrix3x2F::Identity(),
scope.sink);
return scope.geometry;
}();
if (intersection != nullptr)
{
std::for_each (pushedLayers.rbegin(),
pushedLayers.rend(),
[&] (const auto& layer) { layer.pop (ctx); });
}
{
const ScopedBlendCopy scope { ctx };
ctx->FillGeometry (clipWithGeo, brush);
}
if (intersection != nullptr)
{
pushedLayers.clear();
auto newLayer = D2D1::LayerParameters1();
newLayer.geometricMask = intersection;
push (ctx, newLayer);
}
}
private:
struct OwningLayer
{
explicit OwningLayer (const D2D1_LAYER_PARAMETERS1& p) : params (p) {}
D2D1_LAYER_PARAMETERS1 params;
ComSmartPtr<ID2D1Geometry> geometry { params.geometricMask, IncrementRef::yes };
ComSmartPtr<ID2D1Brush> brush { params.opacityBrush, IncrementRef::yes };
};
struct Layer
{
explicit Layer (std::variant<OwningLayer, Rectangle<float>> v) : var (std::move (v)) {}
void push (ComSmartPtr<ID2D1DeviceContext1> context) const
{
if (auto* layer = std::get_if<OwningLayer> (&var))
context->PushLayer (layer->params, nullptr);
else if (auto* rect = std::get_if<Rectangle<float>> (&var))
context->PushAxisAlignedClip (D2DUtilities::toRECT_F (*rect), D2D1_ANTIALIAS_MODE_ALIASED);
}
void pop (ComSmartPtr<ID2D1DeviceContext1> context) const
{
if (std::holds_alternative<OwningLayer> (var))
context->PopLayer();
else if (std::holds_alternative<Rectangle<float>> (var))
context->PopAxisAlignedClip();
}
std::variant<OwningLayer, Rectangle<float>> var;
};
std::vector<Layer> pushedLayers;
//==============================================================================
// PushedLayer represents a Direct2D clipping or transparency layer
//
// D2D layers have to be pushed into the device context. Every push has to be
// matched with a pop.
//
// D2D has special layers called "axis aligned clip layers" which clip to an
// axis-aligned rectangle. Pushing an axis-aligned clip layer must be matched
// with a call to deviceContext->PopAxisAlignedClip() in the reverse order
// in which the layers were pushed.
//
// So if the pushed layer stack is built like this:
//
// PushLayer()
// PushLayer()
// PushAxisAlignedClip()
// PushLayer()
//
// the layer stack must be popped like this:
//
// PopLayer()
// PopAxisAlignedClip()
// PopLayer()
// PopLayer()
//
// PushedLayer, PushedAxisAlignedClipLayer, and LayerPopper all exist just to unwind the
// layer stack accordingly.
};
struct PagesAndArea
{
Image imageHandle;
Span<const Direct2DPixelDataPage> pages;
Rectangle<int> area;
static PagesAndArea make (const Image& image, ComSmartPtr<ID2D1Device1> device)
{
using GetImage = Image (*) (const Image&);
constexpr GetImage converters[] { [] (const Image& i) { return i; },
[] (const Image& i) { return NativeImageType{}.convert (i); } };
for (auto* getImage : converters)
{
const auto converted = getImage (image);
const auto native = converted.getPixelData()->getNativeExtensions();
if (auto pages = native.getPages (device); ! pages.empty())
return PagesAndArea { converted, std::move (pages), converted.getBounds().withPosition (native.getTopLeft()) };
}
// Not sure how this could happen unless the NativeImageType no longer provides Windows native details...
jassertfalse;
return {};
}
};
struct Direct2DGraphicsContext::SavedState
{
public:
// Constructor for first stack entry
SavedState (Direct2DGraphicsContext& ownerIn,
Rectangle<int> frameSizeIn,
ComSmartPtr<ID2D1DeviceContext1> deviceContext,
ComSmartPtr<ID2D1SolidColorBrush>& colourBrushIn,
Direct2DDeviceResources& deviceResourcesIn)
: owner (ownerIn),
context (deviceContext),
currentBrush (colourBrushIn),
colourBrush (colourBrushIn),
deviceResources (deviceResourcesIn),
deviceSpaceClipList (frameSizeIn.toFloat())
{
}
void pushLayer (const D2D1_LAYER_PARAMETERS1& layerParameters)
{
layers.push (context, layerParameters);
}
void pushGeometryClipLayer (ComSmartPtr<ID2D1Geometry> geometry)
{
if (geometry != nullptr)
pushLayer (D2D1::LayerParameters1 (D2D1::InfiniteRect(), geometry));
}
void pushTransformedRectangleGeometryClipLayer (ComSmartPtr<ID2D1RectangleGeometry> geometry, const AffineTransform& transform)
{
JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME (owner.metrics, pushGeometryLayerTime)
jassert (geometry != nullptr);
auto layerParameters = D2D1::LayerParameters1 (D2D1::InfiniteRect(), geometry);
layerParameters.maskTransform = D2DUtilities::transformToMatrix (transform);
pushLayer (layerParameters);
}
void pushAliasedAxisAlignedClipLayer (const Rectangle<float>& r)
{
JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME (owner.metrics, pushAliasedAxisAlignedLayerTime)
layers.push (context, r);
}
void pushTransparencyLayer (float opacity)
{
pushLayer ({ D2D1::InfiniteRect(), nullptr, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, D2D1::IdentityMatrix(), opacity, {}, {} });
}
void popLayers()
{
while (! layers.isEmpty())
layers.popOne (context);
}
void popTopLayer()
{
layers.popOne (context);
}
void setFont (const Font& newFont)
{
font = newFont;
}
void setOpacity (float newOpacity)
{
fillType.setOpacity (newOpacity);
}
void clearFill()
{
linearGradient = nullptr;
radialGradient = nullptr;
bitmapBrush = nullptr;
currentBrush = nullptr;
}
/** Translate a JUCE FillType to a Direct2D brush */
void updateCurrentBrush()
{
if (fillType.isColour())
{
// Reuse the same colour brush
currentBrush = colourBrush;
}
else if (fillType.isTiledImage())
{
if (fillType.image.isNull())
return;
const auto device = D2DUtilities::getDeviceForContext (context);
const auto imageFormat = fillType.image.getFormat();
const auto targetFormat = imageFormat == Image::SingleChannel ? Image::ARGB : imageFormat;
const auto pagesAndArea = PagesAndArea::make (fillType.image.convertedToFormat (targetFormat), device);
if (pagesAndArea.pages.empty())
return;
const auto bitmap = pagesAndArea.pages.front().bitmap;
if (bitmap == nullptr)
return;
D2D1_BRUSH_PROPERTIES brushProps { fillType.getOpacity(), D2DUtilities::transformToMatrix (fillType.transform) };
auto bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
const auto hr = context->CreateBitmapBrush (bitmap,
bmProps,
brushProps,
bitmapBrush.resetAndGetPointerAddress());
if (FAILED (hr))
return;
currentBrush = bitmapBrush;
}
else if (fillType.isGradient())
{
if (fillType.gradient->isRadial)
{
radialGradient = deviceResources.radialGradientCache.get (*fillType.gradient, context, owner.metrics.get());
currentBrush = radialGradient;
}
else
{
linearGradient = deviceResources.linearGradientCache.get (*fillType.gradient, context, owner.metrics.get());
currentBrush = linearGradient;
}
}
updateColourBrush();
}
void updateColourBrush()
{
if (colourBrush && fillType.isColour())
{
auto colour = D2DUtilities::toCOLOR_F (fillType.colour);
colourBrush->SetColor (colour);
}
}
enum BrushTransformFlags
{
noTransforms = 0,
applyWorldTransform = 1,
applyFillTypeTransform = 2,
applyWorldAndFillTypeTransforms = applyFillTypeTransform | applyWorldTransform
};
ComSmartPtr<ID2D1Brush> getBrush (int flags = applyWorldAndFillTypeTransforms)
{
if (fillType.isInvisible())
return nullptr;
if (! fillType.isGradient() && ! fillType.isTiledImage())
return currentBrush;
AffineTransform transform{};
if ((flags & BrushTransformFlags::applyWorldTransform) != 0)
transform = currentTransform.getTransform();
if ((flags & BrushTransformFlags::applyFillTypeTransform) != 0)
transform = fillType.transform.followedBy (transform);
if (fillType.isGradient())
{
const auto& g = *fillType.gradient;
const auto p1 = g.point1;
const auto p2 = g.point2;
if (fillType.gradient->isRadial)
{
const auto endCircleOrigin = g.endRadius >= 0.0f ? p2 : p1;
const auto endRadius = g.endRadius >= 0.0f ? g.endRadius : p2.getDistanceFrom (p1);
const auto gradientOrigin = p1;
const auto gradientOffset = gradientOrigin - endCircleOrigin;
radialGradient->SetRadiusX (endRadius);
radialGradient->SetRadiusY (endRadius);
radialGradient->SetCenter ({ endCircleOrigin.x, endCircleOrigin.y });
radialGradient->SetGradientOriginOffset ({ gradientOffset.x, gradientOffset.y });
}
else
{
linearGradient->SetStartPoint ({ p1.x, p1.y });
linearGradient->SetEndPoint ({ p2.x, p2.y });
}
}
currentBrush->SetTransform (D2DUtilities::transformToMatrix (transform));
currentBrush->SetOpacity (fillType.getOpacity());
return currentBrush;
}
bool doesIntersectClipList (Rectangle<int> r) const noexcept
{
return deviceSpaceClipList.intersects (r.toFloat());
}
bool doesIntersectClipList (Rectangle<float> r) const noexcept
{
return deviceSpaceClipList.intersects (r);
}
bool doesIntersectClipList (Line<float> r) const noexcept
{
return doesIntersectClipList (Rectangle { r.getStart(), r.getEnd() }.expanded (1.0f));
}
bool doesIntersectClipList (const RectangleList<float>& other) const noexcept
{
return deviceSpaceClipList.intersects (other);
}
bool isCurrentTransformAxisAligned() const noexcept
{
return currentTransform.isOnlyTranslated || (currentTransform.complexTransform.mat01 == 0.0f && currentTransform.complexTransform.mat10 == 0.0f);
}
static String toString (const RenderingHelpers::TranslationOrTransform& t)
{
String s;
s << "Offset " << t.offset.toString() << newLine;
s << "Transform " << t.complexTransform.mat00 << " " << t.complexTransform.mat01 << " " << t.complexTransform.mat02 << " / ";
s << " " << t.complexTransform.mat10 << " " << t.complexTransform.mat11 << " " << t.complexTransform.mat12 << newLine;
return s;
}
PushedLayers layers;
Direct2DGraphicsContext& owner;
ComSmartPtr<ID2D1DeviceContext1> context;
ComSmartPtr<ID2D1Brush> currentBrush;
ComSmartPtr<ID2D1SolidColorBrush>& colourBrush; // reference to shared colour brush
ComSmartPtr<ID2D1BitmapBrush> bitmapBrush;
ComSmartPtr<ID2D1LinearGradientBrush> linearGradient;
ComSmartPtr<ID2D1RadialGradientBrush> radialGradient;
RenderingHelpers::TranslationOrTransform currentTransform;
Direct2DDeviceResources& deviceResources;
RectangleList<float> deviceSpaceClipList;
Font font { FontOptions{} };
FillType fillType;
D2D1_INTERPOLATION_MODE interpolationMode = D2D1_INTERPOLATION_MODE_LINEAR;
D2D1_COMPOSITE_MODE imageBlendMode = D2D1_COMPOSITE_MODE_SOURCE_OVER;
JUCE_LEAK_DETECTOR (SavedState)
};
//==============================================================================
bool Direct2DGraphicsContext::Pimpl::prepare()
{
if (! deviceResources.has_value())
deviceResources = Direct2DDeviceResources::create (getDeviceContext());
return deviceResources.has_value();
}
void Direct2DGraphicsContext::Pimpl::teardown()
{
deviceResources.reset();
}
bool Direct2DGraphicsContext::Pimpl::checkPaintReady()
{
return deviceResources.has_value();
}
Direct2DGraphicsContext::Pimpl::Pimpl (Direct2DGraphicsContext& ownerIn)
: owner (ownerIn)
{
directX->adapters.addListener (*this);
}
Direct2DGraphicsContext::Pimpl::~Pimpl()
{
directX->adapters.removeListener (*this);
popAllSavedStates();
}
auto Direct2DGraphicsContext::Pimpl::startFrame() -> SavedState*
{
prepare();
// Anything to paint?
const auto paintAreas = getPaintAreas();
const auto paintBounds = paintAreas.getBounds();
if (! getFrameSize().intersects (paintBounds) || paintBounds.isEmpty() || paintAreas.isEmpty())
return nullptr;
// Is Direct2D ready to paint?
if (! checkPaintReady())
return nullptr;
#if JUCE_DIRECT2D_METRICS
owner.metrics->startFrame();
#endif
JUCE_TRACE_EVENT_INT_RECT_LIST (etw::startD2DFrame, etw::direct2dKeyword, owner.getFrameId(), paintAreas);
const auto deviceContext = getDeviceContext();
// Init device context transform
resetTransform (deviceContext);
// Start drawing
deviceContext->SetTarget (getDeviceContextTarget());
deviceContext->BeginDraw();
// Init the save state stack and return the first saved state
return pushFirstSavedState (paintBounds);
}
HRESULT Direct2DGraphicsContext::Pimpl::finishFrame()
{
// Fully pop the state stack
popAllSavedStates();
// Finish drawing
// SetTarget(nullptr) so the device context doesn't hold a reference to the swap chain buffer
HRESULT hr = S_OK;
{
JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME (owner.metrics, endDrawDuration)
JUCE_SCOPED_TRACE_EVENT_FRAME (etw::endDraw, etw::direct2dKeyword, owner.getFrameId());
const auto deviceContext = getDeviceContext();
hr = deviceContext->EndDraw();
deviceContext->SetTarget (nullptr);
}
jassert (SUCCEEDED (hr));
if (FAILED (hr))
teardown();
#if JUCE_DIRECT2D_METRICS
owner.metrics->finishFrame();
#endif
return hr;
}
auto Direct2DGraphicsContext::Pimpl::getCurrentSavedState() const -> SavedState*
{
return ! savedClientStates.empty() ? savedClientStates.back().get() : nullptr;
}
auto Direct2DGraphicsContext::Pimpl::pushFirstSavedState (Rectangle<int> initialClipRegion) -> SavedState*
{
jassert (savedClientStates.empty());
savedClientStates.push_back (std::make_unique<SavedState> (owner,
initialClipRegion,
getDeviceContext(),
deviceResources->colourBrush,
*deviceResources));
return getCurrentSavedState();
}
auto Direct2DGraphicsContext::Pimpl::pushSavedState() -> SavedState*
{
jassert (! savedClientStates.empty());
savedClientStates.push_back (std::make_unique<SavedState> (*savedClientStates.back()));
return getCurrentSavedState();
}
auto Direct2DGraphicsContext::Pimpl::popSavedState() -> SavedState*
{
savedClientStates.back()->popLayers();
savedClientStates.pop_back();
return getCurrentSavedState();
}
void Direct2DGraphicsContext::Pimpl::popAllSavedStates()
{
while (! savedClientStates.empty())
popSavedState();
}
void Direct2DGraphicsContext::Pimpl::setDeviceContextTransform (AffineTransform transform)
{
setTransform (getDeviceContext(), transform);
}
void Direct2DGraphicsContext::Pimpl::resetDeviceContextTransform()
{
resetTransform (getDeviceContext());
}
bool Direct2DGraphicsContext::Pimpl::fillSpriteBatch (const RectangleList<float>& list)
{
if (! owner.currentState->fillType.isColour())
return false;
auto* rectangleListSpriteBatch = deviceResources->rectangleListSpriteBatch.get();
if (rectangleListSpriteBatch == nullptr)
return false;
const auto deviceContext = getDeviceContext();
if (deviceContext == nullptr)
return false;
owner.applyPendingClipList();
const auto& transform = owner.currentState->currentTransform;
if (transform.isOnlyTranslated)
{
auto translateRectangle = [&] (const Rectangle<float>& r) -> Rectangle<float>
{
return transform.translated (r);
};
return rectangleListSpriteBatch->fillRectangles (deviceContext,
list,
owner.currentState->fillType.colour,
translateRectangle,
owner.metrics.get());
}
if (owner.currentState->isCurrentTransformAxisAligned())
{
auto transformRectangle = [&] (const Rectangle<float>& r) -> Rectangle<float>
{
return transform.boundsAfterTransform (r);
};
return rectangleListSpriteBatch->fillRectangles (deviceContext,
list,
owner.currentState->fillType.colour,
transformRectangle,
owner.metrics.get());
}
auto checkRectangleWithoutTransforming = [&] (const Rectangle<float>& r) -> Rectangle<float>
{
return r;
};
ScopedTransform scopedTransform { *this, owner.currentState };
return rectangleListSpriteBatch->fillRectangles (deviceContext,
list,
owner.currentState->fillType.colour,
checkRectangleWithoutTransforming,
owner.metrics.get());
}
void Direct2DGraphicsContext::Pimpl::resetTransform (ID2D1DeviceContext1* context)
{
context->SetTransform (D2D1::IdentityMatrix());
}
void Direct2DGraphicsContext::Pimpl::setTransform (ID2D1DeviceContext1* context, AffineTransform newTransform)
{
context->SetTransform (D2DUtilities::transformToMatrix (newTransform));
}
DxgiAdapter::Ptr Direct2DGraphicsContext::Pimpl::findAdapter() const
{
return Direct2DDeviceResources::findAdapter (directX->adapters, getDeviceContext());
}
void Direct2DGraphicsContext::Pimpl::adapterCreated (DxgiAdapter::Ptr newAdapter)
{
const auto adapter = findAdapter();
if (adapter == nullptr || ! adapter->uniqueIDMatches (newAdapter))
teardown();
}
void Direct2DGraphicsContext::Pimpl::adapterRemoved (DxgiAdapter::Ptr expiringAdapter)
{
const auto adapter = findAdapter();
if (adapter != nullptr && adapter->uniqueIDMatches (expiringAdapter))
teardown();
}
} // namespace juce
@@ -0,0 +1,137 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
struct Direct2DGraphicsContext::Pimpl : private DxgiAdapterListener
{
public:
explicit Pimpl (Direct2DGraphicsContext& ownerIn);
~Pimpl() override;
virtual SavedState* startFrame();
virtual HRESULT finishFrame();
virtual bool prepare();
virtual void teardown();
virtual bool checkPaintReady();
virtual RectangleList<int> getPaintAreas() const = 0;
virtual Rectangle<int> getFrameSize() const = 0;
virtual ComSmartPtr<ID2D1DeviceContext1> getDeviceContext() const = 0;
virtual ComSmartPtr<ID2D1Image> getDeviceContextTarget() const = 0;
SavedState* getCurrentSavedState() const;
SavedState* pushFirstSavedState (Rectangle<int> initialClipRegion);
SavedState* pushSavedState();
SavedState* popSavedState();
void popAllSavedStates();
void setDeviceContextTransform (AffineTransform transform);
void resetDeviceContextTransform();
DxgiAdapter::Ptr getDefaultAdapter() const
{
return directX->adapters.getDefaultAdapter();
}
auto getDirect2DFactory() const
{
return directX->getD2DFactory();
}
auto getDirectWriteFactory() const
{
return directWrite->getDWriteFactory();
}
auto getDirectWriteFactory4() const
{
return directWrite->getDWriteFactory4();
}
auto& getFontCollection() const
{
return directWrite->getFonts();
}
uint64_t getFrameId() const
{
return owner.getFrameId();
}
Direct2DMetrics::Ptr getMetrics() const
{
return owner.metrics;
}
bool fillSpriteBatch (const RectangleList<float>& list);
virtual ComSmartPtr<IDWriteRenderingParams> getDefaultTextRenderingParams() const
{
ComSmartPtr<IDWriteRenderingParams> result;
getDirectWriteFactory()->CreateRenderingParams (result.resetAndGetPointerAddress());
return result;
}
DirectWriteGlyphRun glyphRun;
private:
static void resetTransform (ID2D1DeviceContext1* context);
static void setTransform (ID2D1DeviceContext1* context, AffineTransform newTransform);
DxgiAdapter::Ptr findAdapter() const;
void adapterCreated (DxgiAdapter::Ptr newAdapter) override;
void adapterRemoved (DxgiAdapter::Ptr expiringAdapter) override;
Direct2DGraphicsContext& owner;
SharedResourcePointer<DirectX> directX;
SharedResourcePointer<Direct2DFactories> directWrite;
std::optional<Direct2DDeviceResources> deviceResources;
std::vector<std::unique_ptr<Direct2DGraphicsContext::SavedState>> savedClientStates;
#if JUCE_DIRECT2D_METRICS
int64 paintStartTicks = 0;
#endif
JUCE_DECLARE_WEAK_REFERENCEABLE (Pimpl)
};
} // namespace juce
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,199 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
class Direct2DGraphicsContext : public LowLevelGraphicsContext
{
public:
Direct2DGraphicsContext();
~Direct2DGraphicsContext() override;
//==============================================================================
bool isVectorDevice() const override { return false; }
void setOrigin (Point<int>) override;
void addTransform (const AffineTransform&) override;
float getPhysicalPixelScaleFactor() const override;
bool clipToRectangle (const Rectangle<int>&) override;
bool clipToRectangleList (const RectangleList<int>&) override;
void excludeClipRectangle (const Rectangle<int>&) override;
void clipToPath (const Path&, const AffineTransform&) override;
void clipToImageAlpha (const Image&, const AffineTransform&) override;
bool clipRegionIntersects (const Rectangle<int>&) override;
Rectangle<int> getClipBounds() const override;
bool isClipEmpty() const override;
//==============================================================================
void saveState() override;
void restoreState() override;
void beginTransparencyLayer (float opacity) override;
void endTransparencyLayer() override;
//==============================================================================
void setFill (const FillType&) override;
void setOpacity (float) override;
void setImageBlendMode (BlendMode) override;
void setInterpolationQuality (Graphics::ResamplingQuality) override;
//==============================================================================
void fillRect (const Rectangle<int>&, bool replaceExistingContents) override;
void fillRect (const Rectangle<float>&) override;
void fillRectList (const RectangleList<float>&) override;
void fillPath (const Path&, const AffineTransform&) override;
void drawImage (const Image& sourceImage, const AffineTransform&) override;
//==============================================================================
void drawLine (const Line<float>&) override;
void setFont (const Font&) override;
const Font& getFont() override;
void drawGlyphs (Span<const uint16_t>,
Span<const Point<float>>,
const AffineTransform&) override;
//==============================================================================
// These methods were not originally part of the LowLevelGraphicsContext; they
// were added because Direct2D supports these drawing primitives directly.
// The specialised functions are more efficient than emulating the same behaviour, e.g.
// by drawing paths.
void drawLineWithThickness (const Line<float>&, float) override;
void drawEllipse (const Rectangle<float>& area, float lineThickness) override;
void fillEllipse (const Rectangle<float>& area) override;
void drawRect (const Rectangle<float>&, float) override;
void strokePath (const Path&, const PathStrokeType& strokeType, const AffineTransform&) override;
void drawRoundedRectangle (const Rectangle<float>& area, float cornerSize, float lineThickness) override;
void fillRoundedRectangle (const Rectangle<float>& area, float cornerSize) override;
//==============================================================================
bool startFrame (float dpiScale);
void endFrame();
virtual Image createSnapshot() const { return {}; }
uint64_t getFrameId() const override { return frame; }
std::unique_ptr<ImageType> getPreferredImageTypeForTemporaryImages() const override
{
return std::make_unique<NativeImageType>();
}
Direct2DMetrics::Ptr metrics;
protected:
template <typename Shape, typename Fn>
void paintPrimitive (const Shape& shape, Fn&& primitiveOp);
static Line<float> offsetShape (Line<float> a, Point<float> b);
static Rectangle<float> offsetShape (Rectangle<float> a, Point<float> b);
static RectangleList<float> offsetShape (RectangleList<float> a, Point<float> b);
struct SavedState;
SavedState* currentState = nullptr;
class PendingClipList
{
public:
void clipTo (Rectangle<float> i)
{
if (std::exchange (clipApplied, true))
list.clipTo (i);
else
list = i;
}
template <typename Numeric>
void clipTo (const RectangleList<Numeric>& other)
{
if (std::exchange (clipApplied, true))
{
list.clipTo (other);
}
else
{
list.clear();
for (const auto& r : other)
list.add (r.toFloat());
}
}
void subtract (Rectangle<float> i)
{
list.subtract (i);
clipApplied = true;
}
RectangleList<float> getList() const { return list; }
bool isClipApplied() const { return clipApplied; }
void reset (Rectangle<float> maxBounds)
{
list = maxBounds;
clipApplied = false;
}
private:
RectangleList<float> list;
bool clipApplied = false;
};
PendingClipList pendingClipList;
struct Pimpl;
virtual Pimpl* getPimpl() const noexcept = 0;
void resetPendingClipList();
void applyPendingClipList();
virtual void clearTargetBuffer() = 0;
struct ScopedTransform
{
ScopedTransform (Pimpl&, SavedState*);
ScopedTransform (Pimpl&, SavedState*, const AffineTransform& transform);
~ScopedTransform();
Pimpl& pimpl;
SavedState* state = nullptr;
};
uint64_t frame = 0;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DGraphicsContext)
};
} // namespace juce
@@ -0,0 +1,112 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
struct Direct2DImageContext::ImagePimpl : public Direct2DGraphicsContext::Pimpl
{
public:
ImagePimpl (Direct2DImageContext& ownerIn,
ComSmartPtr<ID2D1DeviceContext1> contextIn,
ComSmartPtr<ID2D1Bitmap1> bitmapIn,
const RectangleList<int>& paintAreasIn)
: Pimpl (ownerIn),
context (std::move (contextIn)),
bitmap (std::move (bitmapIn)),
paintAreas (paintAreasIn)
{
}
Rectangle<int> getFrameSize() const override
{
if (bitmap == nullptr)
return {};
const auto size = bitmap->GetSize();
return { (int) size.width, (int) size.height };
}
ComSmartPtr<ID2D1DeviceContext1> getDeviceContext() const override
{
return context;
}
ComSmartPtr<ID2D1Image> getDeviceContextTarget() const override
{
return bitmap;
}
RectangleList<int> getPaintAreas() const override
{
return paintAreas;
}
private:
ComSmartPtr<ID2D1DeviceContext1> context;
ComSmartPtr<ID2D1Bitmap1> bitmap;
RectangleList<int> paintAreas;
JUCE_DECLARE_WEAK_REFERENCEABLE (ImagePimpl)
};
//==============================================================================
Direct2DImageContext::Direct2DImageContext (ComSmartPtr<ID2D1DeviceContext1> context,
ComSmartPtr<ID2D1Bitmap1> bitmap,
const RectangleList<int>& paintAreas)
: pimpl (new ImagePimpl { *this, context, bitmap, paintAreas })
{
#if JUCE_DIRECT2D_METRICS
metrics = Direct2DMetricsHub::getInstance()->imageContextMetrics;
#endif
}
Direct2DImageContext::~Direct2DImageContext() = default;
ComSmartPtr<ID2D1DeviceContext1> Direct2DImageContext::getDeviceContext() const
{
return getPimpl()->getDeviceContext();
}
Direct2DGraphicsContext::Pimpl* Direct2DImageContext::getPimpl() const noexcept
{
return pimpl.get();
}
void Direct2DImageContext::clearTargetBuffer()
{
// The bitmap was already cleared when it was created; do nothing here
}
} // namespace juce
@@ -0,0 +1,59 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
class Direct2DImageContext : public Direct2DGraphicsContext
{
public:
Direct2DImageContext (ComSmartPtr<ID2D1DeviceContext1>,
ComSmartPtr<ID2D1Bitmap1>,
const RectangleList<int>&);
~Direct2DImageContext() override;
ComSmartPtr<ID2D1DeviceContext1> getDeviceContext() const;
private:
struct ImagePimpl;
std::unique_ptr<ImagePimpl> pimpl;
Pimpl* getPimpl() const noexcept override;
void clearTargetBuffer() override;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DImageContext)
};
} // namespace juce
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,267 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/* A set of pages that together represent a full virtual bitmap.
All pages in the set always share the same resource context.
Additionally, stores a reference to a software-backed bitmap, the content of which will
be copied to the pages when necessary in order to ensure that the software- and hardware-backed
bitmaps match.
*/
class Direct2DPixelDataPages
{
public:
using Page = Direct2DPixelDataPage;
enum class State
{
unsuitableToRead, // Image data is outdated
suitableToRead, // Image data is up-to-date with the backing data
cleared, // Implies suitableToRead
};
/* Creates a single page containing the provided bitmap and main-memory storage, marking the
hardware data as up-to-date.
*/
Direct2DPixelDataPages (ImagePixelDataBackupExtensions*, ComSmartPtr<ID2D1Bitmap1>, ImagePixelData::Ptr);
/* Allocates hardware storage for the provided software bitmap.
Depending on the initial state, will:
- mark the GPU images as needing to be copied from main memory before they are next accessed, or
- mark the GPU images as up-to-date, or
- clear the GPU images, then mark them as up-to-date
*/
Direct2DPixelDataPages (ImagePixelDataBackupExtensions*, ComSmartPtr<ID2D1Device1>, ImagePixelData::Ptr, State);
/* Returns all pages included in this set.
This will be called before reading from the pages (e.g. when drawing them).
Therefore, this function will check whether the hardware data is out-of-date and
copy from the software image if necessary before returning.
*/
Span<const Page> getPages();
/** Returns all pages without first syncing from main memory. */
Span<const Page> getPagesWithoutSync() const;
/* Marks this set as needing to be updated from the software image.
We don't actually do the copy until the next time that we need to read the hardware pages.
This is to avoid redundant copies in the common case that pages are only drawn on a single
device at a time.
*/
void markOutdated()
{
upToDate = false;
}
bool isUpToDate() const
{
return upToDate;
}
std::optional<Direct2DPixelDataPage> getPageContainingPoint (Point<int> pt) const;
private:
ImagePixelDataBackupExtensions* parentBackupExtensions = nullptr;
ImagePixelData::Ptr backingData;
std::vector<Direct2DPixelDataPage> pages;
bool upToDate = false;
};
/* Pixel data type providing accelerated access to cached Direct2D textures.
Direct2D bitmaps are device-dependent resources, but frequently a computer will
have multiple devices, e.g. if there are several GPUs available which is common for laptops.
In order to support a fast image type that can be drawn by any one of the available devices,
we store a software bitmap which acts as the source-of-truth, and cache per-device hardware
bitmaps alongside it. The caching mechanism tries to minimise the amount of redundant work.
When attempting to access hardware bitmaps, we first check the cache to see whether we've
previously allocated bitmaps for the requested device, and only create bitmaps if none already
exist.
We only copy from the software backup to hardware memory immediately before accessing the
bitmaps for a particular device, and then only if that hardware bitmap is outdated. All
hardware bitmaps are marked as outdated when a writeable BitmapData is created for the current
PixelData. When creating a low-level graphics context, all hardware bitmaps other than the
render target are marked as outdated.
*/
class Direct2DPixelData : public ImagePixelData,
private DxgiAdapterListener,
private ImagePixelDataBackupExtensions
{
public:
using Ptr = ReferenceCountedObjectPtr<Direct2DPixelData>;
using Page = Direct2DPixelDataPage;
using Pages = Direct2DPixelDataPages;
/* Creates image storage, taking ownership of the provided bitmap.
This will immediately copy the content of the image to the software backup, so that the
image can still be drawn if original device goes away.
*/
Direct2DPixelData (ComSmartPtr<ID2D1Device1>, ComSmartPtr<ID2D1Bitmap1>);
/* Creates software image storage of the requested size. */
Direct2DPixelData (Image::PixelFormat, int, int, bool);
~Direct2DPixelData() override;
/* Creates new image storage with content matching the content of this image. */
ImagePixelData::Ptr clone() override;
std::unique_ptr<ImageType> createType() const override
{
return std::make_unique<NativeImageType>();
}
/* Creates a graphics context that will use the default device to draw into hardware bitmaps
for that device. When the context is destroyed, the rendered hardware bitmap will be copied
back to software storage.
This PixelData may hold device resources for devices other than the default device. In that
case, the other device resources will be marked as outdated, to ensure that they are updated
from the software backup before they are next accessed.
*/
std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override;
/* Provides access to the software image storage.
If the bitmap data provides write access, then all device resources will be marked as
outdated, to ensure that they are updated from the software backup before they are next
accessed.
*/
void initialiseBitmapData (Image::BitmapData&, int, int, Image::BitmapData::ReadWriteMode) override;
void applyGaussianBlurEffectInArea (Rectangle<int>, float) override;
void applySingleChannelBoxBlurEffectInArea (Rectangle<int>, int) override;
void multiplyAllAlphasInArea (Rectangle<int>, float) override;
void desaturateInArea (Rectangle<int>) override;
/* This returns image data that is suitable for use when drawing with the provided context.
This image data should be treated as a read-only view - making modifications directly
through the Direct2D API will have unpredictable results.
If you want to render into this image using D2D, call createLowLevelContext.
*/
Span<const Page> getPagesForDevice (ComSmartPtr<ID2D1Device1>);
/* Utility function that just returns a pointer to the bitmap for the first page returned from
getPagesForContext.
*/
ComSmartPtr<ID2D1Bitmap1> getFirstPageForDevice (ComSmartPtr<ID2D1Device1> device)
{
const auto pages = getPagesForDevice (device);
return ! pages.empty() ? pages.front().bitmap : nullptr;
}
BackupExtensions* getBackupExtensions() override { return this; }
const BackupExtensions* getBackupExtensions() const override { return this; }
ImagePixelDataNativeExtensions getNativeExtensions() override;
private:
enum class State
{
initiallyUndefined,
initiallyCleared,
drawing,
drawn,
outdated,
};
Direct2DPixelData (ImagePixelData::Ptr, State);
auto getIteratorForDevice (ComSmartPtr<ID2D1Device1>);
Direct2DPixelDataPages& getPagesStructForDevice (ComSmartPtr<ID2D1Device1>);
/* Attempts to copy the content of the corresponding texture in graphics storage into
persistent software storage.
The argument specifies the device holding the texture that should be backed up.
Passing null will instead search through all devices to find which device has the most
recent copy of the image data.
In most cases it is unnecessary to call this function directly.
Returns true on success, i.e. the backup is already up-to-date or the backup was updated
successfully.
Returns false on failure. The backup process may fail if the graphics storage became
unavailable for some reason, such as an external GPU being disconnected, or a remote desktop
session ending. If this happens, the image content is *irrevocably lost* and will need to
be recreated.
*/
bool createPersistentBackup (ComSmartPtr<ID2D1Device1> deviceHint);
void moveValidatedImageSection (Point<int> destTopLeft, Rectangle<int> sourceRect) override;
struct Context;
std::unique_ptr<Context> createNativeContext();
template <typename Fn>
bool applyEffectInArea (Rectangle<int>, Fn&&);
void setBackupEnabled (bool) override;
bool isBackupEnabled() const override;
bool backupNow() override;
bool needsBackup() const override;
bool canBackup() const override;
static void copyPages (ComSmartPtr<ID2D1Device1>,
Direct2DPixelData&,
Direct2DPixelData&,
Point<int>,
Rectangle<int>);
void adapterCreated (DxgiAdapter::Ptr) override {}
void adapterRemoved (DxgiAdapter::Ptr adapter) override
{
if (adapter != nullptr)
pagesForDevice.erase (adapter->direct2DDevice);
if (mostRecentDevice == adapter->direct2DDevice)
mostRecentDevice = nullptr;
}
ComSmartPtr<ID2D1Device1> getMostRelevantDevice();
SharedResourcePointer<DirectX> directX;
ImagePixelData::Ptr backingData;
ComSmartPtr<ID2D1Device1> mostRecentDevice;
std::map<ComSmartPtr<ID2D1Device1>, Pages> pagesForDevice;
State state;
bool sync = true;
JUCE_LEAK_DETECTOR (Direct2DPixelData)
};
} // namespace juce
@@ -0,0 +1,132 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
#if JUCE_DIRECT2D_METRICS
namespace juce
{
String Direct2DMetricsHub::getProcessString() noexcept
{
auto processID = GetCurrentProcessId();
return String::toHexString ((pointer_sized_int) processID);
}
void Direct2DMetricsHub::HubPipeServer::messageReceived (const MemoryBlock& message)
{
int requestType = *(int*) message.getData();
switch (requestType)
{
case getValuesRequest:
{
ScopedLock locker { owner.lock };
auto foregroundWindow = GetFocus();
Direct2DMetrics::Ptr metrics = nullptr;
for (int i = 0; i < owner.metricsArray.size(); ++i)
{
auto arrayEntry = owner.metricsArray[i];
if (arrayEntry->windowHandle && arrayEntry->windowHandle == foregroundWindow)
{
metrics = arrayEntry;
break;
}
}
if (! metrics)
{
if (owner.lastMetrics && owner.metricsArray.contains (owner.lastMetrics))
metrics = owner.lastMetrics;
}
if (metrics)
{
MemoryBlock block { sizeof (GetValuesResponse), true };
auto* response = (GetValuesResponse*) block.getData();
response->responseType = getValuesRequest;
response->windowHandle = metrics->windowHandle;
for (size_t i = 0; i <= Direct2DMetrics::drawGlyphRunTime; ++i)
{
auto& accumulator = metrics->getAccumulator (i);
response->values[i].count = accumulator.getCount();
response->values[i].total = metrics->getSum (i);
response->values[i].average = accumulator.getAverage();
response->values[i].minimum = accumulator.getMinValue();
response->values[i].maximum = accumulator.getMaxValue();
response->values[i].stdDev = accumulator.getStandardDeviation();
}
// Track bitmap operations common to all device contexts
for (size_t i = Direct2DMetrics::createBitmapTime; i <= Direct2DMetrics::unmapBitmapTime; ++i)
{
auto& accumulator = owner.imageContextMetrics->getAccumulator (i);
response->values[i].count = accumulator.getCount();
response->values[i].total = metrics->getSum (i);
response->values[i].average = accumulator.getAverage();
response->values[i].minimum = accumulator.getMinValue();
response->values[i].maximum = accumulator.getMaxValue();
response->values[i].stdDev = accumulator.getStandardDeviation();
}
sendMessage (block);
owner.lastMetrics = metrics.get();
}
break;
}
case resetValuesRequest:
{
owner.resetAll();
break;
}
}
}
void Direct2DMetricsHub::resetAll()
{
ScopedLock locker { lock };
imageContextMetrics->reset();
for (auto metrics : metricsArray)
{
metrics->reset();
}
}
} // namespace juce
#endif
@@ -0,0 +1,314 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
#pragma once
#if JUCE_DIRECT2D_METRICS
namespace juce
{
struct Direct2DMetrics : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<Direct2DMetrics>;
#define DIRECT2D_PAINT_STAT_LIST \
DIRECT2D_PAINT_STAT (messageThreadPaintDuration) \
DIRECT2D_PAINT_STAT (swapChainThreadTime) \
DIRECT2D_PAINT_STAT (frameInterval) \
DIRECT2D_PAINT_STAT (endDrawDuration) \
DIRECT2D_PAINT_STAT (present1Duration) \
DIRECT2D_PAINT_STAT (createGeometryTime) \
DIRECT2D_PAINT_STAT (drawGeometryTime) \
DIRECT2D_PAINT_STAT (fillGeometryTime) \
DIRECT2D_PAINT_STAT (createFilledGRTime) \
DIRECT2D_PAINT_STAT (createStrokedGRTime) \
DIRECT2D_PAINT_STAT (drawGRTime) \
DIRECT2D_PAINT_STAT (createGradientTime) \
DIRECT2D_PAINT_STAT (pushAliasedAxisAlignedLayerTime) \
DIRECT2D_PAINT_STAT (pushGeometryLayerTime) \
DIRECT2D_PAINT_STAT (fillTranslatedRectTime) \
DIRECT2D_PAINT_STAT (fillAxisAlignedRectTime) \
DIRECT2D_PAINT_STAT (fillTransformedRectTime) \
DIRECT2D_PAINT_STAT (fillRectListTime) \
DIRECT2D_PAINT_STAT (drawImageTime) \
DIRECT2D_PAINT_STAT (spriteBatchTime) \
DIRECT2D_PAINT_STAT (spriteBatchSetupTime) \
DIRECT2D_PAINT_STAT (createSpriteSourceTime) \
DIRECT2D_PAINT_STAT (setSpritesTime) \
DIRECT2D_PAINT_STAT (addSpritesTime) \
DIRECT2D_PAINT_STAT (clearSpritesTime) \
DIRECT2D_PAINT_STAT (drawSpritesTime) \
DIRECT2D_PAINT_STAT (drawGlyphRunTime) \
DIRECT2D_PAINT_STAT (createBitmapTime) \
DIRECT2D_PAINT_STAT (mapBitmapTime) \
DIRECT2D_LAST_PAINT_STAT (unmapBitmapTime)
#define DIRECT2D_PAINT_STAT(name) name,
#define DIRECT2D_LAST_PAINT_STAT(name) name
enum
{
DIRECT2D_PAINT_STAT_LIST,
numStats
};
#undef DIRECT2D_PAINT_STAT
#undef DIRECT2D_LAST_PAINT_STAT
#define DIRECT2D_PAINT_STAT(name) #name,
#define DIRECT2D_LAST_PAINT_STAT(name) #name
StringArray const accumulatorNames { DIRECT2D_PAINT_STAT_LIST };
#undef DIRECT2D_PAINT_STAT
#undef DIRECT2D_LAST_PAINT_STAT
CriticalSection& lock;
String const name;
void* const windowHandle;
int64 const creationTime = Time::getMillisecondCounter();
double const millisecondsPerTick = 1000.0 / (double) Time::getHighResolutionTicksPerSecond();
int paintCount = 0;
int presentCount = 0;
int present1Count = 0;
int64 lastPaintStartTicks = 0;
uint64 lockAcquireMaxTicks = 0;
Direct2DMetrics (CriticalSection& lockIn, String nameIn, void* windowHandleIn)
: lock (lockIn),
name (nameIn),
windowHandle (windowHandleIn)
{
}
~Direct2DMetrics() = default;
void startFrame()
{
ScopedLock locker { lock };
zerostruct (sums);
}
void finishFrame()
{
}
void reset()
{
ScopedLock locker { lock };
for (auto& accumulator : runningAccumulators)
accumulator.reset();
lastPaintStartTicks = 0;
paintCount = 0;
present1Count = 0;
lockAcquireMaxTicks = 0;
}
auto& getAccumulator (size_t index) noexcept
{
return runningAccumulators[index];
}
auto getSum (size_t index) const noexcept
{
return sums[index];
}
void addValueTicks (size_t index, int64 ticks)
{
addValueMsec (index, Time::highResolutionTicksToSeconds (ticks) * 1000.0);
}
void addValueMsec (size_t index, double value)
{
ScopedLock locker { lock };
auto& accumulator = runningAccumulators[index];
switch (index)
{
case frameInterval:
if (accumulator.getCount() > 100)
{
accumulator.reset();
}
break;
}
accumulator.addValue (value);
sums[index] += value;
}
private:
std::array<StatisticsAccumulator<double>, numStats> runningAccumulators;
std::array<double, numStats> sums;
};
struct Direct2DScopedElapsedTime
{
Direct2DScopedElapsedTime (Direct2DMetrics::Ptr metricsIn, size_t accumulatorIndexIn)
: metrics (metricsIn),
accumulatorIndex (accumulatorIndexIn)
{
}
~Direct2DScopedElapsedTime()
{
auto finishTicks = Time::getHighResolutionTicks();
metrics->addValueTicks (accumulatorIndex, finishTicks - startTicks);
}
int64 startTicks = Time::getHighResolutionTicks();
Direct2DMetrics::Ptr metrics;
size_t accumulatorIndex;
};
class Direct2DMetricsHub : public DeletedAtShutdown
{
public:
Direct2DMetricsHub()
{
imageContextMetrics = new Direct2DMetrics { lock, "Image " + getProcessString(), nullptr };
add (imageContextMetrics);
}
~Direct2DMetricsHub() override
{
clearSingletonInstance();
}
void add (Direct2DMetrics::Ptr metrics)
{
metricsArray.insert (0, metrics);
}
void remove (Direct2DMetrics::Ptr metrics)
{
metricsArray.removeObject (metrics);
}
Direct2DMetrics::Ptr getMetricsForWindowHandle (void* windowHandle) noexcept
{
for (auto& metrics : metricsArray)
if (metrics->windowHandle == windowHandle)
return metrics;
return nullptr;
}
enum
{
getValuesRequest,
resetValuesRequest
};
struct MetricValues
{
size_t count;
double total;
double average;
double minimum;
double maximum;
double stdDev;
};
struct GetValuesResponse
{
int responseType;
void* windowHandle;
MetricValues values[Direct2DMetrics::numStats];
};
CriticalSection lock;
Direct2DMetrics::Ptr imageContextMetrics;
static constexpr int magicNumber = 0xd2d1;
JUCE_DECLARE_SINGLETON_INLINE (Direct2DMetricsHub, false)
private:
static String getProcessString() noexcept;
void resetAll();
struct HubPipeServer : public InterprocessConnection
{
explicit HubPipeServer (Direct2DMetricsHub& ownerIn)
: InterprocessConnection (false, magicNumber),
owner (ownerIn)
{
createPipe ("JUCEDirect2DMetricsHub:" + owner.getProcessString(), -1, true);
}
~HubPipeServer() override
{
disconnect();
}
void connectionMade() override
{
}
void connectionLost() override
{
}
void messageReceived (const MemoryBlock& message) override;
Direct2DMetricsHub& owner;
};
HubPipeServer hubPipeServer { *this };
ReferenceCountedArray<Direct2DMetrics> metricsArray;
Direct2DMetrics* lastMetrics = nullptr;
};
} // namespace juce
#define JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME(metrics, name) juce::Direct2DScopedElapsedTime scopedElapsedTime_##name { metrics, juce::Direct2DMetrics::name };
#else
namespace juce
{
struct Direct2DMetrics : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<Direct2DMetrics>;
};
} // namespace juce
#define JUCE_D2DMETRICS_SCOPED_ELAPSED_TIME(metrics, name)
#endif
@@ -0,0 +1,58 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/* A single bitmap that represents a subsection of a virtual bitmap. */
struct Direct2DPixelDataPage
{
/* The bounds of the stored bitmap inside the virtual bitmap. */
Rectangle<int> getBounds() const
{
if (bitmap == nullptr)
return {};
const auto size = bitmap->GetPixelSize();
return Rectangle { (int) size.width, (int) size.height }.withPosition (topLeft);
}
/* The stored subsection bitmap. */
ComSmartPtr<ID2D1Bitmap1> bitmap;
/* The top-left position of this virtual bitmap inside the virtual bitmap. */
Point<int> topLeft;
};
} // namespace juce
@@ -0,0 +1,542 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
StringArray Font::findAllTypefaceNamesImpl()
{
SharedResourcePointer<Direct2DFactories> factories;
return factories->getFonts().findAllTypefaceNames();
}
StringArray Font::findAllTypefaceStylesImpl (const String& family)
{
if (FontStyleHelpers::isPlaceholderFamilyName (family))
return findAllTypefaceStyles (FontStyleHelpers::getConcreteFamilyNameFromPlaceholder (family));
SharedResourcePointer<Direct2DFactories> factories;
return factories->getFonts().findAllTypefaceStyles (family);
}
class WindowsDirectWriteTypeface final : public Typeface
{
public:
Ptr cloneWithVariableSettings (Span<const FontVariableSetting> settings) const override
{
ComSmartPtr<IDWriteFontFace5> fontFace5;
ComSmartPtr<IDWriteFontResource> resource;
if (FAILED (dwFontFace->QueryInterface (fontFace5.resetAndGetPointerAddress()))
|| FAILED (fontFace5->GetFontResource (resource.resetAndGetPointerAddress())))
{
// This version of Windows doesn't support DirectWrite3 (Windows 10 Build 16299).
jassertfalse;
return {};
}
const auto registry = getNativeDetails()->getVariableRegistry();
auto sanitisedVariables = registry->sanitiseVariables (settings);
std::vector<DWRITE_FONT_AXIS_VALUE> axes (sanitisedVariables.size());
std::transform (sanitisedVariables.begin(),
sanitisedVariables.end(),
axes.begin(),
[] (FontVariableSetting var)
{
return DWRITE_FONT_AXIS_VALUE { (DWRITE_FONT_AXIS_TAG) ByteOrder::swap (var.tag.getTag()),
var.value };
});
ComSmartPtr<IDWriteFontFace5> configuredFontFace;
auto hr = resource->CreateFontFace (DWRITE_FONT_SIMULATIONS_NONE,
axes.data(),
(UINT32) axes.size(),
configuredFontFace.resetAndGetPointerAddress());
if (FAILED (hr))
return {};
HbFace hbFace { hb_directwrite_face_create (configuredFontFace), IncrementRef::no };
HbFont font { hb_font_create (hbFace.get()), IncrementRef::no };
const auto dwMetrics = getDwriteMetrics (*fontFace5);
return new WindowsDirectWriteTypeface (dwFont,
configuredFontFace,
std::move (font),
dwMetrics,
registry,
scopedCollectionRegistration,
std::move (sanitisedVariables));
}
static Ptr from (const Font& f)
{
const auto name = f.getTypefaceName();
const auto style = f.getTypefaceStyle();
SharedResourcePointer<Direct2DFactories> factories;
const auto family = factories->getFonts().getFamilyByName (name.toWideCharPointer());
if (family == nullptr)
return getLastResortTypeface (f);
// Try matching the typeface style first
const auto fonts = AggregateFontCollection::getAllFontsInFamily (family);
const auto matchingStyle = std::find_if (fonts.begin(), fonts.end(), [&] (const auto& ptr)
{
return style.compareIgnoreCase (getFontFaceName (ptr)) == 0;
});
if (matchingStyle != fonts.end())
return fromFont (*matchingStyle, nullptr, &f, MetricsMechanism::dwriteOnly);
// No matching typeface style, so let dwrite try to find a reasonable substitute
const auto weight = f.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
const auto italic = f.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
ComSmartPtr<IDWriteFont> dwFont;
if (FAILED (family->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, italic, dwFont.resetAndGetPointerAddress())) || dwFont == nullptr)
return {};
return fromFont (dwFont, nullptr, &f, MetricsMechanism::dwriteOnly);
}
static Ptr from (Span<const std::byte> blob)
{
SharedResourcePointer<Direct2DFactories> factories;
const auto dwFactory = factories->getDWriteFactory();
if (dwFactory == nullptr)
return {};
const auto collectionLoader = factories->getCollectionLoader();
const auto collectionKey = collectionLoader->addRawFontData ({ blob.data(), blob.size() });
ComSmartPtr<IDWriteFontCollection> customFontCollection;
if (FAILED (dwFactory->CreateCustomFontCollection (factories->getCollectionLoader(),
collectionKey.getRawData(),
(UINT32) collectionKey.size(),
customFontCollection.resetAndGetPointerAddress())))
return {};
if (customFontCollection == nullptr)
return {};
ComSmartPtr<IDWriteFontFamily> fontFamily;
if (FAILED (customFontCollection->GetFontFamily (0, fontFamily.resetAndGetPointerAddress())) || fontFamily == nullptr)
return {};
ComSmartPtr<IDWriteFont> dwFont;
if (FAILED (fontFamily->GetFont (0, dwFont.resetAndGetPointerAddress())) || dwFont == nullptr)
return {};
return fromFont (dwFont,
std::make_unique<ScopedCollectionRegistration> (customFontCollection),
nullptr,
MetricsMechanism::gdiWithDwriteFallback);
}
Ptr createSystemFallback (const String& c, const String& language) const override
{
auto factory = factories->getDWriteFactory().getInterface<IDWriteFactory2>();
if (factory == nullptr)
{
// System font fallback is unavailable before Windows 8.1
jassertfalse;
return {};
}
ComSmartPtr<IDWriteFontFallback> fallback;
if (FAILED (factory->GetSystemFontFallback (fallback.resetAndGetPointerAddress())) || fallback == nullptr)
return {};
ComSmartPtr analysisSource { new AnalysisSource (c, language), IncrementRef::no };
const auto originalName = getLocalisedFamilyName (*dwFont);
const auto mapped = factories->getFonts().mapCharacters (fallback,
analysisSource,
0,
numUtf16Words (c.toUTF16()),
originalName.toWideCharPointer(),
dwFont->GetWeight(),
dwFont->GetStyle(),
dwFont->GetStretch());
if (mapped.font == nullptr)
return {};
return fromFont (mapped.font, nullptr, nullptr, MetricsMechanism::dwriteOnly);
}
ComSmartPtr<IDWriteFontFace> getIDWriteFontFace() const { return dwFontFace; }
const Native* getNativeDetails() const override
{
return native.get();
}
static Ptr findSystemTypeface()
{
NONCLIENTMETRICS nonClientMetrics{};
nonClientMetrics.cbSize = sizeof (NONCLIENTMETRICS);
if (! SystemParametersInfo (SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICS), &nonClientMetrics, sizeof (NONCLIENTMETRICS)))
return {};
SharedResourcePointer<Direct2DFactories> factories;
ComSmartPtr<IDWriteGdiInterop> interop;
if (FAILED (factories->getDWriteFactory()->GetGdiInterop (interop.resetAndGetPointerAddress())) || interop == nullptr)
return {};
ComSmartPtr<IDWriteFont> dwFont;
if (FAILED (interop->CreateFontFromLOGFONT (&nonClientMetrics.lfMessageFont, dwFont.resetAndGetPointerAddress())) || dwFont == nullptr)
return {};
return fromFont (dwFont, nullptr, nullptr, MetricsMechanism::gdiWithDwriteFallback);
}
private:
static UINT32 numUtf16Words (const CharPointer_UTF16& str)
{
return (UINT32) (str.findTerminatingNull().getAddress() - str.getAddress());
}
class AnalysisSource final : public ComBaseClassHelper<IDWriteTextAnalysisSource>
{
public:
AnalysisSource (String cIn, String langIn)
: character (cIn), language (langIn) {}
~AnalysisSource() override = default;
JUCE_COMCALL GetLocaleName (UINT32, UINT32*, const WCHAR** localeName) noexcept override
{
*localeName = language.isNotEmpty() ? language.toWideCharPointer() : nullptr;
return S_OK;
}
JUCE_COMCALL GetNumberSubstitution (UINT32, UINT32*, IDWriteNumberSubstitution** substitution) noexcept override
{
*substitution = nullptr;
return S_OK;
}
DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() noexcept override
{
return DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
}
JUCE_COMCALL GetTextAtPosition (UINT32 textPosition, const WCHAR** textString, UINT32* textLength) noexcept override
{
if (textPosition == 0)
{
const auto utf16 = character.toUTF16();
*textString = utf16.getAddress();
*textLength = numUtf16Words (utf16);
}
else
{
// We don't expect this to be hit. If you see this, alert the JUCE team!
jassertfalse;
*textString = nullptr;
*textLength = 0;
}
return S_OK;
}
JUCE_COMCALL GetTextBeforePosition (UINT32, const WCHAR** textString, UINT32* textLength) noexcept override
{
// We don't expect this to be hit. If you see this, alert the JUCE team!
jassertfalse;
*textString = nullptr;
*textLength = 0;
return S_OK;
}
private:
String character;
String language;
};
static String getLocalisedFamilyName (IDWriteFont& font)
{
ComSmartPtr<IDWriteFontFamily> family;
if (FAILED (font.GetFontFamily (family.resetAndGetPointerAddress())) || family == nullptr)
return {};
return getLocalisedFamilyName (*family);
}
static String getLocalisedFamilyName (IDWriteFontFamily& fontFamily)
{
ComSmartPtr<IDWriteLocalizedStrings> familyNames;
if (FAILED (fontFamily.GetFamilyNames (familyNames.resetAndGetPointerAddress())) || familyNames == nullptr)
return {};
return getLocalisedName (familyNames);
}
static String getLocalisedStyle (IDWriteFont& font)
{
ComSmartPtr<IDWriteLocalizedStrings> faceNames;
if (FAILED (font.GetFaceNames (faceNames.resetAndGetPointerAddress())) || faceNames == nullptr)
return {};
return getLocalisedName (faceNames);
}
class ScopedCollectionRegistration
{
public:
explicit ScopedCollectionRegistration (ComSmartPtr<IDWriteFontCollection> x)
: collection (std::move (x))
{
factories->getFonts().addCollection (collection);
}
~ScopedCollectionRegistration()
{
factories->getFonts().removeCollection (collection);
}
private:
SharedResourcePointer<Direct2DFactories> factories;
ComSmartPtr<IDWriteFontCollection> collection;
};
WindowsDirectWriteTypeface (ComSmartPtr<IDWriteFont> font,
ComSmartPtr<IDWriteFontFace> face,
HbFont hbFontIn,
TypefaceVerticalMetrics metrics,
std::shared_ptr<VariableAxisRegistry> variableAxisRegistry = {},
std::shared_ptr<ScopedCollectionRegistration> registrationIn = {},
std::vector<FontVariableSetting> settings = {})
: WindowsDirectWriteTypeface { font,
face,
std::make_unique<Native> (TypefaceNativeOptions { std::move (hbFontIn),
metrics,
std::move (settings),
{},
this,
variableAxisRegistry }),
registrationIn }
{
}
WindowsDirectWriteTypeface (ComSmartPtr<IDWriteFont> font,
ComSmartPtr<IDWriteFontFace> face,
std::unique_ptr<Native> nativeIn,
std::shared_ptr<ScopedCollectionRegistration> registrationIn)
: Typeface (nativeIn->getTypefaceName(), nativeIn->getTypefaceStyle()),
dwFont (font),
dwFontFace (face),
native (std::move (nativeIn)),
scopedCollectionRegistration (std::move (registrationIn))
{
}
static TypefaceVerticalMetrics getDwriteMetrics (IDWriteFontFace& face)
{
DWRITE_FONT_METRICS dwriteFontMetrics{};
face.GetMetrics (&dwriteFontMetrics);
return TypefaceVerticalMetrics { (float) dwriteFontMetrics.ascent / (float) dwriteFontMetrics.designUnitsPerEm,
(float) dwriteFontMetrics.descent / (float) dwriteFontMetrics.designUnitsPerEm,
(float) dwriteFontMetrics.lineGap / (float) dwriteFontMetrics.designUnitsPerEm };
}
static std::optional<TypefaceVerticalMetrics> getGdiMetrics (hb_font_t* font)
{
hb_position_t ascent{}, descent{}, lineGap{};
if (! hb_ot_metrics_get_position (font, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_ASCENT, &ascent) ||
! hb_ot_metrics_get_position (font, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_DESCENT, &descent))
return {};
hb_ot_metrics_get_position (font, HB_OT_METRICS_TAG_VERTICAL_LINE_GAP, &lineGap);
const auto upem = (float) hb_face_get_upem (hb_font_get_face (font));
return TypefaceVerticalMetrics { (float) std::abs (ascent) / upem,
(float) std::abs (descent) / upem,
(float) lineGap / upem };
}
enum class MetricsMechanism
{
dwriteOnly,
gdiWithDwriteFallback,
};
static Ptr fromFont (ComSmartPtr<IDWriteFont> dwFont,
std::shared_ptr<ScopedCollectionRegistration> registration,
const Font* fontForSynthetics,
MetricsMechanism mm)
{
ComSmartPtr<IDWriteFontFace> dwFace;
if (FAILED (dwFont->CreateFontFace (dwFace.resetAndGetPointerAddress())) || dwFace == nullptr)
return {};
HbFace hbFace { hb_directwrite_face_create (dwFace), IncrementRef::no };
HbFont font { hb_font_create (hbFace.get()), IncrementRef::no };
const auto dwMetrics = getDwriteMetrics (*dwFace);
const auto metrics = mm == MetricsMechanism::gdiWithDwriteFallback
? getGdiMetrics (font.get()).value_or (dwMetrics)
: dwMetrics;
if (fontForSynthetics != nullptr)
FontStyleHelpers::initSynthetics (font.get(), *fontForSynthetics);
return new WindowsDirectWriteTypeface (dwFont,
dwFace,
std::move (font),
metrics,
{},
registration);
}
// This attempts to replicate the behaviour of the non-directwrite typeface lookup in JUCE 7 and older
static Ptr getLastResortTypeface (const Font& font)
{
auto* dc = CreateCompatibleDC (nullptr);
const ScopeGuard deleteDC { [&] { DeleteDC (dc); } };
SetMapperFlags (dc, 0);
SetMapMode (dc, MM_TEXT);
const auto style = font.getTypefaceStyle();
LOGFONTW lf{};
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lf.lfQuality = PROOF_QUALITY;
lf.lfItalic = (BYTE) (style.contains ("Italic") ? TRUE : FALSE);
lf.lfWeight = style.contains ("Bold") ? FW_BOLD : FW_NORMAL;
lf.lfHeight = -256;
font.getTypefaceName().copyToUTF16 (lf.lfFaceName, sizeof (lf.lfFaceName));
auto* hfont = CreateFontIndirectW (&lf);
const ScopeGuard deleteFont { [&] { DeleteObject (hfont); } };
auto* prevFont = hfont != nullptr ? SelectObject (dc, hfont) : nullptr;
const ScopeGuard reinstateFont { [&] { if (prevFont != nullptr) SelectObject (dc, prevFont); } };
SharedResourcePointer<Direct2DFactories> factories;
ComSmartPtr<IDWriteGdiInterop> interop;
if (FAILED (factories->getDWriteFactory()->GetGdiInterop (interop.resetAndGetPointerAddress())) || interop == nullptr)
return {};
ComSmartPtr<IDWriteFontFace> dwFontFace;
if (FAILED (interop->CreateFontFaceFromHdc (dc, dwFontFace.resetAndGetPointerAddress())) || dwFontFace == nullptr)
return {};
const auto dwFont = factories->getFonts().findFontForFace (dwFontFace);
if (dwFont == nullptr)
return {};
return fromFont (dwFont, nullptr, nullptr, MetricsMechanism::gdiWithDwriteFallback);
}
SharedResourcePointer<Direct2DFactories> factories;
ComSmartPtr<IDWriteFontCollection> collection;
ComSmartPtr<IDWriteFont> dwFont;
ComSmartPtr<IDWriteFontFace> dwFontFace;
std::unique_ptr<Native> native;
std::shared_ptr<ScopedCollectionRegistration> scopedCollectionRegistration;
};
struct DefaultFontNames
{
const String defaultSans { "Verdana" },
defaultSerif { "Times New Roman" },
defaultFixed { "Lucida Console" },
defaultFallback { "Tahoma" }; // (contains plenty of unicode characters)
};
Typeface::Ptr Font::Native::getDefaultPlatformTypefaceForFont (const Font& font)
{
static DefaultFontNames defaultNames;
Font newFont (font);
auto faceName = font.getTypefaceName();
if (faceName == getDefaultSansSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSans);
else if (faceName == getDefaultSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSerif);
else if (faceName == getDefaultMonospacedFontName()) newFont.setTypefaceName (defaultNames.defaultFixed);
if (font.getTypefaceStyle() == getDefaultStyle())
newFont.setTypefaceStyle ("Regular");
return Typeface::createSystemTypefaceFor (newFont);
}
auto Typeface::createFromFontImpl (const Font& font) -> Ptr
{
return WindowsDirectWriteTypeface::from (font);
}
auto Typeface::createFromDataImpl (Span<const std::byte> data) -> Ptr
{
return WindowsDirectWriteTypeface::from (data);
}
auto Typeface::findSystemTypeface() -> Ptr
{
return WindowsDirectWriteTypeface::findSystemTypeface();
}
void Typeface::scanFolderForFonts (const File&)
{
// TODO(reuk)
}
} // namespace juce
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,439 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/** Heap storage for a DirectWrite glyph run */
class DirectWriteGlyphRun
{
public:
void replace (Span<const Point<float>> positions, float scale);
auto* getAdvances() const { return advances.data(); }
auto* getOffsets() const { return offsets .data(); }
private:
std::vector<float> advances;
std::vector<DWRITE_GLYPH_OFFSET> offsets;
};
struct DxgiAdapter : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<DxgiAdapter>;
static Ptr create (ComSmartPtr<ID2D1Factory2>, ComSmartPtr<IDXGIAdapter1>);
bool uniqueIDMatches (ReferenceCountedObjectPtr<DxgiAdapter> other) const;
LUID getAdapterUniqueID() const;
ComSmartPtr<ID3D11Device> direct3DDevice;
ComSmartPtr<IDXGIDevice> dxgiDevice;
ComSmartPtr<ID2D1Device1> direct2DDevice;
ComSmartPtr<IDXGIAdapter1> dxgiAdapter;
std::vector<ComSmartPtr<IDXGIOutput>> dxgiOutputs;
private:
DxgiAdapter() = default;
};
struct DxgiAdapterListener
{
virtual ~DxgiAdapterListener() = default;
virtual void adapterCreated (DxgiAdapter::Ptr adapter) = 0;
virtual void adapterRemoved (DxgiAdapter::Ptr adapter) = 0;
};
class DxgiAdapters
{
public:
explicit DxgiAdapters (ComSmartPtr<ID2D1Factory2> d2dFactoryIn);
~DxgiAdapters();
void updateAdapters();
void releaseAdapters();
const auto& getAdapterArray() const
{
return adapterArray;
}
auto getFactory() const
{
return factory;
}
DxgiAdapter::Ptr getAdapterForHwnd (HWND hwnd) const;
DxgiAdapter::Ptr getDefaultAdapter() const;
void addListener (DxgiAdapterListener& l);
void removeListener (DxgiAdapterListener& l);
private:
static ComSmartPtr<IDXGIFactory2> makeDxgiFactory();
ComSmartPtr<ID2D1Factory2> d2dFactory;
// It's possible that we'll need to add/remove listeners from background threads, especially in
// the case that Images are created on a background thread.
ThreadSafeListenerList<DxgiAdapterListener> listeners;
ComSmartPtr<IDXGIFactory2> factory = makeDxgiFactory();
ReferenceCountedArray<DxgiAdapter> adapterArray;
};
class DirectX
{
public:
DirectX();
auto getD2DFactory() const { return d2dSharedFactory; }
private:
ComSmartPtr<ID2D1Factory2> d2dSharedFactory;
public:
DxgiAdapters adapters { d2dSharedFactory };
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectX)
};
struct D2DUtilities
{
template <typename Type>
static D2D1_RECT_F toRECT_F (const Rectangle<Type>& r)
{
return { (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom() };
}
template <typename Type>
static D2D1_RECT_U toRECT_U (const Rectangle<Type>& r)
{
return { (UINT32) r.getX(), (UINT32) r.getY(), (UINT32) r.getRight(), (UINT32) r.getBottom() };
}
template <typename Type>
static RECT toRECT (const Rectangle<Type>& r)
{
return { r.getX(), r.getY(), r.getRight(), r.getBottom() };
}
static Rectangle<int> toRectangle (const RECT& r)
{
return Rectangle<int>::leftTopRightBottom (r.left, r.top, r.right, r.bottom);
}
static Point<int> toPoint (POINT p) noexcept { return { p.x, p.y }; }
static POINT toPOINT (Point<int> p) noexcept { return { p.x, p.y }; }
static D2D1_POINT_2U toPOINT_2U (Point<int> p) { return D2D1::Point2U ((UINT32) p.x, (UINT32) p.y); }
static D2D1_COLOR_F toCOLOR_F (Colour c)
{
return { c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha() };
}
static D2D1::Matrix3x2F transformToMatrix (const AffineTransform& t)
{
return { t.mat00, t.mat10, t.mat01, t.mat11, t.mat02, t.mat12 };
}
static AffineTransform matrixToTransform (const D2D1_MATRIX_3X2_F& m)
{
return { m._11, m._21, m._31, m._12, m._22, m._32 };
}
static Rectangle<int> rectFromSize (D2D1_SIZE_U s)
{
return { (int) s.width, (int) s.height };
}
static ComSmartPtr<ID2D1Device1> getDeviceForContext (ComSmartPtr<ID2D1DeviceContext1> context);
};
//==============================================================================
struct Direct2DDeviceContext
{
static ComSmartPtr<ID2D1DeviceContext1> create (ComSmartPtr<ID2D1Device1> device);
static ComSmartPtr<ID2D1DeviceContext1> create (DxgiAdapter::Ptr adapter)
{
return adapter != nullptr ? create (adapter->direct2DDevice) : nullptr;
}
Direct2DDeviceContext() = delete;
};
//==============================================================================
struct Direct2DBitmap
{
Direct2DBitmap() = delete;
static ComSmartPtr<ID2D1Bitmap1> toBitmap (const Image& image,
ComSmartPtr<ID2D1DeviceContext1> deviceContext,
Image::PixelFormat outputFormat);
static ComSmartPtr<ID2D1Bitmap1> createBitmap (ComSmartPtr<ID2D1DeviceContext1> deviceContext,
Image::PixelFormat format,
D2D_SIZE_U size,
D2D1_BITMAP_OPTIONS options);
};
//==============================================================================
/* UpdateRegion extracts the invalid region for a window
UpdateRegion is used to service WM_PAINT to add the invalid region of a window to
deferredRepaints. UpdateRegion marks the region as valid, and the region should be painted on the
next vblank.
This is similar to the invalid region update in HWNDComponentPeer::handlePaintMessage()
*/
class UpdateRegion
{
public:
void findRECTAndValidate (HWND windowHandle);
void clear()
{
numRect = 0;
}
Span<const RECT> getRects() const
{
auto header = (RGNDATAHEADER const* const) block.getData();
auto* data = (RECT*) (header + 1);
return { data, numRect };
}
private:
MemoryBlock block { 1024 };
uint32 numRect = 0;
};
class LinearGradientCache
{
public:
ComSmartPtr<ID2D1LinearGradientBrush> get (const ColourGradient& gradient,
ComSmartPtr<ID2D1DeviceContext1> deviceContext,
Direct2DMetrics* metrics);
private:
LruCache<ColourGradient, ComSmartPtr<ID2D1LinearGradientBrush>> cache;
};
class RadialGradientCache
{
public:
ComSmartPtr<ID2D1RadialGradientBrush> get (const ColourGradient& gradient,
ComSmartPtr<ID2D1DeviceContext1> deviceContext,
Direct2DMetrics* metrics);
private:
LruCache<ColourGradient, ComSmartPtr<ID2D1RadialGradientBrush>> cache;
};
class RectangleListSpriteBatch
{
struct TransformCallback
{
virtual Rectangle<float> transform (Rectangle<float>) const = 0;
};
public:
RectangleListSpriteBatch() = default;
~RectangleListSpriteBatch();
void release();
template <typename TransformRectangle>
bool fillRectangles (ComSmartPtr<ID2D1DeviceContext1> deviceContext,
const RectangleList<float>& rectangles,
const Colour colour,
TransformRectangle&& transformRectangle,
[[maybe_unused]] Direct2DMetrics* metrics)
{
struct Callback : public TransformCallback
{
explicit Callback (TransformRectangle&& x) : fn (x) {}
Rectangle<float> transform (Rectangle<float> x) const override { return fn (x); }
TransformRectangle fn;
};
const Callback callback { std::forward<TransformRectangle> (transformRectangle) };
return fillRectanglesImpl (deviceContext, rectangles, colour, callback, metrics);
}
private:
ComSmartPtr<ID2D1SpriteBatch> getSpriteBatch (ID2D1DeviceContext3& dc, uint32 key);
bool fillRectanglesImpl (ComSmartPtr<ID2D1DeviceContext1> deviceContext,
const RectangleList<float>& rectangles,
Colour colour,
const TransformCallback& transformRectangle,
[[maybe_unused]] Direct2DMetrics* metrics);
static constexpr uint32 rectangleSize = 32;
ComSmartPtr<ID2D1BitmapRenderTarget> whiteRectangle;
HeapBlock<D2D1_RECT_F> destinations;
size_t destinationsCapacity = 0;
LruCache<uint32, ComSmartPtr<ID2D1SpriteBatch>, 8> spriteBatches;
};
class Direct2DDeviceResources
{
public:
static DxgiAdapter::Ptr findAdapter (const DxgiAdapters& adapters, ID2D1Bitmap1* bitmap);
static DxgiAdapter::Ptr findAdapter (const DxgiAdapters& dxgiAdapters, IDXGIDevice* dxgiDevice);
static DxgiAdapter::Ptr findAdapter (const DxgiAdapters& dxgiAdapters, ID2D1DeviceContext1* context);
static LUID getLUID (ComSmartPtr<IDXGIAdapter1> adapter);
static std::optional<Direct2DDeviceResources> create (ComSmartPtr<ID2D1DeviceContext1> context);
ComSmartPtr<ID2D1SolidColorBrush> colourBrush;
LinearGradientCache linearGradientCache;
RadialGradientCache radialGradientCache;
std::unique_ptr<RectangleListSpriteBatch> rectangleListSpriteBatch;
private:
Direct2DDeviceResources() = default;
};
//==============================================================================
class AggregateFontCollection
{
public:
explicit AggregateFontCollection (ComSmartPtr<IDWriteFontCollection> baseCollection);
StringArray findAllTypefaceNames();
static std::vector<ComSmartPtr<IDWriteFont>> getAllFontsInFamily (IDWriteFontFamily* fontFamily);
StringArray findAllTypefaceStyles (const String& family);
ComSmartPtr<IDWriteFontFamily> getFamilyByName (const wchar_t* name);
ComSmartPtr<IDWriteFont> findFontForFace (IDWriteFontFace* face);
void addCollection (ComSmartPtr<IDWriteFontCollection> collection);
void removeCollection (ComSmartPtr<IDWriteFontCollection> collection);
struct MapResult
{
ComSmartPtr<IDWriteFont> font;
UINT32 length{};
float scale{};
};
/* Tries matching against each collection in turn.
If any collection is able to match the entire string, then uses the appropriate font
from that collection.
Otherwise, returns the font that is able to match the longest sequence of characters,
preferring user-provided fonts.
*/
MapResult mapCharacters (IDWriteFontFallback* fallback,
IDWriteTextAnalysisSource* analysisSource,
UINT32 textPosition,
UINT32 textLength,
wchar_t const* baseFamilyName,
DWRITE_FONT_WEIGHT baseWeight,
DWRITE_FONT_STYLE baseStyle,
DWRITE_FONT_STRETCH baseStretch) noexcept;
private:
std::vector<ComSmartPtr<IDWriteFontCollection>> collections;
std::mutex mutex;
};
class DirectWriteCustomFontCollectionLoader final : public ComBaseClassHelper<IDWriteFontCollectionLoader>
{
public:
explicit DirectWriteCustomFontCollectionLoader (IDWriteFactory& factoryIn);
~DirectWriteCustomFontCollectionLoader() override;
Uuid addRawFontData (Span<const std::byte> blob);
HRESULT WINAPI CreateEnumeratorFromKey (IDWriteFactory* factoryIn,
const void* collectionKey,
UINT32 collectionKeySize,
IDWriteFontFileEnumerator** fontFileEnumerator) noexcept override;
private:
class MemoryFontFileLoader;
class FontFileEnumerator;
ComSmartPtr<MemoryFontFileLoader> findLoaderForUuid (const Uuid&) const;
IDWriteFactory& factory;
// Allows lookup of Uuids of all loaders with data matching a particular hash
std::map<size_t, std::vector<Uuid>> uuidsForHash;
// Sorted by Uuid
std::vector<ComSmartPtr<MemoryFontFileLoader>> loaders;
};
//==============================================================================
class Direct2DFactories
{
public:
Direct2DFactories();
~Direct2DFactories();
[[nodiscard]] ComSmartPtr<IDWriteFactory> getDWriteFactory() const { return directWriteFactory; }
[[nodiscard]] ComSmartPtr<IDWriteFactory4> getDWriteFactory4() const { return directWriteFactory4; }
[[nodiscard]] AggregateFontCollection& getFonts() { jassert (fonts.has_value()); return *fonts; }
[[nodiscard]] ComSmartPtr<DirectWriteCustomFontCollectionLoader> getCollectionLoader() const { return collectionLoader; }
private:
DynamicLibrary direct2dDll { "d2d1.dll" }, directWriteDll { "DWrite.dll" };
const ComSmartPtr<ID2D1Factory> d2dFactory;
const ComSmartPtr<IDWriteFactory> directWriteFactory;
const ComSmartPtr<DirectWriteCustomFontCollectionLoader> collectionLoader;
const ComSmartPtr<IDWriteFactory4> directWriteFactory4 = directWriteFactory.getInterface<IDWriteFactory4>();
std::optional<AggregateFontCollection> fonts;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DFactories)
};
} // namespace juce
@@ -0,0 +1,310 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
#pragma once
namespace juce::etw
{
//==============================================================================
/*
The following XML can be passed to Windows Performance Recorder (WPR) to enable tracing from
JUCE projects.
- Save the XML into a file with the name JUCE.wprp
- Run the following command from an admin command prompt to start capture. If you use a Developer
Command Prompt, wpr.exe should be found on the PATH already.
- <path to wpr>\wpr.exe -start JUCE.wprp
- Start your JUCE project
- Run the following command from an admin command prompt to stop capture
- <path to wpr>\wpr.exe -stop TraceCaptureFile.etl description
<?xml version="1.0" encoding="utf-8"?>
<WindowsPerformanceRecorder Version="1.0" Author="Microsoft Corporation" Copyright="Microsoft Corporation" Company="Microsoft Corporation">
<Profiles>
<EventCollector Id="EventCollector_JUCETraceLogProvider" Name="JUCETraceLogProvider">
<BufferSize Value="64" />
<Buffers Value="4" />
</EventCollector>
<EventProvider Id="EventProvider_JUCETraceLogProvider" Name="6A612E78-284D-4DDB-877A-5F521EB33132" />
<Profile Id="JUCETraceLogProvider.Verbose.File" Name="JUCETraceLogProvider" Description="JUCETraceLogProvider" LoggingMode="File" DetailLevel="Verbose">
<Collectors>
<EventCollectorId Value="EventCollector_JUCETraceLogProvider">
<EventProviders>
<EventProviderId Value="EventProvider_JUCETraceLogProvider" />
</EventProviders>
</EventCollectorId>
</Collectors>
</Profile>
<Profile Id="JUCETraceLogProvider.Light.File" Name="JUCETraceLogProvider" Description="JUCETraceLogProvider" Base="JUCETraceLogProvider.Verbose.File" LoggingMode="File" DetailLevel="Light" />
<Profile Id="JUCETraceLogProvider.Verbose.Memory" Name="JUCETraceLogProvider" Description="JUCETraceLogProvider" Base="JUCETraceLogProvider.Verbose.File" LoggingMode="Memory" DetailLevel="Verbose" />
<Profile Id="JUCETraceLogProvider.Light.Memory" Name="JUCETraceLogProvider" Description="JUCETraceLogProvider" Base="JUCETraceLogProvider.Verbose.File" LoggingMode="Memory" DetailLevel="Light" />
</Profiles>
</WindowsPerformanceRecorder>
*/
//==============================================================================
enum
{
paintKeyword = 1 << 0,
sizeKeyword = 1 << 1,
graphicsKeyword = 1 << 2,
crucialKeyword = 1 << 3,
threadPaintKeyword = 1 << 4,
messageKeyword = 1 << 5,
direct2dKeyword = 1 << 6,
softwareRendererKeyword = 1 << 7,
resourcesKeyword = 1 << 8,
componentKeyword = 1 << 9,
spriteKeyword = 1 << 10
};
enum : uint64_t
{
direct2dHwndPaintStart,
direct2dHwndPaintEnd,
endDraw,
present1SwapChainStart,
present1SwapChainEnd,
swapChainThreadEvent,
waitForVBlankDone,
callVBlankListeners,
resize,
createResource,
presentIdleFrame,
direct2dImagePaintStart,
direct2dImagePaintEnd,
startD2DFrame,
flush,
startGDIFrame,
startGDIImage,
endGDIFrame,
createLowLevelGraphicsContext,
createDeviceResources,
createSwapChain,
createSwapChainBuffer,
createPeer,
mapBitmap,
unmapBitmap,
createDirect2DBitmapFromImage,
createDirect2DBitmap,
setOrigin,
addTransform,
clipToRectangle,
clipToRectangleList,
excludeClipRectangle,
clipToPath,
clipToImageAlpha,
saveState,
restoreState,
beginTransparencyLayer,
endTransparencyLayer,
setFill,
setOpacity,
setInterpolationQuality,
fillRect,
fillRectReplace,
fillRectList,
drawRectTranslated,
drawRectTransformed,
drawRect,
fillPath,
strokePath,
drawPath,
drawImage,
drawLine,
setFont,
drawGlyph,
drawGlyphRun,
drawTextLayout,
drawRoundedRectangle,
fillRoundedRectangle,
drawEllipse,
fillEllipse,
filledGeometryRealizationCacheHit,
filledGeometryRealizationCreated,
strokedGeometryRealizationCacheHit,
strokedGeometryRealizationCreated,
releaseGeometryRealization,
gradientCacheHit,
gradientCreated,
releaseGradient,
nativeDropShadow,
nativeGlowEffect,
resetToDefaultState,
reduceClipRegionRectangle,
reduceClipRegionRectangleList,
reduceClipRegionImage,
reduceClipRegionPath,
excludeClipRegion,
fillAll,
repaint,
paintComponentAndChildren,
paintWithinParentContext,
createSpriteBatch,
setSprites,
addSprites,
drawSprites,
};
#if JUCE_WINDOWS && JUCE_ETW_TRACELOGGING
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wc++98-compat-extra-semi", "-Wmissing-prototypes", "-Wgnu-zero-variadic-macro-arguments")
TRACELOGGING_DECLARE_PROVIDER (JUCETraceLogProvider);
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
#define JUCE_WRITE_TRACE_LOG_VA(code, keyword, ...) \
TraceLoggingWrite (::juce::etw::JUCETraceLogProvider, \
#code, \
TraceLoggingLevel (TRACE_LEVEL_INFORMATION), \
TraceLoggingKeyword ((UINT64) keyword), \
__VA_ARGS__, \
TraceLoggingValue ((unsigned short) code, "code"))
#define JUCE_WRITE_TRACE_LOG(code, keyword) \
TraceLoggingWrite (::juce::etw::JUCETraceLogProvider, \
#code, \
TraceLoggingLevel (TRACE_LEVEL_INFORMATION), \
TraceLoggingKeyword ((UINT64) keyword), \
TraceLoggingValue ((unsigned short) code, "code"))
#else
#define JUCE_WRITE_TRACE_LOG_VA(code, keyword, ...)
#define JUCE_WRITE_TRACE_LOG(code, keyword)
#endif
template <typename Number>
auto toVector (const Rectangle<Number>& r)
{
return std::vector { r.getX(), r.getY(), r.getWidth(), r.getHeight() };
}
template <typename Number>
auto toVector (const RectangleList<Number>& list)
{
std::vector<Number> result;
for (const auto& r : list)
result.insert (result.end(), { r.getX(), r.getY(), r.getWidth(), r.getHeight() });
return result;
}
//==============================================================================
#if JUCE_WINDOWS && JUCE_ETW_TRACELOGGING
#define JUCE_SCOPED_TRACE_EVENT_FRAME(code, keyword, frameNumber) \
const ScopeGuard scopedEvent_ ## __LINE__ { [start = ::juce::Time::getHighResolutionTicks(), frame = (frameNumber)] \
{ \
const auto ticks = ::juce::Time::getHighResolutionTicks() - start; \
JUCE_WRITE_TRACE_LOG_VA (code, keyword, TraceLoggingValue (ticks), TraceLoggingValue (frame)); \
} };
#define JUCE_SCOPED_TRACE_EVENT_FRAME_RECT_F32(code, keyword, frameNumber, rectIn) \
const ScopeGuard scopedEvent_ ## __LINE__ { [start = ::juce::Time::getHighResolutionTicks(), frame = (frameNumber), rect = (rectIn)] \
{ \
const auto ticks = ::juce::Time::getHighResolutionTicks() - start; \
const std::vector<float> vec = ::juce::etw::toVector (rect); \
JUCE_WRITE_TRACE_LOG_VA (code, \
keyword, \
TraceLoggingValue (ticks), \
TraceLoggingValue (frame), \
TraceLoggingFloat32Array (vec.data(), (UINT16) vec.size(), "rect")); \
} };
#define JUCE_SCOPED_TRACE_EVENT_FRAME_RECT_I32(code, keyword, frameNumber, rectIn) \
const ScopeGuard scopedEvent_ ## __LINE__ { [start = ::juce::Time::getHighResolutionTicks(), frame = (frameNumber), rect = (rectIn)] \
{ \
const auto ticks = ::juce::Time::getHighResolutionTicks() - start; \
const std::vector<INT32> vec = ::juce::etw::toVector (rect); \
JUCE_WRITE_TRACE_LOG_VA (code, \
keyword, \
TraceLoggingValue (ticks), \
TraceLoggingValue (frame), \
TraceLoggingInt32Array (vec.data(), (UINT16) vec.size(), "rect")); \
} };
#else
#define JUCE_SCOPED_TRACE_EVENT_FRAME(code, keyword, frameNumber)
#define JUCE_SCOPED_TRACE_EVENT_FRAME_RECT_F32(code, keyword, frameNumber, rectIn)
#define JUCE_SCOPED_TRACE_EVENT_FRAME_RECT_I32(code, keyword, frameNumber, rectIn)
#endif
//==============================================================================
#define JUCE_TRACE_LOG_D2D_PAINT_CALL(code, frameNumber) \
JUCE_WRITE_TRACE_LOG_VA (code, etw::paintKeyword | etw::direct2dKeyword, TraceLoggingValue ((UINT64) frameNumber, "frame"))
#define JUCE_TRACE_LOG_JUCE_VBLANK_THREAD_EVENT \
JUCE_WRITE_TRACE_LOG (etw::waitForVBlankDone, etw::softwareRendererKeyword)
#define JUCE_TRACE_LOG_JUCE_VBLANK_CALL_LISTENERS \
JUCE_WRITE_TRACE_LOG (etw::callVBlankListeners, etw::softwareRendererKeyword)
#define JUCE_TRACE_LOG_D2D_RESIZE(message) \
JUCE_WRITE_TRACE_LOG_VA (etw::resize, etw::paintKeyword | etw::direct2dKeyword, TraceLoggingValue (message, "message"))
#define JUCE_TRACE_LOG_D2D_IMAGE_MAP_DATA \
JUCE_WRITE_TRACE_LOG (etw::mapBitmap, etw::direct2dKeyword)
#define JUCE_TRACE_LOG_D2D_IMAGE_UNMAP_DATA \
JUCE_WRITE_TRACE_LOG (etw::unmapBitmap, etw::direct2dKeyword)
#define JUCE_TRACE_LOG_PAINT_COMPONENT_AND_CHILDREN(depth) \
JUCE_WRITE_TRACE_LOG_VA (etw::paintComponentAndChildren, etw::paintKeyword, TraceLoggingValue (depth, "depth"))
#define JUCE_TRACE_LOG_PAINT_CALL(code, frameNumber) \
JUCE_WRITE_TRACE_LOG_VA (code, etw::softwareRendererKeyword, TraceLoggingValue ((UINT64) frameNumber, "frame"))
#if JUCE_ETW_TRACELOGGING
#define JUCE_TRACE_EVENT_INT_RECT_LIST(code, keyword, frameNumber, rect) \
{ \
const std::vector<INT32> vec = ::juce::etw::toVector (rect); \
JUCE_WRITE_TRACE_LOG_VA (code, \
etw::softwareRendererKeyword, \
TraceLoggingValue ((UINT64) frameNumber, "frame"), \
TraceLoggingInt32Array (vec.data(), (UINT16) vec.size(), "rect")); \
}
#define JUCE_TRACE_EVENT_INT_RECT(code, keyword, rect) \
{ \
const std::vector<INT32> vec = ::juce::etw::toVector (rect); \
JUCE_WRITE_TRACE_LOG_VA (code, \
etw::softwareRendererKeyword, \
TraceLoggingInt32Array (vec.data(), (UINT16) vec.size(), "rect")); \
}
#else
#define JUCE_TRACE_EVENT_INT_RECT_LIST(code, keyword, frameNumber, rect)
#define JUCE_TRACE_EVENT_INT_RECT(code, keyword, rect)
#endif
} // namespace juce::etw
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,767 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if JUCE_USE_FONTCONFIG
using FcConfigPtr = std::unique_ptr<FcConfig, FunctionPointerDestructor<FcConfigDestroy>>;
using FcPatternPtr = std::unique_ptr<FcPattern, FunctionPointerDestructor<FcPatternDestroy>>;
using FcCharSetPtr = std::unique_ptr<FcCharSet, FunctionPointerDestructor<FcCharSetDestroy>>;
using FcLangSetPtr = std::unique_ptr<FcLangSet, FunctionPointerDestructor<FcLangSetDestroy>>;
#endif
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wredundant-decls")
extern "C"
{
// Available since FT 2.13.1, so not available on Ubuntu 20.04 for example
[[gnu::weak]] FT_Error FT_Get_Default_Named_Instance (FT_Face, FT_UInt*);
// Unavailable on Ubuntu 18.04
[[gnu::weak]] FT_Error FT_Done_MM_Var (FT_Library, FT_MM_Var*);
[[gnu::weak]] FT_Error FT_Set_Named_Instance (FT_Face, FT_UInt);
} // extern "C"
struct FTLibWrapper final : public ReferenceCountedObject
{
FTLibWrapper()
{
if (FT_Init_FreeType (&library) != 0)
{
library = {};
DBG ("Failed to initialize FreeType");
}
}
~FTLibWrapper()
{
if (library != nullptr)
FT_Done_FreeType (library);
}
#if JUCE_USE_FONTCONFIG
const FcConfigPtr fcConfig { FcInitLoadConfigAndFonts() };
#endif
FT_Library library = {};
using Ptr = ReferenceCountedObjectPtr<FTLibWrapper>;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FTLibWrapper)
};
//==============================================================================
struct FTFaceWrapper final : public ReferenceCountedObject
{
using Ptr = ReferenceCountedObjectPtr<FTFaceWrapper>;
static FTFaceWrapper::Ptr selectUnicodeCharmap (FTFaceWrapper::Ptr face)
{
if (face != nullptr)
if (FT_Select_Charmap (face->face, ft_encoding_unicode) != 0)
FT_Set_Charmap (face->face, face->face->charmaps[0]);
return face;
}
static FTFaceWrapper::Ptr from (const FTLibWrapper::Ptr& ftLib, const File& file, int faceIndex)
{
FT_Face result{};
if (FT_New_Face (ftLib->library, file.getFullPathName().toUTF8(), faceIndex, &result) != 0)
return {};
return selectUnicodeCharmap (new FTFaceWrapper (ftLib, result));
}
static FTFaceWrapper::Ptr from (const FTLibWrapper::Ptr& ftLib, const void* data, size_t dataSize, int faceIndex)
{
MemoryBlock storage (data, dataSize);
FT_Face result{};
if (FT_New_Memory_Face (ftLib->library,
static_cast<const FT_Byte*> (storage.getData()),
(FT_Long) storage.getSize(),
faceIndex,
&result) != 0)
return {};
return selectUnicodeCharmap (new FTFaceWrapper (ftLib, result, std::move (storage)));
}
template <typename Callback>
bool forEachStyleDefaultFirst (Callback&& callback) const
{
const auto numInstances = std::invoke ([&]() -> FT_UInt
{
if (FT_Done_MM_Var == nullptr)
return 0;
if (FT_MM_Var* ftMmVar{}; FT_Get_MM_Var (face, &ftMmVar) == 0)
{
const ScopeGuard scope { [&] { FT_Done_MM_Var (library->library, ftMmVar); } };
return ftMmVar->num_namedstyles;
}
return 0;
});
if (numInstances == 0)
return false;
const auto defaultInstance = std::invoke ([&]() -> FT_UInt
{
if (FT_Get_Default_Named_Instance == nullptr)
return 0;
if (FT_UInt result{}; FT_Get_Default_Named_Instance (face, &result) == 0)
return result;
return 0;
});
callback (defaultInstance);
for (FT_UInt i = 0; i < numInstances; ++i)
if (i + 1 != defaultInstance)
callback (i + 1);
return true;
}
FTFaceWrapper (const FTLibWrapper::Ptr& ftLib, FT_Face faceIn, MemoryBlock mb = {})
: library (ftLib), savedFaceData (std::move (mb)), face (faceIn) {}
~FTFaceWrapper()
{
if (face != nullptr)
FT_Done_Face (face);
}
FTLibWrapper::Ptr library;
MemoryBlock savedFaceData;
FT_Face face = {};
JUCE_LEAK_DETECTOR (FTFaceWrapper)
};
//==============================================================================
class FTTypefaceList final : private DeletedAtShutdown
{
public:
FTTypefaceList()
{
scanFontPaths (getDefaultFontDirectories());
}
~FTTypefaceList() override
{
clearSingletonInstance();
}
//==============================================================================
struct KnownTypeface
{
explicit KnownTypeface (const FTFaceWrapper& face)
: family (face.face->family_name),
style (face.face->style_name),
faceIndex ((int) face.face->face_index),
flags (((face.face->style_flags & FT_STYLE_FLAG_BOLD) ? bold : 0)
| ((face.face->style_flags & FT_STYLE_FLAG_ITALIC) ? italic : 0)
| ((face.face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) ? monospaced : 0)
| (isFaceSansSerif (family) ? sansSerif : 0))
{
}
virtual ~KnownTypeface() = default;
virtual FTFaceWrapper::Ptr create (FTLibWrapper::Ptr) const = 0;
virtual bool holdsFace (FTFaceWrapper::Ptr) const { return false; }
enum Flag
{
bold = 1 << 0,
italic = 1 << 1,
monospaced = 1 << 2,
sansSerif = 1 << 3,
};
const String family, style;
const int faceIndex;
const int flags;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownTypeface)
};
struct FileTypeface : public KnownTypeface
{
FileTypeface (const FTFaceWrapper& face, const File& fileIn)
: KnownTypeface (face), file (fileIn) {}
FTFaceWrapper::Ptr create (FTLibWrapper::Ptr lib) const override
{
return FTFaceWrapper::from (lib, file, faceIndex);
}
const File file;
};
struct CachedTypeface : public KnownTypeface
{
explicit CachedTypeface (FTFaceWrapper::Ptr ptr)
: KnownTypeface (*ptr), face (ptr) {}
FTFaceWrapper::Ptr create (FTLibWrapper::Ptr) const override
{
return face;
}
bool holdsFace (FTFaceWrapper::Ptr p) const override
{
return face == p;
}
FTFaceWrapper::Ptr face;
};
using Cache = std::vector<std::unique_ptr<KnownTypeface>>;
//==============================================================================
FTFaceWrapper::Ptr createFace (const void* data, size_t dataSize, int index)
{
return FTFaceWrapper::from (library, data, dataSize, index);
}
FTFaceWrapper::Ptr createFace (const File& file, int index)
{
return FTFaceWrapper::from (library, file, index);
}
FTFaceWrapper::Ptr createFace (const String& fontName, const String& fontStyle)
{
auto ftFace = matchTypeface (fontName, fontStyle);
if (ftFace == nullptr) ftFace = matchTypeface (fontName, "Regular");
if (ftFace == nullptr) ftFace = matchTypeface (fontName, {});
if (ftFace != nullptr)
return ftFace->create (library);
return nullptr;
}
//==============================================================================
StringArray findAllFamilyNames() const
{
std::set<String> set;
for (const auto& face : faces)
set.insert (face->family);
StringArray s;
for (const auto& family : set)
s.add (family);
return s;
}
StringArray findAllTypefaceStyles (const String& family) const
{
StringArray s;
for (const auto& face : faces)
if (face->family == family)
s.addIfNotAlreadyThere (face->style);
// scanFontPaths ensures that regular styles are ordered before other styles
return s;
}
void scanFontPaths (const StringArray& paths)
{
for (auto& path : paths)
{
for (const auto& iter : RangedDirectoryIterator (File::getCurrentWorkingDirectory().getChildFile (path), true))
{
if (iter.getFile().hasFileExtension ("ttf;otf"))
scanFont (iter.getFile());
}
}
}
void getMonospacedNames (StringArray& monoSpaced) const
{
for (const auto& face : faces)
if (face->flags & KnownTypeface::monospaced)
monoSpaced.addIfNotAlreadyThere (face->family);
}
void getSerifNames (StringArray& serif) const
{
for (const auto& face : faces)
if ((face->flags & (KnownTypeface::sansSerif | KnownTypeface::monospaced)) == 0)
serif.addIfNotAlreadyThere (face->family);
}
void getSansSerifNames (StringArray& sansSerif) const
{
for (const auto& face : faces)
if (face->flags & KnownTypeface::sansSerif)
sansSerif.addIfNotAlreadyThere (face->family);
}
void addMemoryFaces (Span<const FTFaceWrapper::Ptr> ptr)
{
if (ptr.empty())
return;
auto cached = std::make_unique<CachedTypeface> (ptr.front());
auto insertionPoint = findInsertionPoint (*cached);
for (const auto& p : ptr)
insertionPoint = std::next (faces.insert (insertionPoint, std::make_unique<CachedTypeface> (p)));
}
void removeMemoryFaces (Span<const FTFaceWrapper::Ptr> ptr)
{
for (const auto& p : ptr)
{
faces.erase (std::remove_if (faces.begin(), faces.end(), [&] (const std::unique_ptr<KnownTypeface>& tf)
{
return tf->holdsFace (p);
}), faces.end());
}
}
JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL_INLINE (FTTypefaceList)
FTLibWrapper::Ptr getLibrary() const { return library; }
private:
void resort()
{
std::sort (faces.begin(), faces.end(), [] (const auto& a, const auto& b)
{
const auto tie = [] (const KnownTypeface& t)
{
return std::make_tuple (t.family,
t.flags,
t.style,
t.faceIndex);
};
return tie (*a) < tie (*b);
});
}
FTLibWrapper::Ptr library = new FTLibWrapper;
Cache faces;
static StringArray getDefaultFontDirectories();
void scanFont (const File& file)
{
for (auto faceIndex = 0;; ++faceIndex)
{
if (auto face = FTFaceWrapper::from (library, file, faceIndex); face != nullptr && face->face != nullptr)
{
auto insertionPoint = findInsertionPoint (FileTypeface (*face, file));
const auto handledNamedStyles = FT_Set_Named_Instance != nullptr && face->forEachStyleDefaultFirst ([&] (auto index)
{
const auto err = FT_Set_Named_Instance (face->face, index);
jassertquiet (err == 0);
insertionPoint = std::next (faces.insert (insertionPoint, std::make_unique<FileTypeface> (*face, file)));
});
if (! handledNamedStyles)
{
insertionPoint = std::next (faces.insert (insertionPoint, std::make_unique<FileTypeface> (*face, file)));
}
}
else
{
break;
}
}
}
std::vector<std::unique_ptr<KnownTypeface>>::const_iterator findInsertionPoint (const KnownTypeface& tf)
{
struct Comparator
{
static auto tie (const KnownTypeface& t)
{
return std::make_tuple (t.family, t.flags, t.style, t.faceIndex);
}
bool operator() (const KnownTypeface& a, const std::unique_ptr<KnownTypeface>& b)
{
return tie (a) < tie (*b);
}
bool operator() (const std::unique_ptr<KnownTypeface>& a, const KnownTypeface& b)
{
return tie (*a) < tie (b);
}
bool operator() (const std::unique_ptr<KnownTypeface>& a, const std::unique_ptr<KnownTypeface>& b)
{
return tie (*a) < tie (*b);
}
bool operator() (const KnownTypeface& a, const KnownTypeface& b)
{
return tie (a) < tie (b);
}
};
return std::upper_bound (faces.begin(), faces.end(), tf, Comparator{});
}
const KnownTypeface* matchTypeface (const String& familyName, const String& style) const noexcept
{
for (const auto& face : faces)
if (face->family == familyName && (face->style.equalsIgnoreCase (style) || style.isEmpty()))
return face.get();
return nullptr;
}
static bool isFaceSansSerif (const String& family)
{
static const char* sansNames[] = { "Sans", "Verdana", "Arial", "Ubuntu" };
for (auto* name : sansNames)
if (family.containsIgnoreCase (name))
return true;
return false;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FTTypefaceList)
};
//==============================================================================
class FreeTypeTypeface final : public Typeface
{
using Ptr = ReferenceCountedObjectPtr<FreeTypeTypeface>;
public:
Typeface::Ptr cloneWithVariableSettings (Span<const FontVariableSetting> settings) const override
{
auto newFreeTypeFace = cloneFace();
if (newFreeTypeFace == nullptr)
return {};
// FreeType uses a 16.16 fixed-point format (FT_Fixed) to represent fractional values.
// Multiplying or dividing by 65536 allows us to convert to and from float.
static constexpr float ftFixedMultiplier = 65536.0f;
static auto floatToFTFixed = [] (float v)
{
return (FT_Fixed) (v * ftFixedMultiplier);
};
const auto& registry = getNativeDetails()->getVariableRegistry();
auto sanitisedVariables = registry->sanitiseVariables (settings);
const auto numAxes = std::invoke ([&]() -> FT_UInt
{
if (FT_Done_MM_Var == nullptr)
return 0;
if (FT_MM_Var* ftMmVar{}; FT_Get_MM_Var (newFreeTypeFace->face, &ftMmVar) == 0)
{
const ScopeGuard scope { [&] { FT_Done_MM_Var (newFreeTypeFace->library->library, ftMmVar); } };
return ftMmVar->num_axis;
}
jassertfalse;
return 0;
});
std::vector<FT_Fixed> coords (numAxes);
FT_Get_Var_Design_Coordinates (newFreeTypeFace->face,
(FT_UInt) coords.size(),
coords.data());
// We have to apply the variables in their original order.
// Thankfully we have that information in the registry.
for (const auto& var : settings)
{
if (auto index = registry->getOriginalIndexForTag (var.tag))
coords[*index] = floatToFTFixed (var.value);
}
FT_Set_Var_Design_Coordinates (newFreeTypeFace->face,
(FT_UInt) coords.size(),
coords.data());
HbFace hbFace { hb_ft_face_create_referenced (newFreeTypeFace->face), IncrementRef::no };
HbFont hb { hb_font_create (hbFace.get()), IncrementRef::no };
return new FreeTypeTypeface (std::move (newFreeTypeFace),
std::move (hb),
registry,
std::move (sanitisedVariables));
}
static Ptr from (const Font& font)
{
const auto name = font.getTypefaceName();
const auto style = font.getTypefaceStyle();
auto face = FTTypefaceList::getInstance()->createFace (name, style);
if (face == nullptr)
return {};
HbFace hbFace { hb_ft_face_create_referenced (face->face), IncrementRef::no };
HbFont hb { hb_font_create (hbFace.get()), IncrementRef::no };
if (hb == nullptr)
return {};
FontStyleHelpers::initSynthetics (hb.get(), font);
return new FreeTypeTypeface (face, std::move (hb));
}
static Ptr from (Span<const std::byte> data, int index = 0)
{
auto face = FTTypefaceList::getInstance()->createFace (data.data(), data.size(), index);
if (face == nullptr)
return {};
HbFace hbFace { hb_ft_face_create_referenced (face->face), IncrementRef::no };
HbFont hb { hb_font_create (hbFace.get()), IncrementRef::no };
if (hb == nullptr)
return {};
return new FreeTypeTypeface (face, std::move (hb));
}
Typeface::Ptr createSystemFallback ([[maybe_unused]] const String& text,
[[maybe_unused]] const String& language) const override
{
#if JUCE_USE_FONTCONFIG
auto* cache = TypefaceFileCache::getInstance();
if (cache == nullptr)
return {};
const auto makeBasicPattern = [&]
{
FcPatternPtr pattern { FcPatternCreate() };
{
FcValue value{};
value.type = FcTypeString;
value.u.s = unalignedPointerCast<const FcChar8*> (ftFace->face->style_name);
FcPatternAdd (pattern.get(), FC_STYLE, value, FcFalse);
}
{
const FcCharSetPtr charset { FcCharSetCreate() };
for (const auto& character : text)
FcCharSetAddChar (charset.get(), (FcChar32) character);
FcPatternAddCharSet (pattern.get(), FC_CHARSET, charset.get());
}
if (language.isNotEmpty())
{
const FcLangSetPtr langset { FcLangSetCreate() };
FcLangSetAdd (langset.get(), unalignedPointerCast<const FcChar8*> (language.toRawUTF8()));
FcPatternAddLangSet (pattern.get(), FC_LANG, langset.get());
}
return pattern;
};
const auto fallbackWithFamily = std::invoke ([&]
{
auto pattern = makeBasicPattern();
FcValue value{};
value.type = FcTypeString;
value.u.s = unalignedPointerCast<const FcChar8*> (ftFace->face->family_name);
FcPatternAddWeak (pattern.get(), FC_FAMILY, value, FcFalse);
return fromPattern (pattern.get());
});
if (text.isEmpty() || fallbackWithFamily->getNominalGlyphForCodepoint (*text.getCharPointer()).has_value())
return fallbackWithFamily;
const auto fallbackWithoutFamily = fromPattern (makeBasicPattern().get());
jassert (fallbackWithoutFamily->getNominalGlyphForCodepoint (*text.getCharPointer()).has_value());
return fallbackWithoutFamily;
#else
// Font substitution will not work unless fontconfig is enabled.
jassertfalse;
return nullptr;
#endif
}
const Native* getNativeDetails() const override
{
return native.get();
}
static Typeface::Ptr findSystemTypeface()
{
#if JUCE_USE_FONTCONFIG
FcPatternPtr pattern { FcNameParse (unalignedPointerCast<const FcChar8*> ("system-ui")) };
return fromPattern (pattern.get());
#else
return nullptr;
#endif
}
private:
FTFaceWrapper::Ptr cloneFace() const
{
auto blob = getNativeDetails()->getBlob();
unsigned int blobSize = 0;
const auto* data = hb_blob_get_data (blob.get(), &blobSize);
return FTFaceWrapper::from (FTTypefaceList::getInstance()->getLibrary(),
data,
blobSize,
0);
}
#if JUCE_USE_FONTCONFIG
static Typeface::Ptr fromPattern (FcPattern* pattern)
{
auto* cache = TypefaceFileCache::getInstance();
if (cache == nullptr)
return {};
const auto library = FTTypefaceList::getInstance()->getLibrary();
FcConfigSubstitute (library->fcConfig.get(), pattern, FcMatchPattern);
FcDefaultSubstitute (pattern);
FcResult result{};
const FcPatternPtr matched { FcFontMatch (library->fcConfig.get(), pattern, &result) };
if (result != FcResultMatch)
return {};
FcChar8* fileString{};
if (FcPatternGetString (matched.get(), FC_FILE, 0, &fileString) != FcResultMatch)
return {};
int index{};
if (FcPatternGetInteger (matched.get(), FC_INDEX, 0, &index) != FcResultMatch)
return {};
const File file { String { CharPointer_UTF8 { unalignedPointerCast<const char*> (fileString) } } };
return cache->get ({ file, index }, [] (const TypefaceFileAndIndex& f) -> Ptr
{
auto face = FTTypefaceList::getInstance()->createFace (f.file, f.index);
if (face == nullptr)
return {};
HbFace hbFace { hb_ft_face_create_referenced (face->face), IncrementRef::no };
HbFont cachedFont { hb_font_create (hbFace.get()), IncrementRef::no };
if (cachedFont == nullptr)
return {};
return new FreeTypeTypeface (face, std::move (cachedFont));
});
}
#endif
static TypefaceVerticalMetrics getNativeMetrics (FTFaceWrapper::Ptr ftFace)
{
const auto upem = (float) ftFace->face->units_per_EM;
const auto ascent = (float) std::abs (ftFace->face->ascender) / upem;
const auto descent = (float) std::abs (ftFace->face->descender) / upem;
const auto lineGap = (float) std::abs (ftFace->face->height) / upem - (ascent + descent);
return { ascent, descent, lineGap };
}
FreeTypeTypeface (FTFaceWrapper::Ptr ftFaceIn,
HbFont hbIn,
std::shared_ptr<VariableAxisRegistry> variableAxisRegistry = {},
std::vector<FontVariableSetting> settings = {})
: FreeTypeTypeface (ftFaceIn,
std::make_unique<Native> (TypefaceNativeOptions { std::move (hbIn),
getNativeMetrics (ftFaceIn),
std::move (settings),
{},
{},
variableAxisRegistry }))
{
}
FreeTypeTypeface (FTFaceWrapper::Ptr ftFaceIn, std::unique_ptr<Native> nativeIn)
: Typeface (nativeIn->getTypefaceName(), nativeIn->getTypefaceStyle()),
ftFace (ftFaceIn),
native (std::move (nativeIn))
{
}
FTFaceWrapper::Ptr ftFace;
std::unique_ptr<Native> native;
JUCE_DECLARE_NON_COPYABLE (FreeTypeTypeface)
};
auto Typeface::createFromFontImpl (const Font& font) -> Ptr
{
return FreeTypeTypeface::from (font);
}
auto Typeface::createFromDataImpl (Span<const std::byte> data) -> Ptr
{
return FreeTypeTypeface::from (data);
}
auto Typeface::findSystemTypeface() -> Ptr
{
return FreeTypeTypeface::findSystemTypeface();
}
} // namespace juce
@@ -0,0 +1,216 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
static std::unique_ptr<XmlElement> findFontsConfFile()
{
static const char* pathsToSearch[] = { "/etc/fonts/fonts.conf",
"/usr/share/fonts/fonts.conf",
"/usr/local/etc/fonts/fonts.conf",
"/usr/share/defaults/fonts/fonts.conf" };
for (auto* path : pathsToSearch)
if (auto xml = parseXML (File (path)))
return xml;
return {};
}
StringArray FTTypefaceList::getDefaultFontDirectories()
{
StringArray fontDirs;
fontDirs.addTokens (String (CharPointer_UTF8 (getenv ("JUCE_FONT_PATH"))), ";,", "");
fontDirs.removeEmptyStrings (true);
if (fontDirs.isEmpty())
{
if (auto fontsInfo = findFontsConfFile())
{
for (auto* e : fontsInfo->getChildWithTagNameIterator ("dir"))
{
auto fontPath = e->getAllSubText().trim();
if (fontPath.isNotEmpty())
{
if (e->getStringAttribute ("prefix") == "xdg")
{
auto xdgDataHome = SystemStats::getEnvironmentVariable ("XDG_DATA_HOME", {});
if (xdgDataHome.trimStart().isEmpty())
xdgDataHome = "~/.local/share";
fontPath = File (xdgDataHome).getChildFile (fontPath).getFullPathName();
}
fontDirs.add (fontPath);
}
}
}
}
if (fontDirs.isEmpty())
fontDirs.add ("/usr/X11R6/lib/X11/fonts");
fontDirs.removeDuplicates (false);
return fontDirs;
}
void Typeface::scanFolderForFonts (const File& folder)
{
FTTypefaceList::getInstance()->scanFontPaths (StringArray (folder.getFullPathName()));
}
StringArray Font::findAllTypefaceNamesImpl()
{
return FTTypefaceList::getInstance()->findAllFamilyNames();
}
StringArray Font::findAllTypefaceStylesImpl (const String& family)
{
return FTTypefaceList::getInstance()->findAllTypefaceStyles (family);
}
//==============================================================================
struct DefaultFontInfo
{
DefaultFontInfo()
: defaultSans (getDefaultSansSerifFontName()),
defaultSerif (getDefaultSerifFontName()),
defaultFixed (getDefaultMonospacedFontName())
{
}
String getRealFontName (const String& faceName) const
{
if (faceName == Font::getDefaultSansSerifFontName()) return defaultSans;
if (faceName == Font::getDefaultSerifFontName()) return defaultSerif;
if (faceName == Font::getDefaultMonospacedFontName()) return defaultFixed;
return faceName;
}
String defaultSans, defaultSerif, defaultFixed;
private:
template <typename Range>
static String pickBestFont (const StringArray& names, Range&& choicesArray)
{
for (auto& choice : choicesArray)
if (names.contains (choice, true))
return choice;
for (auto& choice : choicesArray)
for (auto& name : names)
if (name.startsWithIgnoreCase (choice))
return name;
for (auto& choice : choicesArray)
for (auto& name : names)
if (name.containsIgnoreCase (choice))
return name;
for (auto& name : names)
if (name.isNotEmpty())
return name;
jassertfalse;
return {};
}
static String getDefaultSansSerifFontName()
{
StringArray allFonts;
FTTypefaceList::getInstance()->getSansSerifNames (allFonts);
static constexpr const char* targets[] { "Verdana",
"Bitstream Vera Sans",
"Luxi Sans",
"Liberation Sans",
"DejaVu Sans",
"Sans" };
return pickBestFont (allFonts, targets);
}
static String getDefaultSerifFontName()
{
StringArray allFonts;
FTTypefaceList::getInstance()->getSerifNames (allFonts);
static constexpr const char* targets[] { "Bitstream Vera Serif",
"Times",
"Nimbus Roman",
"Liberation Serif",
"DejaVu Serif",
"Serif" };
return pickBestFont (allFonts, targets);
}
static String getDefaultMonospacedFontName()
{
StringArray allFonts;
FTTypefaceList::getInstance()->getMonospacedNames (allFonts);
static constexpr const char* targets[] { "DejaVu Sans Mono",
"Bitstream Vera Sans Mono",
"Sans Mono",
"Liberation Mono",
"Courier",
"DejaVu Mono",
"Mono" };
return pickBestFont (allFonts, targets);
}
JUCE_DECLARE_NON_COPYABLE (DefaultFontInfo)
};
Typeface::Ptr Font::Native::getDefaultPlatformTypefaceForFont (const Font& font)
{
static const DefaultFontInfo defaultInfo;
Font f (font);
const auto name = font.getTypefaceName();
const auto realName = defaultInfo.getRealFontName (name);
if (realName.isEmpty())
return nullptr;
f.setTypefaceName (realName);
return Typeface::createSystemTypefaceFor (f);
}
} // namespace juce
@@ -0,0 +1,426 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
// This symbol is available on all the platforms we support, but not declared in the CoreText headers on older platforms.
extern "C" CTFontRef CTFontCreateForStringWithLanguage (CTFontRef currentFont,
CFStringRef string,
CFRange range,
CFStringRef language);
class CoreTextTypeface final : public Typeface
{
static CFUniquePtr<CTFontRef> addOwner (CTFontRef reference)
{
CFRetain (reference);
return CFUniquePtr<CTFontRef> { reference };
}
public:
static Typeface::Ptr from (const Font& font)
{
auto ctFont = std::invoke ([&]() -> CFUniquePtr<CTFontRef>
{
CFUniquePtr<CFStringRef> cfFontFamily (FontStyleHelpers::getConcreteFamilyName (font).toCFString());
if (cfFontFamily == nullptr)
return {};
CFUniquePtr<CFStringRef> cfFontStyle (findBestAvailableStyle (font).toCFString());
if (cfFontStyle == nullptr)
return {};
CFStringRef keys[] { kCTFontFamilyNameAttribute, kCTFontStyleNameAttribute };
CFTypeRef values[] { cfFontFamily.get(), cfFontStyle.get() };
CFUniquePtr<CFDictionaryRef> fontDescAttributes (CFDictionaryCreate (nullptr,
(const void**) &keys,
(const void**) &values,
numElementsInArray (keys),
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
if (fontDescAttributes == nullptr)
return {};
CFUniquePtr<CTFontDescriptorRef> ctFontDescRef (CTFontDescriptorCreateWithAttributes (fontDescAttributes.get()));
if (ctFontDescRef == nullptr)
return {};
return CFUniquePtr<CTFontRef> { CTFontCreateWithFontDescriptor (ctFontDescRef.get(), 1, nullptr) };
});
if (ctFont == nullptr)
return {};
HbFont result { hb_coretext_font_create (ctFont.get()), IncrementRef::no };
if (result == nullptr)
return {};
FontStyleHelpers::initSynthetics (result.get(), font);
return new CoreTextTypeface (std::move (ctFont),
std::move (result));
}
static CFUniquePtr<CFDictionaryRef> createVariableDictionary (Span<const FontVariableSetting> variables)
{
Array<CFStringRef> keys;
Array<CFNumberRef> values;
for (auto v : variables)
{
keys.add (v.tag.toString().toCFString());
const auto valueAsCGFloat = (CGFloat) v.value;
values.add (CFNumberCreate (kCFAllocatorDefault, kCFNumberCGFloatType, &valueAsCGFloat));
}
const ScopeGuard stringReleaser { [&] { for (auto key : keys) CFRelease (key); } };
return CFUniquePtr<CFDictionaryRef> { CFDictionaryCreate (kCFAllocatorDefault,
(const void**) keys.data(),
(const void**) values.data(),
(CFIndex) variables.size(),
&kCFTypeDictionaryKeyCallBacks,
nullptr) };
}
Typeface::Ptr cloneWithVariableSettings (Span<const FontVariableSetting> variables) const override
{
const auto registry = getNativeDetails()->getVariableRegistry();
auto sanitisedVariables = registry->sanitiseVariables (variables);
auto variableDict = createVariableDictionary (sanitisedVariables);
if (variableDict == nullptr)
{
jassertfalse;
return {};
}
CFUniquePtr<CGFontRef> baseCGFont { CTFontCopyGraphicsFont (ctFont.get(), nullptr) };
if (baseCGFont == nullptr)
return {};
CFUniquePtr<CGFontRef> newCGFont { CGFontCreateCopyWithVariations (baseCGFont.get(),
variableDict.get()) };
if (newCGFont == nullptr)
return {};
CFUniquePtr<CTFontRef> newFont { CTFontCreateWithGraphicsFont (newCGFont.get(), 1.0f, {}, {}) };
if (newFont == nullptr)
return {};
HbFont result { hb_coretext_font_create (newFont.get()), IncrementRef::no };
if (result == nullptr)
return {};
return new CoreTextTypeface (std::move (newFont),
std::move (result),
storage,
registry,
std::move (sanitisedVariables));
}
static Typeface::Ptr from (Span<const std::byte> data)
{
// We can't use CFDataCreate here as this triggers a false positive in ASAN
// so copy the data manually and use CFDataCreateWithBytesNoCopy
auto copy = std::make_shared<MemoryBlock> (data.data(), data.size());
const CFUniquePtr<CFDataRef> cfData { CFDataCreateWithBytesNoCopy (kCFAllocatorDefault,
static_cast<const UInt8*> (copy->getData()),
(CFIndex) copy->getSize(),
kCFAllocatorNull) };
if (cfData == nullptr)
return {};
#if JUCE_IOS
// Workaround for a an obscure iOS bug which can cause the app to dead-lock
// when loading custom type faces. See: http://www.openradar.me/18778790 and
// http://stackoverflow.com/questions/40242370/app-hangs-in-simulator
[UIFont systemFontOfSize: 12];
#endif
const CFUniquePtr<CGDataProviderRef> provider { CGDataProviderCreateWithCFData (cfData.get()) };
if (provider == nullptr)
return {};
const CFUniquePtr<CGFontRef> font { CGFontCreateWithDataProvider (provider.get()) };
if (font == nullptr)
return {};
CFUniquePtr<CTFontRef> ctFont { CTFontCreateWithGraphicsFont (font.get(), 1.0f, {}, {}) };
if (ctFont == nullptr)
return {};
HbFont result { hb_coretext_font_create (ctFont.get()), IncrementRef::no };
if (result == nullptr)
return {};
return new CoreTextTypeface (std::move (ctFont),
std::move (result),
std::move (copy));
}
Typeface::Ptr createSystemFallback (const String& c, const String& language) const override
{
const CFUniquePtr<CFStringRef> cfText { c.toCFString() };
const CFUniquePtr<CFStringRef> cfLanguage { language.toCFString() };
auto* old = ctFont.get();
const CFUniquePtr<CFStringRef> oldName { CTFontCopyFamilyName (old) };
const CFUniquePtr<CTFontDescriptorRef> oldDescriptor { CTFontCopyFontDescriptor (old) };
const CFUniquePtr<CFStringRef> oldStyle { (CFStringRef) CTFontDescriptorCopyAttribute (oldDescriptor.get(),
kCTFontStyleNameAttribute) };
CFUniquePtr<CTFontRef> newFont { CTFontCreateForStringWithLanguage (old,
cfText.get(),
CFRangeMake (0, CFStringGetLength (cfText.get())),
cfLanguage.get()) };
const CFUniquePtr<CFStringRef> newName { CTFontCopyFamilyName (newFont.get()) };
const CFUniquePtr<CTFontDescriptorRef> descriptor { CTFontCopyFontDescriptor (newFont.get()) };
const CFUniquePtr<CFStringRef> newStyle { (CFStringRef) CTFontDescriptorCopyAttribute (descriptor.get(),
kCTFontStyleNameAttribute) };
HbFont result { hb_coretext_font_create (newFont.get()), IncrementRef::no };
if (result == nullptr)
return {};
return new CoreTextTypeface (std::move (newFont),
std::move (result));
}
const Native* getNativeDetails() const override
{
return native.get();
}
static Typeface::Ptr findSystemTypeface()
{
CFUniquePtr<CTFontRef> defaultCtFont (CTFontCreateUIFontForLanguage (kCTFontUIFontSystem, 0.0, nullptr));
const CFUniquePtr<CFStringRef> newName { CTFontCopyFamilyName (defaultCtFont.get()) };
const CFUniquePtr<CTFontDescriptorRef> descriptor { CTFontCopyFontDescriptor (defaultCtFont.get()) };
const CFUniquePtr<CFStringRef> newStyle { (CFStringRef) CTFontDescriptorCopyAttribute (descriptor.get(),
kCTFontStyleNameAttribute) };
HbFont result { hb_coretext_font_create (defaultCtFont.get()), IncrementRef::no };
if (result == nullptr)
return {};
return new CoreTextTypeface (std::move (defaultCtFont),
std::move (result));
}
private:
static TypefaceVerticalMetrics getNativeMetrics (CTFontRef ctFont)
{
const CFUniquePtr<CGFontRef> cgFont { CTFontCopyGraphicsFont (ctFont, nullptr) };
const auto upem = (float) CGFontGetUnitsPerEm (cgFont.get());
const auto ascent = std::abs ((float) CGFontGetAscent (cgFont.get()) / upem);
const auto descent = std::abs ((float) CGFontGetDescent (cgFont.get()) / upem);
const auto leading = std::abs ((float) CGFontGetLeading (cgFont.get()) / upem);
return { ascent, descent, leading };
}
CoreTextTypeface (CFUniquePtr<CTFontRef> nativeFont,
HbFont fontIn,
std::shared_ptr<MemoryBlock> data = {},
std::shared_ptr<VariableAxisRegistry> variableAxisRegistry = {},
std::vector<FontVariableSetting> variables = {})
: CoreTextTypeface (addOwner (nativeFont.get()),
std::make_unique<Native> (TypefaceNativeOptions { fontIn,
getNativeMetrics (nativeFont.get()),
std::move (variables),
{},
{},
variableAxisRegistry }),
std::move (data))
{
}
CoreTextTypeface (CFUniquePtr<CTFontRef> nativeFont,
std::unique_ptr<Native> nativeIn,
std::shared_ptr<MemoryBlock> data)
: Typeface (nativeIn->getTypefaceName(), nativeIn->getTypefaceStyle()),
ctFont (std::move (nativeFont)),
storage (std::move (data)),
native (std::move (nativeIn))
{
}
static String findBestAvailableStyle (const Font& font)
{
const auto availableStyles = Font::findAllTypefaceStyles (font.getTypefaceName());
const auto style = font.getTypefaceStyle();
if (availableStyles.contains (style))
return style;
return availableStyles[0];
}
// We store this, rather than calling hb_coretext_font_get_ct_font, because harfbuzz may
// override the font cascade list in the returned font.
CFUniquePtr<CTFontRef> ctFont;
std::shared_ptr<MemoryBlock> storage;
std::unique_ptr<Native> native;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreTextTypeface)
};
//==============================================================================
Typeface::Ptr Typeface::createFromFontImpl (const Font& font)
{
return CoreTextTypeface::from (font);
}
Typeface::Ptr Typeface::createFromDataImpl (Span<const std::byte> data)
{
return CoreTextTypeface::from (data);
}
void Typeface::scanFolderForFonts (const File& folder)
{
for (auto& file : folder.findChildFiles (File::findFiles, false, "*.otf;*.ttf"))
if (auto urlref = CFUniquePtr<CFURLRef> (CFURLCreateWithFileSystemPath (kCFAllocatorDefault, file.getFullPathName().toCFString(), kCFURLPOSIXPathStyle, true)))
CTFontManagerRegisterFontsForURL (urlref.get(), kCTFontManagerScopeProcess, nullptr);
}
Typeface::Ptr Typeface::findSystemTypeface()
{
return CoreTextTypeface::findSystemTypeface();
}
StringArray Font::findAllTypefaceNamesImpl()
{
StringArray names;
CFUniquePtr<CTFontCollectionRef> fontCollectionRef (CTFontCollectionCreateFromAvailableFonts (nullptr));
CFUniquePtr<CFArrayRef> fontDescriptorArray (CTFontCollectionCreateMatchingFontDescriptors (fontCollectionRef.get()));
for (CFIndex i = 0; i < CFArrayGetCount (fontDescriptorArray.get()); ++i)
{
auto ctFontDescriptorRef = (CTFontDescriptorRef) CFArrayGetValueAtIndex (fontDescriptorArray.get(), i);
CFUniquePtr<CFStringRef> cfsFontFamily ((CFStringRef) CTFontDescriptorCopyAttribute (ctFontDescriptorRef, kCTFontFamilyNameAttribute));
names.add (String::fromCFString (cfsFontFamily.get()));
}
return names;
}
StringArray Font::findAllTypefaceStylesImpl (const String& family)
{
if (FontStyleHelpers::isPlaceholderFamilyName (family))
return findAllTypefaceStyles (FontStyleHelpers::getConcreteFamilyNameFromPlaceholder (family));
StringArray results;
CFUniquePtr<CFStringRef> cfsFontFamily (family.toCFString());
CFStringRef keys[] { kCTFontFamilyNameAttribute };
CFTypeRef values[] { cfsFontFamily.get() };
CFUniquePtr<CFDictionaryRef> fontDescAttributes (CFDictionaryCreate (nullptr, (const void**) &keys, (const void**) &values, numElementsInArray (keys),
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
CFUniquePtr<CTFontDescriptorRef> ctFontDescRef (CTFontDescriptorCreateWithAttributes (fontDescAttributes.get()));
CFUniquePtr<CFArrayRef> fontFamilyArray (CFArrayCreate (kCFAllocatorDefault, (const void**) &ctFontDescRef, 1, &kCFTypeArrayCallBacks));
CFUniquePtr<CTFontCollectionRef> fontCollectionRef (CTFontCollectionCreateWithFontDescriptors (fontFamilyArray.get(), nullptr));
if (auto fontDescriptorArray = CFUniquePtr<CFArrayRef> (CTFontCollectionCreateMatchingFontDescriptors (fontCollectionRef.get())))
{
for (CFIndex i = 0; i < CFArrayGetCount (fontDescriptorArray.get()); ++i)
{
auto ctFontDescriptorRef = (CTFontDescriptorRef) CFArrayGetValueAtIndex (fontDescriptorArray.get(), i);
CFUniquePtr<CFStringRef> cfsFontStyle ((CFStringRef) CTFontDescriptorCopyAttribute (ctFontDescriptorRef, kCTFontStyleNameAttribute));
const auto name = String::fromCFString (cfsFontStyle.get());
results.add (name);
}
}
return results;
}
struct DefaultFontNames
{
#if JUCE_IOS
String defaultSans { "Helvetica" },
defaultSerif { "Times New Roman" },
defaultFixed { "Courier New" };
#else
String defaultSans { "Lucida Grande" },
defaultSerif { "Times New Roman" },
defaultFixed { "Menlo" };
#endif
};
Typeface::Ptr Font::Native::getDefaultPlatformTypefaceForFont (const Font& font)
{
static DefaultFontNames defaultNames;
auto newFont = font;
auto faceName = font.getTypefaceName();
if (faceName == getDefaultSansSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSans);
else if (faceName == getDefaultSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSerif);
else if (faceName == getDefaultMonospacedFontName()) newFont.setTypefaceName (defaultNames.defaultFixed);
if (font.getTypefaceStyle() == getDefaultStyle())
newFont.setTypefaceStyle ("Regular");
return Typeface::createSystemTypefaceFor (newFont);
}
} // namespace juce
@@ -0,0 +1,43 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
{
return SoftwareImageType().create (format, width, height, clearImage);
}
} // namespace juce
@@ -0,0 +1,39 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
Image JUCE_API getIconFromApplication (const String&, int);
Image JUCE_API getIconFromApplication (const String&, int) { return {}; }
}
@@ -0,0 +1,39 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
Image JUCE_API getIconFromApplication (const String&, int);
Image JUCE_API getIconFromApplication (const String&, int) { return {}; }
}
@@ -0,0 +1,150 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
extern Image JUCE_API getIconFromApplication (const String&, int);
static Image getIconFromIcnsFile (const File& icnsFile, const int size)
{
FileInputStream stream (icnsFile);
if (! stream.openedOk())
return {};
const int numHeaderSectionBytes = 4;
char headerSection [numHeaderSectionBytes];
if (stream.read (headerSection, numHeaderSectionBytes) != numHeaderSectionBytes
|| headerSection[0] != 'i'
|| headerSection[1] != 'c'
|| headerSection[2] != 'n'
|| headerSection[3] != 's')
return {};
if (stream.read (headerSection, numHeaderSectionBytes) != numHeaderSectionBytes)
return {};
const auto dataSize = juce::ByteOrder::bigEndianInt (headerSection);
if (dataSize <= 0)
return {};
OwnedArray<juce::ImageFileFormat> internalFormats;
internalFormats.add (new PNGImageFormat());
internalFormats.add (new JPEGImageFormat());
Array<Image> images;
auto maxWidth = 0;
auto maxWidthIndex = -1;
while (stream.getPosition() < dataSize)
{
const auto sectionStart = stream.getPosition();
if (! stream.setPosition (sectionStart + 4))
break;
if (stream.read (headerSection, numHeaderSectionBytes) != numHeaderSectionBytes)
break;
const auto sectionSize = ByteOrder::bigEndianInt (headerSection);
if (sectionSize <= 0)
break;
const auto sectionDataStart = stream.getPosition();
for (auto* fmt : internalFormats)
{
if (fmt->canUnderstand (stream))
{
stream.setPosition (sectionDataStart);
images.add (fmt->decodeImage (stream));
const auto lastImageIndex = images.size() - 1;
const auto lastWidth = images.getReference (lastImageIndex).getWidth();
if (lastWidth > maxWidth)
{
maxWidthIndex = lastImageIndex;
maxWidth = lastWidth;
}
}
stream.setPosition (sectionDataStart);
}
stream.setPosition (sectionStart + sectionSize);
}
return maxWidthIndex == -1 ? juce::Image()
: images.getReference (maxWidthIndex).rescaled (size, size, Graphics::ResamplingQuality::highResamplingQuality);
}
Image JUCE_API getIconFromApplication (const String& applicationPath, const int size)
{
if (auto pathCFString = CFUniquePtr<CFStringRef> (CFStringCreateWithCString (kCFAllocatorDefault, applicationPath.toRawUTF8(), kCFStringEncodingUTF8)))
{
if (auto url = CFUniquePtr<CFURLRef> (CFURLCreateWithFileSystemPath (kCFAllocatorDefault, pathCFString.get(), kCFURLPOSIXPathStyle, 1)))
{
if (auto appBundle = CFUniquePtr<CFBundleRef> (CFBundleCreate (kCFAllocatorDefault, url.get())))
{
if (CFTypeRef infoValue = CFBundleGetValueForInfoDictionaryKey (appBundle.get(), CFSTR ("CFBundleIconFile")))
{
if (CFGetTypeID (infoValue) == CFStringGetTypeID())
{
CFStringRef iconFilename = reinterpret_cast<CFStringRef> (infoValue);
CFStringRef resourceURLSuffix = CFStringHasSuffix (iconFilename, CFSTR (".icns")) ? nullptr : CFSTR ("icns");
if (auto iconURL = CFUniquePtr<CFURLRef> (CFBundleCopyResourceURL (appBundle.get(), iconFilename, resourceURLSuffix, nullptr)))
{
if (auto iconPath = CFUniquePtr<CFStringRef> (CFURLCopyFileSystemPath (iconURL.get(), kCFURLPOSIXPathStyle)))
{
File icnsFile (CFStringGetCStringPtr (iconPath.get(), CFStringGetSystemEncoding()));
return getIconFromIcnsFile (icnsFile, size);
}
}
}
}
}
}
}
return {};
}
} // namespace juce
@@ -0,0 +1,39 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
Image JUCE_API getIconFromApplication (const String&, int);
Image JUCE_API getIconFromApplication (const String&, int) { return {}; }
}
File diff suppressed because it is too large Load Diff