OmaPhoto 1.0.0: the Linux port of Compositor
A layered image editor for Linux and Omarchy, ported from Compositor (github.com/robbietilton/Compositor), whose Swift source is its specification. It reads and writes Compositor's .comp projects. Packages for Ubuntu, Fedora and Arch come from the release workflow; scripts/install/ holds one install script per distribution family, and flake.nix serves NixOS. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
c864304695
564 files changed
+100804
No files matched your search
@@ -0,0 +1,35 @@
|
||||
#include "Rendering/AdjustmentSurface.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "Logging.h"
|
||||
#include <QPaintEngine>
|
||||
|
||||
void AdjustmentSurface::draw(QPainter &context, const std::function<void(QPainter &)> &body, qint64 pixelBudget)
|
||||
{
|
||||
// The engine's device holds the pixels: a widget's window store.
|
||||
const QPaintDevice &target = *context.paintEngine()->paintDevice();
|
||||
const QRect device(0, 0, target.width(), target.height());
|
||||
const QRect area = context.deviceTransform().mapRect(BrushRaster::visibleRect(context)).toAlignedRect().intersected(device);
|
||||
if (area.isEmpty())
|
||||
return;
|
||||
if (qint64(area.width()) * area.height() > pixelBudget) {
|
||||
qCWarning(lcRendering) << "an adjustment surface passes its pixel budget:" << area.size();
|
||||
return;
|
||||
}
|
||||
QImage surface(area.size(), QImage::Format_RGBA8888_Premultiplied);
|
||||
if (surface.isNull()) {
|
||||
qCWarning(lcRendering) << "an adjustment surface could not be allocated:" << area.size();
|
||||
return;
|
||||
}
|
||||
surface.fill(0);
|
||||
{
|
||||
// The body draws in the painter's own coordinates.
|
||||
QPainter painter(&surface);
|
||||
painter.setTransform(context.deviceTransform() * QTransform::fromTranslate(-area.left(), -area.top()));
|
||||
body(painter);
|
||||
}
|
||||
// Drawn back under the painter's own opacity, mode and clip.
|
||||
context.save();
|
||||
context.setWorldTransform(context.deviceTransform().inverted() * context.worldTransform());
|
||||
context.drawImage(QRectF(area), surface);
|
||||
context.restore();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include <QPainter>
|
||||
#include <functional>
|
||||
|
||||
// Draws through an image surface over what the painter shows.
|
||||
namespace AdjustmentSurface {
|
||||
inline constexpr qint64 pixelBudget = 100'000'000;
|
||||
void draw(QPainter &context, const std::function<void(QPainter &)> &body, qint64 pixelBudget = AdjustmentSurface::pixelBudget);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
#include "Rendering/BrushCoverage.h"
|
||||
#include "Rendering/PoolMap.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include <QtConcurrent>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
// The shader's uniforms.
|
||||
struct Uniforms {
|
||||
float a, b, c, d;
|
||||
float originX, originY, radius, hardness;
|
||||
float canvasWidth, canvasHeight, antialias, spacing;
|
||||
};
|
||||
|
||||
float segmentDistanceSquared(float px, float py, const BrushSegment &s)
|
||||
{
|
||||
const float vx = s.x1 - s.x0, vy = s.y1 - s.y0;
|
||||
const float t = std::clamp(((px - s.x0) * vx + (py - s.y0) * vy) / std::max(vx * vx + vy * vy, 1e-12f), 0.0f, 1.0f);
|
||||
const float dx = px - (s.x0 + t * vx), dy = py - (s.y0 + t * vy);
|
||||
return dx * dx + dy * dy;
|
||||
}
|
||||
|
||||
// The hard tip's antialiased silhouette, as the shader draws it.
|
||||
float hardCoverage(float distanceSquared, const Uniforms &u)
|
||||
{
|
||||
return std::clamp((u.radius - std::sqrt(distanceSquared)) / u.antialias + 0.5f, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
// The optical density at the solid core: coverage capped.
|
||||
const float solidDensity = -std::log(0.001f);
|
||||
|
||||
// The shader's soft falloff as optical density, float for float.
|
||||
float tipDensity(float distanceSquared, const Uniforms &u)
|
||||
{
|
||||
const float t = std::clamp((std::sqrt(distanceSquared) / u.radius - u.hardness) / (1.0f - u.hardness), 0.0f, 1.0f);
|
||||
// The solid and empty ends, as the formula yields them.
|
||||
if (t == 0.0f)
|
||||
return solidDensity;
|
||||
if (t == 1.0f)
|
||||
return 0.0f;
|
||||
const float coverage = std::max(0.0f, (std::exp(-2.5f * t * t) - std::exp(-2.5f)) / (1.0f - std::exp(-2.5f)));
|
||||
// Optical density adds; coverage is 1 − exp(−density).
|
||||
return -std::log(std::max(1.0f - coverage, 0.001f));
|
||||
}
|
||||
|
||||
// Table steps over d²/r², from hardness² out to the rim.
|
||||
constexpr int densitySteps = 8192;
|
||||
|
||||
// A soft tip's density, in radii; solid within its hardness.
|
||||
std::shared_ptr<const std::vector<float>> densityTable(float hardness)
|
||||
{
|
||||
static std::mutex lock;
|
||||
static float cached = -1;
|
||||
static std::shared_ptr<const std::vector<float>> table;
|
||||
const std::lock_guard<std::mutex> guard(lock);
|
||||
if (table && cached == hardness)
|
||||
return table;
|
||||
Uniforms unit{};
|
||||
unit.radius = 1;
|
||||
unit.hardness = hardness;
|
||||
const float start = hardness * hardness;
|
||||
auto values = std::make_shared<std::vector<float>>(size_t(densitySteps) + 1);
|
||||
for (int step = 0; step <= densitySteps; ++step)
|
||||
(*values)[size_t(step)] = tipDensity(start + (1 - start) * float(step) / densitySteps, unit);
|
||||
cached = hardness;
|
||||
table = values;
|
||||
return table;
|
||||
}
|
||||
|
||||
// Linear between steps; `core` clamps for the solid centre.
|
||||
template <bool core> float tableDensity(const std::vector<float> &table, float beyondStart, float scale)
|
||||
{
|
||||
float position = std::min(beyondStart * scale, float(densitySteps));
|
||||
if constexpr (core)
|
||||
position = std::max(position, 0.0f);
|
||||
const size_t index = size_t(std::min(int(position), densitySteps - 1));
|
||||
// One checked read: the upper step; the lower sits below.
|
||||
const float *const upper = &table[index + 1];
|
||||
return upper[-1] + (position - float(index)) * (upper[0] - upper[-1]);
|
||||
}
|
||||
|
||||
// A soft tip's density: from the table, or by formula.
|
||||
struct Fade {
|
||||
const std::vector<float> &table;
|
||||
// Where the table begins, h²r², and its steps per pixel².
|
||||
float start;
|
||||
float scale;
|
||||
// The table's steps finer than float can tell apart.
|
||||
bool exact;
|
||||
};
|
||||
|
||||
// Eight-point Gauss–Legendre quadrature, clipped to the tip.
|
||||
template <typename Density> float quadrature(float midpoint, float halfLength, float projection, const Density &density)
|
||||
{
|
||||
constexpr float nodes[4] = {0.1834346425f, 0.5255324099f, 0.7966664774f, 0.9602898565f};
|
||||
constexpr float weights[4] = {0.3626837834f, 0.3137066459f, 0.2223810345f, 0.1012285363f};
|
||||
float integral = 0.0f;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
// The shader's order: far along a stroke, float rounds differently.
|
||||
const float a = midpoint - halfLength * nodes[i] - projection, b = midpoint + halfLength * nodes[i] - projection;
|
||||
integral += weights[i] * (density(a * a) + density(b * b));
|
||||
}
|
||||
return integral;
|
||||
}
|
||||
|
||||
float segmentDensity(float px, float py, const BrushSegment &s, const Uniforms &u, const Fade &fade)
|
||||
{
|
||||
const float vx = s.x1 - s.x0, vy = s.y1 - s.y0;
|
||||
const float length = std::sqrt(vx * vx + vy * vy);
|
||||
if (length < 1e-6f) {
|
||||
const float distanceSquared = (px - s.x0) * (px - s.x0) + (py - s.y0) * (py - s.y0);
|
||||
return fade.exact ? tipDensity(distanceSquared, u) : tableDensity<true>(fade.table, distanceSquared - fade.start, fade.scale);
|
||||
}
|
||||
const float dx = vx / length, dy = vy / length;
|
||||
const float projection = (px - s.x0) * dx + (py - s.y0) * dy;
|
||||
const float perpX = px - s.x0 - projection * dx, perpY = py - s.y0 - projection * dy;
|
||||
const float perpendicularSquared = perpX * perpX + perpY * perpY;
|
||||
const float radiusSquared = u.radius * u.radius;
|
||||
if (perpendicularSquared >= radiusSquared)
|
||||
return 0.0f;
|
||||
const float reach = std::sqrt(radiusSquared - perpendicularSquared);
|
||||
const float lo = std::max(0.0f, projection - reach), hi = std::min(length, projection + reach);
|
||||
if (hi <= lo)
|
||||
return 0.0f;
|
||||
const float midpoint = (lo + hi) * 0.5f, halfLength = (hi - lo) * 0.5f;
|
||||
// The table counts from h²r², so shift once per segment.
|
||||
const float shifted = perpendicularSquared - fade.start;
|
||||
float integral;
|
||||
if (fade.exact)
|
||||
integral = quadrature(midpoint, halfLength, projection, [&](float along) { return tipDensity(perpendicularSquared + along, u); });
|
||||
else if (shifted < 0)
|
||||
// Only a segment through the solid core needs the clamp.
|
||||
integral = quadrature(midpoint, halfLength, projection, [&](float along) { return tableDensity<true>(fade.table, shifted + along, fade.scale); });
|
||||
else
|
||||
integral = quadrature(midpoint, halfLength, projection, [&](float along) { return tableDensity<false>(fade.table, shifted + along, fade.scale); });
|
||||
return integral * halfLength / u.spacing;
|
||||
}
|
||||
|
||||
// A tile's rows, from bits fetched before the threads.
|
||||
struct Band {
|
||||
const BrushCoverage::Work *work;
|
||||
uchar *bits;
|
||||
qsizetype stride;
|
||||
int top;
|
||||
int bottom;
|
||||
};
|
||||
|
||||
// Permanent paint and the replaceable tail stay apart.
|
||||
void renderBand(const Band &band, const Uniforms &u, const std::vector<BrushSegment> &segments, size_t settledCount, const std::vector<float> &table)
|
||||
{
|
||||
const BrushCoverage::Work &work = *band.work;
|
||||
const int width = int(work.rect.width());
|
||||
// The table's span, h²r² to r², in pixels squared.
|
||||
const float inner = u.hardness * u.hardness;
|
||||
const Fade fade{table, inner * u.radius * u.radius, densitySteps / ((1 - inner) * u.radius * u.radius),
|
||||
(1 - inner) / densitySteps < std::numeric_limits<float>::epsilon()};
|
||||
for (int y = band.top; y < band.bottom; ++y) {
|
||||
uchar *row = band.bits + y * band.stride;
|
||||
for (int x = 0; x < width; ++x) {
|
||||
float &permanent = work.tile->permanent[size_t(y) * width + x];
|
||||
const float lx = x + 0.5f, ly = y + 0.5f;
|
||||
const float px = u.originX + lx * u.a + ly * u.c, py = u.originY + lx * u.b + ly * u.d;
|
||||
if (px < 0 || py < 0 || px >= u.canvasWidth || py >= u.canvasHeight) {
|
||||
row[x] = 0;
|
||||
continue;
|
||||
}
|
||||
if (u.hardness >= 1.0f) {
|
||||
// Hard tips keep their antialiased silhouette.
|
||||
float settled = INFINITY, tail = INFINITY;
|
||||
for (size_t i = 0; i < settledCount; ++i)
|
||||
settled = std::min(settled, segmentDistanceSquared(px, py, segments[i]));
|
||||
for (size_t i = settledCount; i < segments.size(); ++i)
|
||||
tail = std::min(tail, segmentDistanceSquared(px, py, segments[i]));
|
||||
const float value = std::max(permanent, hardCoverage(settled, u));
|
||||
permanent = value;
|
||||
row[x] = uchar(std::round(255.0f * std::max(value, hardCoverage(tail, u))));
|
||||
} else {
|
||||
float value = permanent, tail = 0.0f;
|
||||
for (size_t i = 0; i < settledCount; ++i)
|
||||
value += segmentDensity(px, py, segments[i], u, fade);
|
||||
for (size_t i = settledCount; i < segments.size(); ++i)
|
||||
tail += segmentDensity(px, py, segments[i], u, fade);
|
||||
permanent = std::min(value, 20.0f);
|
||||
row[x] = uchar(std::round(255.0f * (1.0f - std::exp(-std::min(value + tail, 20.0f)))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BrushCoverage::Tile BrushCoverage::tile(int width, int height)
|
||||
{
|
||||
try {
|
||||
return Tile{std::vector<float>(size_t(width) * size_t(height), 0.0f)};
|
||||
} catch (const std::bad_alloc &) {
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
}
|
||||
}
|
||||
|
||||
void BrushCoverage::render(const std::vector<Work> &tiles, const std::vector<BrushSegment> &settled, const std::vector<BrushSegment> &tail,
|
||||
const QTransform &mapping, const BrushSettings &settings, QSizeF canvas)
|
||||
{
|
||||
if (tiles.empty())
|
||||
return;
|
||||
std::vector<BrushSegment> segments = settled;
|
||||
segments.insert(segments.end(), tail.begin(), tail.end());
|
||||
Uniforms base{};
|
||||
base.a = float(mapping.m11());
|
||||
base.b = float(mapping.m12());
|
||||
base.c = float(mapping.m21());
|
||||
base.d = float(mapping.m22());
|
||||
base.radius = float(settings.diameter / 2);
|
||||
base.hardness = float(settings.hardness);
|
||||
base.canvasWidth = float(canvas.width());
|
||||
base.canvasHeight = float(canvas.height());
|
||||
base.antialias = float(std::max(0.001, std::min(std::hypot(mapping.m11(), mapping.m12()), std::hypot(mapping.m21(), mapping.m22()))));
|
||||
base.spacing = float(std::max(0.25, settings.diameter * BrushStroke::spacingFraction(settings.hardness)));
|
||||
const std::shared_ptr<const std::vector<float>> table = densityTable(base.hardness);
|
||||
// Row bands keep every core busy, however few tiles changed.
|
||||
std::vector<Band> bands;
|
||||
for (const Work &item : tiles) {
|
||||
uchar *const bits = item.context->bits();
|
||||
const int height = int(item.rect.height());
|
||||
for (int top = 0; top < height; top += 32)
|
||||
bands.push_back({&item, bits, item.context->bytesPerLine(), top, std::min(height, top + 32)});
|
||||
}
|
||||
PoolMap::blocking(bands, [&](const Band &band) {
|
||||
Uniforms u = base;
|
||||
const QPointF origin = mapping.map(band.work->rect.topLeft());
|
||||
u.originX = float(origin.x());
|
||||
u.originY = float(origin.y());
|
||||
renderBand(band, u, segments, settled.size(), *table);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include <QImage>
|
||||
#include <QRectF>
|
||||
#include <QSizeF>
|
||||
#include <QTransform>
|
||||
#include <vector>
|
||||
|
||||
struct BrushSettings;
|
||||
|
||||
// A piece of the centreline, in document points (Swift's SIMD4).
|
||||
struct BrushSegment {
|
||||
float x0;
|
||||
float y0;
|
||||
float x1;
|
||||
float y1;
|
||||
};
|
||||
|
||||
// Twin of MetalBrushCoverage: the continuous brush on the CPU.
|
||||
namespace BrushCoverage {
|
||||
// Density laid so far, a float a pixel.
|
||||
struct Tile {
|
||||
std::vector<float> permanent;
|
||||
};
|
||||
// One tile's density, rect, and the gray context previewed.
|
||||
struct Work {
|
||||
Tile *tile;
|
||||
QRectF rect;
|
||||
QImage *context;
|
||||
};
|
||||
Tile tile(int width, int height);
|
||||
void render(const std::vector<Work> &tiles, const std::vector<BrushSegment> &settled, const std::vector<BrushSegment> &tail,
|
||||
const QTransform &mapping, const BrushSettings &settings, QSizeF canvas);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#include "Rendering/BrushCursorOverlay.h"
|
||||
#include "Rendering/AdjustmentSurface.h"
|
||||
#include <QPainterPath>
|
||||
|
||||
namespace {
|
||||
// A white line under a black one, as Swift's.
|
||||
void stroked(QPainter &painter, const QRectF &ellipse, bool dashed)
|
||||
{
|
||||
for (const auto &[colour, width] : {std::pair(QColor(Qt::white), 2.5), std::pair(QColor(Qt::black), 1.0)}) {
|
||||
QPen pen(colour, width, Qt::SolidLine, Qt::FlatCap);
|
||||
// Four on, three off, in points: Qt counts in widths.
|
||||
if (dashed)
|
||||
pen.setDashPattern({4 / width, 3 / width});
|
||||
painter.setPen(pen);
|
||||
painter.drawEllipse(ellipse);
|
||||
}
|
||||
}
|
||||
|
||||
QRect around(QPointF point, double reach)
|
||||
{
|
||||
return QRectF(point.x() - reach, point.y() - reach, reach * 2, reach * 2).toAlignedRect();
|
||||
}
|
||||
}
|
||||
|
||||
QRegion BrushCursorOverlay::update(std::optional<QPointF> point, double diameter, std::optional<double> hardness, std::optional<QPointF> sample,
|
||||
const QImage &preview, double previewOpacity, const QImage &tip)
|
||||
{
|
||||
const std::optional<QRectF> next = point ? std::optional(QRectF(point->x() - diameter / 2, point->y() - diameter / 2, diameter, diameter)) : std::nullopt;
|
||||
QRegion dirty;
|
||||
// Images compare by identity, as Swift's `!==`.
|
||||
if (m_circle != next || m_preview.cacheKey() != preview.cacheKey() || m_previewOpacity != previewOpacity || m_tip.cacheKey() != tip.cacheKey()
|
||||
|| m_hardness != hardness) {
|
||||
if (m_circle)
|
||||
dirty += m_circle->adjusted(-3, -3, 3, 3).toAlignedRect();
|
||||
m_circle = next;
|
||||
m_preview = preview;
|
||||
m_previewOpacity = previewOpacity;
|
||||
m_tip = tip;
|
||||
m_hardness = hardness;
|
||||
if (m_circle)
|
||||
dirty += m_circle->adjusted(-3, -3, 3, 3).toAlignedRect();
|
||||
}
|
||||
if (m_marker != sample) {
|
||||
if (m_marker)
|
||||
dirty += around(*m_marker, markerReach + 3);
|
||||
m_marker = sample;
|
||||
if (m_marker)
|
||||
dirty += around(*m_marker, markerReach + 3);
|
||||
}
|
||||
return dirty;
|
||||
}
|
||||
|
||||
void BrushCursorOverlay::draw(QPainter &painter) const
|
||||
{
|
||||
painter.save();
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
if (m_circle) {
|
||||
if (!m_preview.isNull()) {
|
||||
painter.save();
|
||||
QPainterPath ellipse;
|
||||
ellipse.addEllipse(*m_circle);
|
||||
painter.setClipPath(ellipse, Qt::IntersectClip);
|
||||
painter.setOpacity(painter.opacity() * m_previewOpacity);
|
||||
// Swift's transparency layer: the tip cuts at drawing resolution.
|
||||
AdjustmentSurface::draw(painter, [this](QPainter &layer) {
|
||||
layer.setRenderHint(QPainter::SmoothPixmapTransform);
|
||||
layer.drawImage(*m_circle, m_preview);
|
||||
// Only what one click lays down: soft tips preview softly.
|
||||
layer.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
layer.drawImage(*m_circle, m_tip);
|
||||
});
|
||||
painter.restore();
|
||||
}
|
||||
stroked(painter, *m_circle, false);
|
||||
// At zero hardness the inner ellipse has no size.
|
||||
if (m_hardness) {
|
||||
const double inset = m_circle->width() * (1 - *m_hardness) / 2;
|
||||
stroked(painter, m_circle->adjusted(inset, inset, -inset, -inset), true);
|
||||
}
|
||||
}
|
||||
if (m_marker) {
|
||||
QPainterPath arms;
|
||||
arms.moveTo(m_marker->x() - markerReach, m_marker->y());
|
||||
arms.lineTo(m_marker->x() + markerReach, m_marker->y());
|
||||
arms.moveTo(m_marker->x(), m_marker->y() - markerReach);
|
||||
arms.lineTo(m_marker->x(), m_marker->y() + markerReach);
|
||||
for (const auto &[colour, width] : {std::pair(QColor(Qt::white), 3.0), std::pair(QColor(Qt::black), 1.0)})
|
||||
painter.strokePath(arms, QPen(colour, width, Qt::SolidLine, Qt::RoundCap));
|
||||
}
|
||||
painter.restore();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <QRegion>
|
||||
#include <optional>
|
||||
|
||||
// Swift's brush circle; the canvas draws it over its pixels.
|
||||
class BrushCursorOverlay {
|
||||
public:
|
||||
// Moves circle and marker; returns the old and new areas.
|
||||
QRegion update(std::optional<QPointF> point, double diameter, std::optional<double> hardness,
|
||||
std::optional<QPointF> sample = std::nullopt, const QImage &preview = QImage(), double previewOpacity = 1,
|
||||
const QImage &tip = QImage());
|
||||
void draw(QPainter &painter) const;
|
||||
std::optional<QRectF> circle() const { return m_circle; }
|
||||
std::optional<double> hardness() const { return m_hardness; }
|
||||
std::optional<QPointF> marker() const { return m_marker; }
|
||||
const QImage &preview() const { return m_preview; }
|
||||
const QImage &tip() const { return m_tip; }
|
||||
|
||||
private:
|
||||
static constexpr double markerReach = 7;
|
||||
std::optional<QRectF> m_circle;
|
||||
// Clone Stamp's source crosshair, in view points.
|
||||
std::optional<QPointF> m_marker;
|
||||
// What a Clone Stamp click would stamp, inside the circle.
|
||||
QImage m_preview;
|
||||
double m_previewOpacity = 1;
|
||||
// One click's coverage, shaping the preview's edge.
|
||||
QImage m_tip;
|
||||
// While hardness is dragged: the full-strength share, as a ring.
|
||||
std::optional<double> m_hardness;
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "Rendering/CanvasViewport.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
QRectF CanvasViewport::documentRect(QSizeF size) const
|
||||
{
|
||||
const QSizeF scaled(size.width() * pointsPerPixel(), size.height() * pointsPerPixel());
|
||||
return {center().x() - scaled.width() / 2 + pan.width(),
|
||||
center().y() - scaled.height() / 2 + pan.height(), scaled.width(), scaled.height()};
|
||||
}
|
||||
|
||||
QPointF CanvasViewport::documentPoint(QPointF from, QSizeF documentSize) const
|
||||
{
|
||||
const QPointF origin = documentRect(documentSize).topLeft();
|
||||
return {(from.x() - origin.x()) / pointsPerPixel(), (from.y() - origin.y()) / pointsPerPixel()};
|
||||
}
|
||||
|
||||
QPointF CanvasViewport::viewPoint(QPointF from, QSizeF documentSize) const
|
||||
{
|
||||
const QPointF origin = documentRect(documentSize).topLeft();
|
||||
return {origin.x() + from.x() * pointsPerPixel(), origin.y() + from.y() * pointsPerPixel()};
|
||||
}
|
||||
|
||||
void CanvasViewport::fit(QSizeF documentSize)
|
||||
{
|
||||
m_followsFit = true;
|
||||
if (viewSize.width() <= 0 || viewSize.height() <= 0)
|
||||
return;
|
||||
const double fitted = std::min(std::max(1.0, viewSize.width() - 96) / documentSize.width(),
|
||||
std::max(1.0, viewSize.height() - 96) / documentSize.height());
|
||||
m_zoom = std::clamp(fitted * backingScale, minimumZoom, maximumZoom);
|
||||
pan = {0, 0};
|
||||
}
|
||||
|
||||
void CanvasViewport::resize(QSizeF to, double newScale, std::optional<QSizeF> documentSize)
|
||||
{
|
||||
const double oldScale = pointsPerPixel();
|
||||
viewSize = to;
|
||||
backingScale = std::max(1.0, newScale);
|
||||
if (m_followsFit && documentSize) {
|
||||
fit(*documentSize);
|
||||
return;
|
||||
}
|
||||
const double ratio = pointsPerPixel() / oldScale;
|
||||
pan = {pan.width() * ratio, pan.height() * ratio};
|
||||
}
|
||||
|
||||
void CanvasViewport::setZoom(double value, QPointF anchoredAt, QSizeF documentSize)
|
||||
{
|
||||
if (!std::isfinite(value))
|
||||
return;
|
||||
const QPointF pixel = documentPoint(anchoredAt, documentSize);
|
||||
m_zoom = std::clamp(value, minimumZoom, maximumZoom);
|
||||
const QPointF moved = viewPoint(pixel, documentSize);
|
||||
pan += QSizeF(anchoredAt.x() - moved.x(), anchoredAt.y() - moved.y());
|
||||
m_followsFit = false;
|
||||
}
|
||||
|
||||
void CanvasViewport::translate(QSizeF by)
|
||||
{
|
||||
pan += by;
|
||||
m_followsFit = false;
|
||||
}
|
||||
|
||||
bool operator==(const CanvasViewport &lhs, const CanvasViewport &rhs)
|
||||
{
|
||||
return lhs.viewSize.width() == rhs.viewSize.width() && lhs.viewSize.height() == rhs.viewSize.height()
|
||||
&& lhs.backingScale == rhs.backingScale && lhs.m_zoom == rhs.m_zoom
|
||||
&& lhs.pan.width() == rhs.pan.width() && lhs.pan.height() == rhs.pan.height()
|
||||
&& lhs.m_followsFit == rhs.m_followsFit;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
#include <QPointF>
|
||||
#include <QRectF>
|
||||
#include <QSizeF>
|
||||
#include <optional>
|
||||
|
||||
// Document: top-left pixels. View: widget points. Zoom 1: device pixels.
|
||||
class CanvasViewport {
|
||||
public:
|
||||
static constexpr double minimumZoom = 0.001;
|
||||
static constexpr double maximumZoom = 32;
|
||||
|
||||
QSizeF viewSize{0, 0};
|
||||
double backingScale = 1;
|
||||
QSizeF pan{0, 0};
|
||||
|
||||
double zoom() const { return m_zoom; }
|
||||
bool followsFit() const { return m_followsFit; }
|
||||
double pointsPerPixel() const { return m_zoom / backingScale; }
|
||||
QPointF center() const { return {viewSize.width() / 2, viewSize.height() / 2}; }
|
||||
|
||||
QRectF documentRect(QSizeF size) const;
|
||||
QPointF documentPoint(QPointF from, QSizeF documentSize) const;
|
||||
QPointF viewPoint(QPointF from, QSizeF documentSize) const;
|
||||
void fit(QSizeF documentSize);
|
||||
void resize(QSizeF to, double backingScale, std::optional<QSizeF> documentSize);
|
||||
void setZoom(double value, QPointF anchoredAt, QSizeF documentSize);
|
||||
void translate(QSizeF by);
|
||||
friend bool operator==(const CanvasViewport &lhs, const CanvasViewport &rhs);
|
||||
|
||||
private:
|
||||
double m_zoom = 1;
|
||||
bool m_followsFit = true;
|
||||
};
|
||||
@@ -0,0 +1,268 @@
|
||||
#include "Rendering/DownsampleCache.h"
|
||||
#include "Rendering/PoolMap.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include <QThreadPool>
|
||||
#include <QtConcurrent>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <numbers>
|
||||
|
||||
extern "C" {
|
||||
#include "AdjustPixels.h"
|
||||
}
|
||||
|
||||
namespace {
|
||||
constexpr int taps = 12;
|
||||
|
||||
// Lanczos-3 at half scale, sampled between source pixels.
|
||||
const std::array<float, taps> &kernel()
|
||||
{
|
||||
static const std::array<float, taps> weights = [] {
|
||||
std::array<double, taps> lobes{};
|
||||
double sum = 0;
|
||||
for (int tap = 0; tap < taps; ++tap) {
|
||||
const double x = std::numbers::pi * (tap - 5.5) / 2;
|
||||
lobes[tap] = std::sin(x) / x * std::sin(x / 3) / (x / 3);
|
||||
sum += lobes[tap];
|
||||
}
|
||||
std::array<float, taps> result{};
|
||||
for (int tap = 0; tap < taps; ++tap)
|
||||
result[tap] = float(lobes[tap] / sum);
|
||||
return result;
|
||||
}();
|
||||
return weights;
|
||||
}
|
||||
|
||||
// A mask's row, one channel: scalar, clamped at the edges.
|
||||
void filterMaskRow(const uchar *row, int width, float *line, int outWidth)
|
||||
{
|
||||
const float *const weights = kernel().data();
|
||||
for (int x = 0; x < outWidth; ++x) {
|
||||
float sum = 0;
|
||||
for (int tap = 0; tap < taps; ++tap)
|
||||
sum += weights[tap] * float(row[std::clamp(2 * x - 5 + tap, 0, width - 1)]);
|
||||
line[x] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
// Four channels in one vector: each lane sums as before.
|
||||
using Float4 = float __attribute__((vector_size(16)));
|
||||
|
||||
void filterColorRow(const uchar *row, int width, float *line, int outWidth, float *floats)
|
||||
{
|
||||
for (int index = 0; index < width * 4; ++index)
|
||||
floats[index] = float(row[index]);
|
||||
const float *const weights = kernel().data();
|
||||
for (int x = 0; x < outWidth; ++x) {
|
||||
Float4 sum = {0, 0, 0, 0};
|
||||
for (int tap = 0; tap < taps; ++tap) {
|
||||
Float4 pixel;
|
||||
std::memcpy(&pixel, floats + std::clamp(2 * x - 5 + tap, 0, width - 1) * 4, sizeof pixel);
|
||||
sum += weights[tap] * pixel;
|
||||
}
|
||||
std::memcpy(line + x * 4, &sum, sizeof sum);
|
||||
}
|
||||
}
|
||||
|
||||
// One band's scratch: twelve rows, sums, a source row.
|
||||
struct Band {
|
||||
int first;
|
||||
int last;
|
||||
float *lines;
|
||||
float *sums;
|
||||
float *floats;
|
||||
};
|
||||
|
||||
struct Target {
|
||||
uchar *bits;
|
||||
qsizetype stride;
|
||||
int width;
|
||||
};
|
||||
|
||||
template <int channels> void filterBand(const QImage &source, const Target &target, const Band &band)
|
||||
{
|
||||
const float *const weights = kernel().data();
|
||||
const int samples = target.width * channels;
|
||||
std::array<int, taps> held;
|
||||
held.fill(-1);
|
||||
for (int y = band.first; y < band.last; ++y) {
|
||||
std::array<const float *, taps> rows;
|
||||
for (int tap = 0; tap < taps; ++tap) {
|
||||
const int sourceRow = std::clamp(2 * y - 5 + tap, 0, source.height() - 1);
|
||||
const int slot = sourceRow % taps;
|
||||
float *line = band.lines + size_t(slot) * samples;
|
||||
if (held[slot] != sourceRow) {
|
||||
if (channels == 4)
|
||||
filterColorRow(source.constScanLine(sourceRow), source.width(), line, target.width, band.floats);
|
||||
else
|
||||
filterMaskRow(source.constScanLine(sourceRow), source.width(), line, target.width);
|
||||
held[slot] = sourceRow;
|
||||
}
|
||||
rows[tap] = line;
|
||||
}
|
||||
// Tap by tap over whole rows: the same order, contiguous.
|
||||
float *const sum = band.sums;
|
||||
std::fill(sum, sum + samples, 0.0f);
|
||||
for (int tap = 0; tap < taps; ++tap) {
|
||||
const float weight = weights[tap];
|
||||
const float *const row = rows.data()[tap];
|
||||
for (int sample = 0; sample < samples; ++sample)
|
||||
sum[sample] += weight * row[sample];
|
||||
}
|
||||
uchar *out = target.bits + y * target.stride;
|
||||
for (int sample = 0; sample < samples; ++sample)
|
||||
out[sample] = uchar(std::clamp(int(sum[sample] + 0.5f), 0, 255));
|
||||
}
|
||||
}
|
||||
|
||||
void filterBand(const QImage &source, const Target &target, int channels, const Band &band)
|
||||
{
|
||||
if (channels == 4)
|
||||
filterBand<4>(source, target, band);
|
||||
else
|
||||
filterBand<1>(source, target, band);
|
||||
}
|
||||
|
||||
// False when the scratch rows cannot be allocated.
|
||||
bool lanczosHalve(const QImage &source, QImage &destination, int channels, bool threaded)
|
||||
{
|
||||
const int height = destination.height();
|
||||
const int count = threaded ? std::clamp(height / 32, 1, QThreadPool::globalInstance()->maxThreadCount()) : 1;
|
||||
const size_t samples = size_t(destination.width()) * channels;
|
||||
// Workers allocate nothing: a failure throws here, caught below.
|
||||
const size_t bandFloats = size_t(taps) * samples + samples + size_t(source.width()) * channels;
|
||||
// Writable bits are fetched once: scanLine() is not thread-safe.
|
||||
const Target target{destination.bits(), destination.bytesPerLine(), destination.width()};
|
||||
try {
|
||||
std::vector<float> scratch(bandFloats * count);
|
||||
std::vector<Band> bands;
|
||||
for (int index = 0; index < count; ++index) {
|
||||
float *const lines = scratch.data() + bandFloats * index;
|
||||
bands.push_back({height * index / count, height * (index + 1) / count, lines, lines + taps * samples, lines + taps * samples + samples});
|
||||
}
|
||||
if (threaded)
|
||||
PoolMap::blocking(bands, [&](const Band &band) { filterBand(source, target, channels, band); });
|
||||
else
|
||||
filterBand(source, target, channels, bands.front());
|
||||
} catch (const std::bad_alloc &) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
DownsampleCache::DownsampleCache(qint64 pixelBudget) : m_pixelBudget(pixelBudget) {}
|
||||
|
||||
DownsampleCache &DownsampleCache::shared()
|
||||
{
|
||||
static DownsampleCache cache;
|
||||
return cache;
|
||||
}
|
||||
|
||||
qint64 DownsampleCache::Entry::pixels() const
|
||||
{
|
||||
qint64 total = 0;
|
||||
for (const QImage &level : levels)
|
||||
total += qint64(level.width()) * level.height();
|
||||
return total;
|
||||
}
|
||||
|
||||
int DownsampleCache::level(double factor)
|
||||
{
|
||||
if (!std::isfinite(factor) || factor <= 0 || factor >= 0.5)
|
||||
return 0;
|
||||
return std::min(maxLevel, int(std::floor(std::log2(1 / factor))));
|
||||
}
|
||||
|
||||
QImage DownsampleCache::imageDrawnAt(const QImage &image, double factor)
|
||||
{
|
||||
return imageAtLevel(image, level(factor)).image;
|
||||
}
|
||||
|
||||
DownsampleCache::Reduced DownsampleCache::imageAtLevel(const QImage &image, int wanted)
|
||||
{
|
||||
if (wanted < 1 || (image.width() <= 1 && image.height() <= 1))
|
||||
return {image, 0};
|
||||
const qint64 key = image.cacheKey();
|
||||
std::vector<QImage> levels;
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
m_clock += 1;
|
||||
if (const auto found = m_entries.find(key); found != m_entries.end())
|
||||
levels = found->second.levels;
|
||||
}
|
||||
while (int(levels.size()) < wanted) {
|
||||
const QImage &previous = levels.empty() ? image : levels.back();
|
||||
if (previous.width() <= 1 && previous.height() <= 1)
|
||||
break;
|
||||
const std::optional<QImage> next = halve(previous);
|
||||
if (!next)
|
||||
break;
|
||||
levels.push_back(*next);
|
||||
}
|
||||
if (levels.empty())
|
||||
return {image, 0};
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
const auto found = m_entries.find(key);
|
||||
if (found != m_entries.end() && found->second.levels.size() >= levels.size())
|
||||
found->second.lastUse = m_clock;
|
||||
else
|
||||
m_entries.insert_or_assign(key, Entry{image, levels, m_clock});
|
||||
evict(key);
|
||||
}
|
||||
const int applied = std::min(wanted, int(levels.size()));
|
||||
return {levels[applied - 1], applied};
|
||||
}
|
||||
|
||||
void DownsampleCache::evict(qint64 keeping)
|
||||
{
|
||||
qint64 total = 0;
|
||||
for (const auto &[key, entry] : m_entries)
|
||||
total += entry.pixels();
|
||||
while (total > m_pixelBudget) {
|
||||
auto oldest = m_entries.end();
|
||||
for (auto entry = m_entries.begin(); entry != m_entries.end(); ++entry) {
|
||||
if (entry->first != keeping && (oldest == m_entries.end() || entry->second.lastUse < oldest->second.lastUse))
|
||||
oldest = entry;
|
||||
}
|
||||
if (oldest == m_entries.end())
|
||||
return;
|
||||
total -= oldest->second.pixels();
|
||||
m_entries.erase(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<QImage> DownsampleCache::halve(const QImage &image, bool threaded)
|
||||
{
|
||||
const bool mask = image.format() == QImage::Format_Grayscale8;
|
||||
const int width = (image.width() + 1) / 2, height = (image.height() + 1) / 2;
|
||||
// Color fades into transparent padding wherever an image is cut.
|
||||
const int pad = mask ? 0 : 8;
|
||||
const int paddedWidth = width * 2 + pad * 2, paddedHeight = height * 2 + pad * 2;
|
||||
const QImage::Format format = mask ? QImage::Format_Grayscale8 : QImage::Format_RGBA8888_Premultiplied;
|
||||
QImage source(paddedWidth, paddedHeight, format), destination(paddedWidth / 2, paddedHeight / 2, format);
|
||||
if (source.isNull() || destination.isNull())
|
||||
return std::nullopt;
|
||||
source.fill(0);
|
||||
{
|
||||
QPainter painter(&source);
|
||||
BrushRaster::draw(image, QRectF(pad, pad, image.width(), image.height()), painter);
|
||||
}
|
||||
if (mask) {
|
||||
// An odd last column and row repeat.
|
||||
for (int y = 0; y < image.height() && paddedWidth > image.width(); ++y)
|
||||
source.scanLine(y)[image.width()] = source.constScanLine(y)[image.width() - 1];
|
||||
if (paddedHeight > image.height())
|
||||
std::copy_n(source.constScanLine(image.height() - 1), paddedWidth, source.scanLine(image.height()));
|
||||
}
|
||||
if (!lanczosHalve(source, destination, mask ? 1 : 4, threaded))
|
||||
return std::nullopt;
|
||||
if (mask)
|
||||
return destination;
|
||||
rgba_clamp_premultiplied(destination.bits(), size_t(destination.width()) * destination.height());
|
||||
const QImage cropped = destination.copy(pad / 2, pad / 2, width, height);
|
||||
return cropped.isNull() ? std::nullopt : std::optional(cropped);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
#include <QImage>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
// Sharp halved copies of layer images, least recently used dropped.
|
||||
class DownsampleCache {
|
||||
public:
|
||||
// Pixels of halved copies kept at once.
|
||||
static constexpr qint64 pixelBudget = 100'000'000;
|
||||
// Most halvings ever used; QPainter does the rest.
|
||||
static constexpr int maxLevel = 6;
|
||||
|
||||
struct Reduced {
|
||||
QImage image;
|
||||
int level;
|
||||
};
|
||||
|
||||
explicit DownsampleCache(qint64 pixelBudget = DownsampleCache::pixelBudget);
|
||||
static DownsampleCache &shared();
|
||||
|
||||
static int level(double factor);
|
||||
QImage imageDrawnAt(const QImage &image, double factor);
|
||||
Reduced imageAtLevel(const QImage &image, int wanted);
|
||||
// Unthreaded when its caller already works side by side.
|
||||
static std::optional<QImage> halve(const QImage &image, bool threaded = true);
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
QImage source;
|
||||
std::vector<QImage> levels;
|
||||
quint64 lastUse;
|
||||
qint64 pixels() const;
|
||||
};
|
||||
|
||||
void evict(qint64 keeping);
|
||||
|
||||
const qint64 m_pixelBudget;
|
||||
std::unordered_map<qint64, Entry> m_entries;
|
||||
quint64 m_clock = 0;
|
||||
std::mutex m_lock;
|
||||
};
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "IO/ProjectStore.h"
|
||||
#include "Logging.h"
|
||||
#include <QKeyEvent>
|
||||
#include <cmath>
|
||||
|
||||
// Swift's brush on the canvas: strokes, tip drag, circle.
|
||||
void CanvasView::brushMouseDown(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document().value().size());
|
||||
// Alt-click with Clone Stamp sets where it copies from.
|
||||
if (m_session.tool() == NavigationTool::cloneStamp && modifiers.testFlag(Qt::AltModifier)) {
|
||||
m_session.setCloneSource(pixel);
|
||||
updateBrushCursor();
|
||||
return;
|
||||
}
|
||||
m_brushPointer = point;
|
||||
// Shift paints a line on from the last stroke's end.
|
||||
const bool shift = modifiers.testFlag(Qt::ShiftModifier);
|
||||
const std::optional<QPointF> from = shift ? m_session.shiftLineStart() : std::nullopt;
|
||||
if (from) {
|
||||
m_session.beginBrush(*from);
|
||||
m_session.continueBrush(pixel);
|
||||
} else {
|
||||
m_session.beginBrush(pixel);
|
||||
}
|
||||
m_brushAxisAnchor = shift ? std::optional(pixel) : std::nullopt;
|
||||
m_brushAxisHorizontal = std::nullopt;
|
||||
m_brushLastPixel = pixel;
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
// The circle follows; a drag goes on, Shift keeping axis.
|
||||
bool CanvasView::brushMouseMove(QPointF point, Qt::KeyboardModifiers modifiers, bool dragging)
|
||||
{
|
||||
m_brushPointer = point;
|
||||
updateBrushCursor();
|
||||
// Swift's mouseMoved paints nothing; mouseDragged does.
|
||||
if (!dragging || (!m_session.brushStroke() && !m_session.warpStroke()) || m_session.isProjectBusy() || !m_session.document())
|
||||
return false;
|
||||
QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
if (modifiers.testFlag(Qt::ShiftModifier)) {
|
||||
// The first three pixels settle the axis; it never flips.
|
||||
const QPointF anchor = m_brushAxisAnchor ? *m_brushAxisAnchor : m_brushLastPixel.value_or(pixel);
|
||||
if (!m_brushAxisAnchor) {
|
||||
m_brushAxisAnchor = anchor;
|
||||
m_brushAxisHorizontal = std::nullopt;
|
||||
}
|
||||
if (!m_brushAxisHorizontal && std::hypot(pixel.x() - anchor.x(), pixel.y() - anchor.y()) >= 3)
|
||||
m_brushAxisHorizontal = std::abs(pixel.x() - anchor.x()) >= std::abs(pixel.y() - anchor.y());
|
||||
if (m_brushAxisHorizontal)
|
||||
pixel = *m_brushAxisHorizontal ? QPointF(pixel.x(), anchor.y()) : QPointF(anchor.x(), pixel.y());
|
||||
else
|
||||
pixel = anchor;
|
||||
} else {
|
||||
// Re-anchoring resets the axis, so the anchor alone goes.
|
||||
m_brushAxisAnchor = std::nullopt;
|
||||
}
|
||||
m_brushLastPixel = pixel;
|
||||
m_session.continueBrush(pixel);
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
|
||||
// The release reaches its own point, then the stroke lands.
|
||||
void CanvasView::brushMouseUp(QPointF point)
|
||||
{
|
||||
if ((!m_session.brushStroke() && !m_session.warpStroke()) || m_session.isProjectBusy())
|
||||
return;
|
||||
if (m_session.document())
|
||||
m_session.continueBrush(m_session.viewport.documentPoint(point, m_session.document()->size()));
|
||||
m_session.finishBrushImmediately();
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
// Right-drag: size across, hardness with Shift; the circle stays.
|
||||
void CanvasView::beginBrushTipDrag(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const BrushSettings &settings = m_session.brushSettings();
|
||||
m_brushTipDrag = BrushTipDrag{point, settings.diameter, settings.hardness, modifiers.testFlag(Qt::ShiftModifier)};
|
||||
m_brushPointer = point;
|
||||
updateBrushCursor();
|
||||
}
|
||||
|
||||
void CanvasView::dragBrushTip(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
BrushTipDrag &drag = m_brushTipDrag.value();
|
||||
drag.hardnessShown = modifiers.testFlag(Qt::ShiftModifier);
|
||||
const double dx = point.x() - drag.start.x();
|
||||
BrushSettings settings = m_session.brushSettings();
|
||||
if (drag.hardnessShown) {
|
||||
// The full range across 200 points.
|
||||
settings.hardness = std::clamp(drag.hardness + dx / 200, 0.0, 1.0);
|
||||
settings.diameter = drag.diameter;
|
||||
} else {
|
||||
// The circle's edge follows the pointer on screen.
|
||||
const double perPixel = std::max(0.0001, m_session.viewport.pointsPerPixel());
|
||||
settings.diameter = std::clamp(std::round(drag.diameter + 2 * dx / perPixel), 1.0, 2000.0);
|
||||
settings.hardness = drag.hardness;
|
||||
}
|
||||
m_session.setBrushSettings(settings);
|
||||
m_brushPointer = drag.start;
|
||||
updateBrushCursor();
|
||||
}
|
||||
|
||||
void CanvasView::endBrushTipDrag(QPointF point)
|
||||
{
|
||||
m_brushTipDrag = std::nullopt;
|
||||
m_brushPointer = point;
|
||||
updateBrushCursor();
|
||||
}
|
||||
|
||||
// The circle at the pointer, a stroke's own size.
|
||||
void CanvasView::updateBrushCursor()
|
||||
{
|
||||
const bool shows = isBrushTool(m_session.tool()) && !m_spaceHeld && !picking();
|
||||
const double diameter = m_session.brushStroke() ? m_session.brushStroke()->settings.diameter : m_session.brushSettings().diameter;
|
||||
// Clone Stamp marks its source; between strokes, previews a click.
|
||||
std::optional<QPointF> sample;
|
||||
QImage preview;
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (shows && m_session.tool() == NavigationTool::cloneStamp && m_brushPointer && document) {
|
||||
const QPointF point = m_session.viewport.documentPoint(*m_brushPointer, document->size());
|
||||
if (const std::optional<QPointF> source = m_session.cloneSamplePoint(point))
|
||||
sample = m_session.viewport.viewPoint(*source, document->size());
|
||||
const std::optional<QSizeF> offset = m_session.cloneStrokeOffset(point);
|
||||
if (!m_session.brushStroke() && !m_optionHeld && offset)
|
||||
preview = clonePreview(point + QPointF(offset->width(), offset->height()), diameter, *document);
|
||||
}
|
||||
const std::optional<double> hardness = m_brushTipDrag && m_brushTipDrag->hardnessShown ? std::optional(m_session.brushSettings().hardness) : std::nullopt;
|
||||
const QImage tip = preview.isNull() ? QImage() : cloneTip(diameter, m_session.brushSettings().hardness);
|
||||
update(m_brushCursor.update(shows ? m_brushPointer : std::nullopt, std::max(1.0, diameter * m_session.viewport.pointsPerPixel()), hardness, sample,
|
||||
preview, m_session.brushSettings().opacity, tip));
|
||||
}
|
||||
|
||||
// The brush engine paints one click; the preview softens alike.
|
||||
QImage CanvasView::cloneTip(double diameter, double hardness)
|
||||
{
|
||||
if (m_cloneTip && m_cloneTip->diameter == diameter && m_cloneTip->hardness == hardness)
|
||||
return m_cloneTip->image;
|
||||
const int side = std::max(1, int(std::ceil(diameter)));
|
||||
const QSizeF size(side, side);
|
||||
BrushSettings settings{.diameter = diameter, .hardness = hardness, .red = 1, .green = 1, .blue = 1};
|
||||
QImage image;
|
||||
try {
|
||||
BrushStroke stroke(ImageLayer(QStringLiteral("Tip"), size), false, settings, size);
|
||||
stroke.append(QPointF(side / 2.0, side / 2.0));
|
||||
stroke.flush();
|
||||
const PaintSnapshot painted = stroke.paintSnapshot();
|
||||
QImage context = BrushRaster::context(side, side, false);
|
||||
QPainter painter(&context);
|
||||
BrushRaster::draw(painted.asset.image(), painted.bounds, painter);
|
||||
painter.end();
|
||||
image = context;
|
||||
} catch (const ProjectError &error) {
|
||||
qCWarning(lcRendering) << "the clone tip cannot be painted:" << error.what();
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "the clone tip cannot be painted:" << error.what();
|
||||
}
|
||||
m_cloneTip = CloneTip{diameter, hardness, image};
|
||||
return image;
|
||||
}
|
||||
|
||||
// The source around `center` at screen resolution, kept until changed.
|
||||
QImage CanvasView::clonePreview(QPointF center, double diameter, const CanvasDocument &document)
|
||||
{
|
||||
const double scale = m_session.viewport.pointsPerPixel() * m_session.viewport.backingScale;
|
||||
const ClonePreviewKey key{center, diameter, scale, m_session.brushRevision(), m_session.history.undoCount(),
|
||||
m_session.cloneSettings().sampleAllLayers, m_session.activeLayerID()};
|
||||
if (m_clonePreview && m_clonePreview->key == key)
|
||||
return m_clonePreview->image;
|
||||
const int side = std::min(1024, std::max(1, int(std::ceil(diameter * scale))));
|
||||
QImage image;
|
||||
try {
|
||||
QImage context = BrushRaster::context(side, side, false);
|
||||
QPainter painter(&context);
|
||||
const double perPixel = side / diameter;
|
||||
painter.scale(perPixel, perPixel);
|
||||
painter.translate(diameter / 2 - center.x(), diameter / 2 - center.y());
|
||||
// A painted asset flattens here; the catch covers it too.
|
||||
if (m_session.cloneSettings().sampleAllLayers) {
|
||||
m_session.drawLiveComposite(document, painter);
|
||||
} else if (const std::optional<ImageLayer> layer = m_session.activeLayer(); layer && layer->asset) {
|
||||
const LayerTransform transform = m_session.displayedTransform(*layer);
|
||||
LayerRenderer::draw(layer->asset->image(), transform, transform.center(), painter, {});
|
||||
}
|
||||
painter.end();
|
||||
image = context;
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "the clone preview cannot be drawn:" << error.what();
|
||||
}
|
||||
m_clonePreview = ClonePreview{key, image};
|
||||
return image;
|
||||
}
|
||||
|
||||
// Swift's brush keys: Tab, B, E, digits, brackets.
|
||||
bool CanvasView::brushKey(const QKeyEvent &key)
|
||||
{
|
||||
if (key.modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))
|
||||
return false;
|
||||
if (key.key() == Qt::Key_Tab && !key.modifiers().testFlag(Qt::ShiftModifier)) {
|
||||
m_session.cycleToolMode();
|
||||
updateCursor();
|
||||
updateBrushCursor();
|
||||
return true;
|
||||
}
|
||||
if (key.key() == Qt::Key_B || key.key() == Qt::Key_E) {
|
||||
m_session.selectTool(NavigationTool::brush);
|
||||
m_session.setBrushMode(key.key() == Qt::Key_E ? BrushToolMode::erase : BrushToolMode::paint);
|
||||
return true;
|
||||
}
|
||||
const QString text = key.text();
|
||||
if (text.size() == 1 && text.front().isDigit() && m_session.usesOpacityKeys()) {
|
||||
m_session.typeOpacityDigit(text.front().digitValue());
|
||||
return true;
|
||||
}
|
||||
return brushBracket(text);
|
||||
}
|
||||
|
||||
// Brackets: size, and hardness with Shift, for brushes.
|
||||
bool CanvasView::brushBracket(const QString &text)
|
||||
{
|
||||
if (!isBrushTool(m_session.tool()) || (text != u"[" && text != u"]" && text != u"{" && text != u"}"))
|
||||
return false;
|
||||
if (text == u"[" || text == u"]")
|
||||
m_session.changeBrushSize(text == u"]");
|
||||
else
|
||||
m_session.changeBrushHardness(text == u"}");
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include <QKeyEvent>
|
||||
#include <array>
|
||||
|
||||
namespace {
|
||||
// CGRect's contains: the far edges lie outside.
|
||||
bool contains(const QRectF &rect, QPointF point)
|
||||
{
|
||||
return point.x() >= rect.left() && point.x() < rect.right() && point.y() >= rect.top() && point.y() < rect.bottom();
|
||||
}
|
||||
|
||||
// Swift's frame positions, top left first, as Qt's shapes.
|
||||
Qt::CursorShape resizeShape(int index)
|
||||
{
|
||||
constexpr std::array<Qt::CursorShape, 8> shapes = {Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor, Qt::SizeHorCursor,
|
||||
Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor, Qt::SizeHorCursor};
|
||||
return shapes[size_t(index)];
|
||||
}
|
||||
}
|
||||
|
||||
// The grip under the pointer: the first region holding it.
|
||||
std::optional<int> CanvasView::cropRegion(QPointF point) const
|
||||
{
|
||||
for (const TransformOverlay::CropRegion ®ion : m_overlay.cropResizeRegions()) {
|
||||
if (contains(region.rect, point))
|
||||
return region.index;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
QCursor CanvasView::cropCursor(QPointF point) const
|
||||
{
|
||||
const std::optional<int> index = cropRegion(point);
|
||||
return index ? QCursor(resizeShape(*index)) : QCursor(Qt::CrossCursor);
|
||||
}
|
||||
|
||||
// A grip resizes, a drawn frame moves, elsewhere draws anew.
|
||||
void CanvasView::beginCropDrag(QPointF point)
|
||||
{
|
||||
const QSizeF size = m_session.document().value().size();
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, size);
|
||||
// Swift's current cursor: the old frame's, kept until the release.
|
||||
const QCursor cursor = cropCursor(point);
|
||||
// Swift's fallback is dead: the Crop tool has a frame.
|
||||
const QRectF rect = m_session.visibleCropRect().value();
|
||||
CropDrag::Mode mode{CropDrag::Kind::create};
|
||||
if (const std::optional<int> index = cropRegion(point))
|
||||
mode = {CropDrag::Kind::resize, *index};
|
||||
else if (m_session.cropRect() && contains(*m_session.cropRect(), pixel) && rect != QRectF(QPointF(0, 0), size))
|
||||
mode = {CropDrag::Kind::move};
|
||||
else
|
||||
m_session.setCropRect(std::nullopt);
|
||||
m_cropDrag = CropDrag{pixel, rect, mode};
|
||||
const SnapGuides targets = m_session.cropSnapTargets();
|
||||
m_cropSnap = CropSnap{targets.xs, targets.ys, cropSnapDistance / std::max(m_session.viewport.pointsPerPixel(), 0.0001)};
|
||||
m_dragCursor = cursor;
|
||||
updateCursor();
|
||||
}
|
||||
|
||||
// Without the left button the release was lost: drag ends.
|
||||
bool CanvasView::cropMove(QPointF point, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
if (!m_cropDrag)
|
||||
return false;
|
||||
if (!buttons.testFlag(Qt::LeftButton)) {
|
||||
endCropDrag();
|
||||
return false;
|
||||
}
|
||||
if (m_session.tool() != NavigationTool::crop || m_session.isProjectBusy() || !m_session.document())
|
||||
return false;
|
||||
dragCrop(point, modifiers);
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Alt keeps the middle still; Ctrl leaves the edges unsnapped.
|
||||
void CanvasView::dragCrop(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document().value().size());
|
||||
const bool symmetric = modifiers.testFlag(Qt::AltModifier);
|
||||
const std::optional<double> ratio = m_session.cropRatio();
|
||||
const CropDrag &drag = m_cropDrag.value();
|
||||
QRectF next = drag.updated(pixel, ratio, symmetric);
|
||||
if (!modifiers.testFlag(Qt::ControlModifier))
|
||||
next = m_cropSnap.value().apply(next, drag, pixel, ratio, symmetric);
|
||||
if (CropGeometry::valid(next))
|
||||
m_session.setCropRect(next);
|
||||
}
|
||||
|
||||
// Swift's cropDrag = nil: its didSet lets the cursor go.
|
||||
void CanvasView::endCropDrag()
|
||||
{
|
||||
if (!m_cropDrag)
|
||||
return;
|
||||
m_cropDrag.reset();
|
||||
m_dragCursor.reset();
|
||||
updateCursor();
|
||||
}
|
||||
|
||||
// Escape drops the frame; Return and Enter crop to it.
|
||||
bool CanvasView::cropKey(const QKeyEvent &key)
|
||||
{
|
||||
const bool enter = key.key() == Qt::Key_Return || key.key() == Qt::Key_Enter;
|
||||
if (m_session.tool() != NavigationTool::crop || !(enter || key.key() == Qt::Key_Escape))
|
||||
return false;
|
||||
endCropDrag();
|
||||
if (enter)
|
||||
m_session.commitCrop();
|
||||
else
|
||||
m_session.cancelCrop();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "Rendering/EyedropperIcon.h"
|
||||
#include <QApplication>
|
||||
#include <QKeyEvent>
|
||||
#include <QLineEdit>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
// A haloed magnifier with a plus or a minus.
|
||||
QCursor zoomCursor(bool out, double ratio)
|
||||
{
|
||||
QPixmap pixmap(QSize(24, 24) * ratio);
|
||||
pixmap.setDevicePixelRatio(ratio);
|
||||
pixmap.fill(Qt::transparent);
|
||||
const QRectF glyph(2, 2, 20, 20);
|
||||
// The lens sits toward the top left, as the symbol's.
|
||||
const QPointF center(glyph.left() + glyph.width() * 0.41, glyph.top() + glyph.height() * 0.40);
|
||||
const double radius = glyph.width() * 0.27;
|
||||
QPainterPath shape;
|
||||
shape.addEllipse(center, radius, radius);
|
||||
const QPointF grip = center + QPointF(radius, radius) * std::sqrt(0.5);
|
||||
shape.moveTo(grip);
|
||||
shape.lineTo(glyph.bottomRight() - QPointF(1, 1));
|
||||
shape.moveTo(center - QPointF(radius * 0.55, 0));
|
||||
shape.lineTo(center + QPointF(radius * 0.55, 0));
|
||||
if (!out) {
|
||||
shape.moveTo(center - QPointF(0, radius * 0.55));
|
||||
shape.lineTo(center + QPointF(0, radius * 0.55));
|
||||
}
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(Qt::white, 4, Qt::SolidLine, Qt::RoundCap));
|
||||
painter.drawPath(shape);
|
||||
painter.setPen(Qt::NoPen);
|
||||
painter.setBrush(Qt::white);
|
||||
painter.drawEllipse(center, radius, radius);
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(Qt::black, 1.6, Qt::SolidLine, Qt::RoundCap));
|
||||
painter.drawPath(shape);
|
||||
return QCursor(pixmap, 10, 10);
|
||||
}
|
||||
|
||||
QPixmap cursorPixmap(QSize size, double ratio)
|
||||
{
|
||||
QPixmap pixmap(size * ratio);
|
||||
pixmap.setDevicePixelRatio(ratio);
|
||||
pixmap.fill(Qt::transparent);
|
||||
return pixmap;
|
||||
}
|
||||
|
||||
// A black stroke over a white one, like the crosshair.
|
||||
void strokeHaloed(QPainter &painter, const QPainterPath &path, double width)
|
||||
{
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(Qt::white, width + 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(path);
|
||||
painter.setPen(QPen(Qt::black, width, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(path);
|
||||
}
|
||||
|
||||
// The crosshair: two 15-point lines through the hot spot.
|
||||
void drawCrosshair(QPainter &painter, QPointF hotSpot)
|
||||
{
|
||||
QPainterPath cross;
|
||||
cross.moveTo(hotSpot - QPointF(7.5, 0));
|
||||
cross.lineTo(hotSpot + QPointF(7.5, 0));
|
||||
cross.moveTo(hotSpot - QPointF(0, 7.5));
|
||||
cross.lineTo(hotSpot + QPointF(0, 7.5));
|
||||
strokeHaloed(painter, cross, 1.2);
|
||||
}
|
||||
|
||||
// A plus to add or a minus to subtract, beside.
|
||||
void drawBadge(QPainter &painter, QPointF center, SelectionMode mode)
|
||||
{
|
||||
if (mode == SelectionMode::replace)
|
||||
return;
|
||||
QPainterPath badge;
|
||||
badge.moveTo(center - QPointF(3, 0));
|
||||
badge.lineTo(center + QPointF(3, 0));
|
||||
if (mode == SelectionMode::add) {
|
||||
badge.moveTo(center - QPointF(0, 3));
|
||||
badge.lineTo(center + QPointF(0, 3));
|
||||
}
|
||||
strokeHaloed(painter, badge, 1.2);
|
||||
}
|
||||
|
||||
// An icon on its 18-unit grid fitted to `box`.
|
||||
void drawIcon(QPainter &painter, SelectionIcon icon, const QRectF &box, const QColor &colour)
|
||||
{
|
||||
painter.save();
|
||||
painter.translate(box.topLeft());
|
||||
painter.scale(box.width() / 18, box.height() / 18);
|
||||
painter.setPen(QPen(colour, 1.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
SelectionIcons::paint(painter, icon);
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
// Black over eight white offsets: the icon's outline.
|
||||
void drawHaloedIcon(QPainter &painter, SelectionIcon icon, const QRectF &box)
|
||||
{
|
||||
for (const QPointF offset : {QPointF(-1, 0), QPointF(1, 0), QPointF(0, -1), QPointF(0, 1), QPointF(-0.7, -0.7), QPointF(0.7, 0.7), QPointF(-0.7, 0.7), QPointF(0.7, -0.7)})
|
||||
drawIcon(painter, icon, box.translated(offset), Qt::white);
|
||||
drawIcon(painter, icon, box, Qt::black);
|
||||
}
|
||||
|
||||
// Scissors on an 11-point grid: handles below, blades crossed.
|
||||
QPainterPath scissorsPath(const QRectF &box)
|
||||
{
|
||||
const double unit = box.width() / 11;
|
||||
const auto at = [&](double x, double y) { return box.topLeft() + QPointF(x * unit, y * unit); };
|
||||
QPainterPath path;
|
||||
path.addEllipse(at(2.8, 8.4), 2 * unit, 2 * unit);
|
||||
path.addEllipse(at(8.2, 8.4), 2 * unit, 2 * unit);
|
||||
path.moveTo(at(3.9, 6.7));
|
||||
path.lineTo(at(8.8, 0.6));
|
||||
path.moveTo(at(7.1, 6.7));
|
||||
path.lineTo(at(2.2, 0.6));
|
||||
return path;
|
||||
}
|
||||
|
||||
// A dashed selection box, white under black, as Swift badges.
|
||||
void drawSelectionBox(QPainter &painter, const QRectF &box)
|
||||
{
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(Qt::white, 2.5));
|
||||
painter.drawRect(box);
|
||||
QPen dashed(Qt::black, 1);
|
||||
dashed.setCapStyle(Qt::FlatCap);
|
||||
dashed.setDashPattern({2, 1.5});
|
||||
painter.setPen(dashed);
|
||||
painter.drawRect(box);
|
||||
}
|
||||
}
|
||||
|
||||
QCursor CanvasView::moveSelectionCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(28, 32), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF tip(4, 3);
|
||||
const QPainterPath arrow = arrowPath().translated(tip);
|
||||
painter.setPen(QPen(Qt::white, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(arrow);
|
||||
painter.fillPath(arrow, Qt::black);
|
||||
drawSelectionBox(painter, QRectF(tip + QPointF(9.5, 13.5), QSizeF(8, 6)));
|
||||
return QCursor(pixmap, 4, 3);
|
||||
}
|
||||
|
||||
QCursor CanvasView::selectionCursor(SelectionIcon icon, SelectionMode mode, double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(44, 36), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF hotSpot(8, 8);
|
||||
drawCrosshair(painter, hotSpot);
|
||||
// The icon below right of the cross, then its badge.
|
||||
const QRectF box(hotSpot + QPointF(7, 7), QSizeF(12, 12));
|
||||
drawHaloedIcon(painter, icon, box);
|
||||
drawBadge(painter, QPointF(box.right() + 5, box.center().y()), mode);
|
||||
return QCursor(pixmap, int(hotSpot.x()), int(hotSpot.y()));
|
||||
}
|
||||
|
||||
// Swift's wand: sparkle at the hot spot, stick down right.
|
||||
QCursor CanvasView::wandCursor(SelectionMode mode, double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(34, 34), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF hotSpot(7, 7);
|
||||
QPainterPath stick(hotSpot + QPointF(6, 6));
|
||||
stick.lineTo(hotSpot + QPointF(20, 20));
|
||||
QPainterPath marks;
|
||||
for (const QPointF direction : {QPointF(0, -1), QPointF(0, 1), QPointF(-1, 0), QPointF(1, 0)}) {
|
||||
marks.moveTo(hotSpot + direction * 2.5);
|
||||
marks.lineTo(hotSpot + direction * 6);
|
||||
}
|
||||
if (mode != SelectionMode::replace) {
|
||||
const QPointF center = hotSpot + QPointF(17, 5);
|
||||
marks.moveTo(center - QPointF(3, 0));
|
||||
marks.lineTo(center + QPointF(3, 0));
|
||||
if (mode == SelectionMode::add) {
|
||||
marks.moveTo(center - QPointF(0, 3));
|
||||
marks.lineTo(center + QPointF(0, 3));
|
||||
}
|
||||
}
|
||||
// White outlines first, so neither covers the other's black.
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
for (const auto &[colour, stickWidth, markWidth] : {std::tuple(Qt::white, 5.0, 3.2), std::tuple(Qt::black, 2.4, 1.2)}) {
|
||||
painter.setPen(QPen(colour, stickWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(stick);
|
||||
painter.setPen(QPen(colour, markWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(marks);
|
||||
}
|
||||
return QCursor(pixmap, int(hotSpot.x()), int(hotSpot.y()));
|
||||
}
|
||||
|
||||
QCursor CanvasView::eyedropperCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(24, 24), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
// Swift's box: sixteen white offsets first, then black.
|
||||
const QRectF glyph(2, 2, 20, 20);
|
||||
const double scale = glyph.width() / 18;
|
||||
const auto draw = [&painter, &glyph, scale](QPointF offset, const QColor &colour) {
|
||||
painter.save();
|
||||
painter.translate(glyph.topLeft() + offset);
|
||||
painter.scale(scale, scale);
|
||||
painter.setPen(QPen(colour, 1.5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
EyedropperIcon::paint(painter);
|
||||
painter.restore();
|
||||
};
|
||||
for (int step = 0; step < 16; ++step)
|
||||
draw(QPointF(std::cos(step * M_PI / 8), std::sin(step * M_PI / 8)) * 1.25, Qt::white);
|
||||
draw(QPointF(), Qt::black);
|
||||
// The dropper's tip is the hot spot, as Swift's.
|
||||
const QPointF tip = glyph.topLeft() + EyedropperIcon::tip() * scale;
|
||||
return QCursor(pixmap, int(std::round(tip.x())), int(std::round(tip.y())));
|
||||
}
|
||||
|
||||
// Swift's arrow with the scissors symbol beside, haloed white.
|
||||
QCursor CanvasView::movePixelsCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(36, 36), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF tip(4, 3);
|
||||
const QPainterPath arrow = arrowPath().translated(tip);
|
||||
painter.setPen(QPen(Qt::white, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(arrow);
|
||||
painter.fillPath(arrow, Qt::black);
|
||||
strokeHaloed(painter, scissorsPath(QRectF(tip + QPointF(9, 12), QSizeF(11, 11))), 1.2);
|
||||
return QCursor(pixmap, 4, 3);
|
||||
}
|
||||
|
||||
// Ctrl-drag cuts and moves; with Alt it copies.
|
||||
QCursor CanvasView::pixelDragCursor(bool duplicate, double ratio)
|
||||
{
|
||||
return duplicate ? duplicateCursor(ratio) : movePixelsCursor(ratio);
|
||||
}
|
||||
|
||||
void CanvasView::updateCursor()
|
||||
{
|
||||
const NavigationTool tool = m_session.tool();
|
||||
// A transform, outline or pixel drag keeps its cursor.
|
||||
if (m_dragCursor)
|
||||
setCursor(*m_dragCursor);
|
||||
else if (m_selectionDragStart)
|
||||
setCursor(moveSelectionCursor(devicePixelRatio()));
|
||||
else if (m_pixelDragStart)
|
||||
setCursor(pixelDragCursor(m_session.pixelMove() && m_session.pixelMove()->duplicate, devicePixelRatio()));
|
||||
else if (m_lastDragPoint)
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
// Picking outranks Space and the tools, as Swift's cursor rects.
|
||||
else if (picking())
|
||||
setCursor(eyedropperCursor(devicePixelRatio()));
|
||||
else if (m_session.hueTargeting())
|
||||
setCursor(Qt::SizeHorCursor);
|
||||
else if (m_spaceHeld || tool == NavigationTool::hand)
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
else if (tool == NavigationTool::crop)
|
||||
setCursor(m_hover ? cropCursor(*m_hover) : QCursor(Qt::CrossCursor));
|
||||
else if (tool == NavigationTool::zoom)
|
||||
setCursor(zoomCursor(m_optionHeld, devicePixelRatio()));
|
||||
else if (tool == NavigationTool::type)
|
||||
setCursor(m_inlineTextEditor && m_hover ? m_inlineTextEditor->cursorAt(*m_hover).value_or(QCursor(Qt::IBeamCursor)) : QCursor(Qt::IBeamCursor));
|
||||
else if (tool == NavigationTool::move)
|
||||
setCursor(m_hover ? transformCursor(*m_hover, heldModifiers()) : QCursor(Qt::ArrowCursor));
|
||||
else if (isSelectionTool(tool))
|
||||
setCursor(lassoCursor(heldModifiers(), m_hover));
|
||||
// The circle, preview and crosshair stand in; Alt picks anew.
|
||||
else if (tool == NavigationTool::cloneStamp && m_session.cloneSource() && !m_optionHeld)
|
||||
setCursor(Qt::BlankCursor);
|
||||
else if (tool == NavigationTool::idle)
|
||||
setCursor(Qt::ArrowCursor);
|
||||
else
|
||||
setCursor(Qt::CrossCursor);
|
||||
}
|
||||
|
||||
Qt::KeyboardModifiers CanvasView::heldModifiers() const
|
||||
{
|
||||
return (m_optionHeld ? Qt::AltModifier : Qt::NoModifier) | (m_controlHeld ? Qt::ControlModifier : Qt::NoModifier)
|
||||
| (m_shiftHeld ? Qt::ShiftModifier : Qt::NoModifier);
|
||||
}
|
||||
|
||||
void CanvasView::readModifiers(Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
m_optionHeld = modifiers.testFlag(Qt::AltModifier);
|
||||
m_controlHeld = modifiers.testFlag(Qt::ControlModifier);
|
||||
m_shiftHeld = modifiers.testFlag(Qt::ShiftModifier);
|
||||
}
|
||||
|
||||
// Swift's monitors: the window's keys, and modifiers from anywhere.
|
||||
bool CanvasView::eventFilter(QObject *watched, QEvent *event)
|
||||
{
|
||||
if (event->type() != QEvent::KeyPress && event->type() != QEvent::KeyRelease)
|
||||
return false;
|
||||
const auto *key = static_cast<QKeyEvent *>(event);
|
||||
// Alt, Ctrl and Shift from any window, as Swift's monitor.
|
||||
if (key->key() == Qt::Key_Alt || key->key() == Qt::Key_Control || key->key() == Qt::Key_Shift) {
|
||||
if (!key->isAutoRepeat()) {
|
||||
(key->key() == Qt::Key_Alt ? m_optionHeld : key->key() == Qt::Key_Control ? m_controlHeld : m_shiftHeld) = event->type() == QEvent::KeyPress;
|
||||
modifiersChanged();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const auto *widget = qobject_cast<QWidget *>(watched);
|
||||
if (!widget || widget->window() != window())
|
||||
return false;
|
||||
// Shift-+ and Shift-− step the blend mode, except while typing.
|
||||
const bool typing = qobject_cast<QLineEdit *>(QApplication::focusWidget()) || (m_inlineTextEditor && hasFocus());
|
||||
if (event->type() != QEvent::KeyPress || typing || key->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))
|
||||
return false;
|
||||
const bool forward = key->key() == Qt::Key_Plus || key->key() == Qt::Key_Equal;
|
||||
if (key->modifiers().testFlag(Qt::ShiftModifier) && (forward || key->key() == Qt::Key_Underscore || key->key() == Qt::Key_Minus)) {
|
||||
m_session.cycleBlendMode(forward);
|
||||
return true;
|
||||
}
|
||||
// Brush brackets too; the canvas's own keys take its own.
|
||||
return QApplication::focusWidget() != this && !m_session.levels() && brushBracket(key->text());
|
||||
}
|
||||
|
||||
// A key changed: badge, box and cursor follow at once.
|
||||
void CanvasView::modifiersChanged()
|
||||
{
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (m_marqueeDragPixel && draft && (draft->kind == LassoKind::rectangle || draft->kind == LassoKind::ellipse))
|
||||
dragMarqueeDraft(*m_marqueeDragPixel, heldModifiers());
|
||||
// So does a crop drag, as Alt and Ctrl change.
|
||||
if (m_cropDrag && m_session.tool() == NavigationTool::crop && m_session.document())
|
||||
dragCrop(m_hover.value(), heldModifiers());
|
||||
// As Swift's monitor: Alt may start or end picking.
|
||||
synchronizeDisplay();
|
||||
m_session.updateHeldSelectionKeys(m_shiftHeld, m_optionHeld);
|
||||
updateCursor();
|
||||
updateBrushCursor();
|
||||
}
|
||||
|
||||
// The pointer arrow as a path, tip at the origin.
|
||||
QPainterPath CanvasView::arrowPath()
|
||||
{
|
||||
QPainterPath arrow(QPointF(0, 0));
|
||||
for (const QPointF point : {QPointF(0, 16.5), QPointF(3.9, 12.8), QPointF(6.6, 19), QPointF(9.2, 17.9), QPointF(6.6, 11.8), QPointF(11.8, 11.8)})
|
||||
arrow.lineTo(point);
|
||||
arrow.closeSubpath();
|
||||
return arrow;
|
||||
}
|
||||
|
||||
// Arrows back to front, each outlined under its fill.
|
||||
QCursor CanvasView::duplicateCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap(QSize(28, 32) * ratio);
|
||||
pixmap.setDevicePixelRatio(ratio);
|
||||
pixmap.fill(Qt::transparent);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF tip(4, 3);
|
||||
for (const auto &[offset, fill, outline] : {std::tuple(5.0, Qt::white, Qt::black), std::tuple(0.0, Qt::black, Qt::white)}) {
|
||||
const QPainterPath arrow = arrowPath().translated(tip + QPointF(offset, offset));
|
||||
painter.setPen(QPen(outline, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(arrow);
|
||||
painter.fillPath(arrow, fill);
|
||||
}
|
||||
return QCursor(pixmap, 4, 3);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#include "Document/LayerEffects+Renderer.h"
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include "Rendering/TiledLayerRenderer.h"
|
||||
|
||||
// Swift's effects surface: a painted layer keeps its effects on.
|
||||
|
||||
// A stroke previews as the finished layer will look (TiledLayerRenderer).
|
||||
void CanvasView::drawStroke(const BrushStroke &stroke, const ImageLayer &layer, const LayerTransform &transform, const std::optional<QImage> &mask,
|
||||
const LayerRenderer::Options &options, double scale, const Center ¢er, QPainter &target)
|
||||
{
|
||||
const std::optional<ImportedImage> &previous = stroke.layer.asset;
|
||||
const QImage image = previous && !previous->raster ? previous->image() : QImage();
|
||||
const std::shared_ptr<const RasterSnapshot> raster = previous ? previous->raster : nullptr;
|
||||
const LayerRenderer::Options bare{.scale = scale, .opacity = options.opacity, .blendMode = options.blendMode, .clip = options.clip};
|
||||
if (!stroke.isMask) {
|
||||
// The surface holds the wet pixels under their effects.
|
||||
if (LayerEffectsSurface *surface = strokeSurface(layer, stroke, mask); surface && surface->image()) {
|
||||
const LayerTransform grown = LayerEffectsRenderer::placed(transform, *surface->image(), surface->margin);
|
||||
surface->placement = grown;
|
||||
LayerRenderer::draw(*surface->image(), grown, center(grown.center()), target, bare);
|
||||
return;
|
||||
}
|
||||
if (const std::optional<EffectsPreviewCache::Result> effects = m_session.effectsPreviews.rendered(layer.id)) {
|
||||
const LayerTransform grown = effects->placement.value_or(LayerEffectsRenderer::placed(layer.transform, effects->image, effects->inset));
|
||||
LayerRenderer::draw(effects->image, grown, center(grown.center()), target, bare);
|
||||
}
|
||||
TiledLayerRenderer::drawStroke(stroke.width, stroke.height, stroke.sourceRect, stroke.patches(), image, raster, transform, center(transform.center()),
|
||||
target, options);
|
||||
return;
|
||||
}
|
||||
if (stroke.layer.mask && stroke.layer.mask->placement) {
|
||||
// A placed mask: the layer draws through its own grid.
|
||||
if (!layer.asset)
|
||||
return;
|
||||
LayerRenderer::Options through = options;
|
||||
through.mask = stroke.placedMaskPreview(*stroke.layer.mask->placement).value_or(QImage());
|
||||
if (layer.asset->raster)
|
||||
TiledLayerRenderer::drawRaster(layer.asset->raster, transform, center(transform.center()), target, through);
|
||||
else
|
||||
LayerRenderer::draw(layer.asset->image(), transform, center(transform.center()), target, through);
|
||||
return;
|
||||
}
|
||||
TiledLayerRenderer::drawMaskStroke(stroke.width, stroke.height, stroke.sourceRect, stroke.patches(),
|
||||
stroke.layer.mask ? std::optional(stroke.layer.mask->asset) : std::nullopt, image, raster, transform,
|
||||
center(transform.center()), target, bare);
|
||||
}
|
||||
|
||||
// Made as the stroke starts, updated as it goes.
|
||||
LayerEffectsSurface *CanvasView::strokeSurface(const ImageLayer &layer, const BrushStroke &stroke, const std::optional<QImage> &mask)
|
||||
{
|
||||
const LayerEffects effects = layer.effects.value_or(LayerEffects()).visible();
|
||||
if (effects.isEmpty() || !effects.isValid())
|
||||
return nullptr;
|
||||
const QSizeF grid(stroke.width, stroke.height);
|
||||
if (!m_strokeSurface || !m_strokeSurface->matches(layer.id, effects, grid, stroke.sourceRect))
|
||||
m_strokeSurface = LayerEffectsSurface::make(layer.id, effects, grid, stroke.sourceRect);
|
||||
if (!m_strokeSurface)
|
||||
return nullptr;
|
||||
m_strokeSurface->update(stroke.layer.asset, stroke.patches(), mask);
|
||||
return m_strokeSurface.get();
|
||||
}
|
||||
|
||||
// The surface shows until the new effects land: nothing blinks.
|
||||
void CanvasView::handOnStrokeSurface()
|
||||
{
|
||||
if (m_session.brushStroke() || !m_strokeSurface)
|
||||
return;
|
||||
if (m_strokeSurface->image() && m_strokeSurface->placement)
|
||||
m_session.effectsPreviews.seed(m_strokeSurface->layerID, *m_strokeSurface->image(), *m_strokeSurface->placement);
|
||||
m_strokeSurface.reset();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
|
||||
// Grabs a pending end, else starts a line there.
|
||||
void CanvasView::beginGradientDrag(QPointF point)
|
||||
{
|
||||
if (!m_session.document())
|
||||
return;
|
||||
if (const std::optional<std::pair<QPointF, QPointF>> line = m_overlay.gradientLine()) {
|
||||
if (std::hypot(point.x() - line->second.x(), point.y() - line->second.y()) <= 10) {
|
||||
m_gradientDrag = GradientHandle::end;
|
||||
return;
|
||||
}
|
||||
if (std::hypot(point.x() - line->first.x(), point.y() - line->first.y()) <= 10) {
|
||||
m_gradientDrag = GradientHandle::start;
|
||||
return;
|
||||
}
|
||||
}
|
||||
m_session.beginGradient(m_session.viewport.documentPoint(point, m_session.document()->size()));
|
||||
m_gradientDrag = m_session.gradientEdit() ? std::optional(GradientHandle::end) : std::nullopt;
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
bool CanvasView::dragGradient(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const std::optional<GradientEdit> &edit = m_session.gradientEdit();
|
||||
if (!m_gradientDrag || !edit || !m_session.document())
|
||||
return false;
|
||||
const bool start = *m_gradientDrag == GradientHandle::start;
|
||||
QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
if (modifiers.testFlag(Qt::ShiftModifier))
|
||||
pixel = snapped(pixel, start ? edit->end : edit->start);
|
||||
m_session.moveGradient(start ? std::optional(pixel) : std::nullopt, start ? std::nullopt : std::optional(pixel));
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
|
||||
QPointF CanvasView::snapped(QPointF point, QPointF anchor)
|
||||
{
|
||||
const double dx = point.x() - anchor.x(), dy = point.y() - anchor.y();
|
||||
const double length = std::hypot(dx, dy);
|
||||
const double angle = std::round(std::atan2(dy, dx) / (std::numbers::pi / 4)) * (std::numbers::pi / 4);
|
||||
return {anchor.x() + std::cos(angle) * length, anchor.y() + std::sin(angle) * length};
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "UI/FloatingPanel.h"
|
||||
#include <QApplication>
|
||||
#include <QKeyEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QNativeGestureEvent>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <QStyleHints>
|
||||
#include <QWheelEvent>
|
||||
#include <QWindow>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
bool isArrow(int key)
|
||||
{
|
||||
return key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down;
|
||||
}
|
||||
|
||||
std::optional<NavigationTool> toolForKey(int key)
|
||||
{
|
||||
switch (key) {
|
||||
case Qt::Key_B:
|
||||
case Qt::Key_E:
|
||||
return NavigationTool::brush;
|
||||
case Qt::Key_J:
|
||||
return NavigationTool::spotHealing;
|
||||
case Qt::Key_S:
|
||||
return NavigationTool::cloneStamp;
|
||||
case Qt::Key_T:
|
||||
return NavigationTool::type;
|
||||
case Qt::Key_G:
|
||||
return NavigationTool::gradient;
|
||||
case Qt::Key_U:
|
||||
return NavigationTool::shape;
|
||||
case Qt::Key_I:
|
||||
return NavigationTool::eyedropper;
|
||||
case Qt::Key_W:
|
||||
return NavigationTool::wand;
|
||||
case Qt::Key_A:
|
||||
return NavigationTool::idle;
|
||||
case Qt::Key_R:
|
||||
return NavigationTool::blur;
|
||||
case Qt::Key_C:
|
||||
return NavigationTool::crop;
|
||||
case Qt::Key_V:
|
||||
return NavigationTool::move;
|
||||
case Qt::Key_H:
|
||||
return NavigationTool::hand;
|
||||
case Qt::Key_Z:
|
||||
return NavigationTool::zoom;
|
||||
default:
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CanvasView::event(QEvent *event)
|
||||
{
|
||||
// Open text takes its editing keys ahead of the menus.
|
||||
if (event->type() == QEvent::ShortcutOverride && m_inlineTextEditor && InlineTextEditor::claims(*static_cast<QKeyEvent *>(event))) {
|
||||
event->accept();
|
||||
return true;
|
||||
}
|
||||
// A text view keeps Shift-Tab: the focus stays put.
|
||||
if (event->type() == QEvent::KeyPress && static_cast<QKeyEvent *>(event)->key() == Qt::Key_Backtab && m_inlineTextEditor)
|
||||
return true;
|
||||
// Tab cycles a tool's mode, as Swift's canvas takes it.
|
||||
if (event->type() == QEvent::KeyPress && static_cast<QKeyEvent *>(event)->key() == Qt::Key_Tab) {
|
||||
keyPressEvent(static_cast<QKeyEvent *>(event));
|
||||
return true;
|
||||
}
|
||||
if (event->type() == QEvent::NativeGesture) {
|
||||
const auto *gesture = static_cast<QNativeGestureEvent *>(event);
|
||||
// A pinch, as Swift's magnify; not mid-drag or mid-stroke.
|
||||
if (gesture->gestureType() == Qt::ZoomNativeGesture && !m_transformDrag && !m_cropDrag && !m_session.brushStroke() && !m_session.warpStroke()) {
|
||||
m_session.zoom(m_session.viewport.zoom() * (1 + gesture->value()), gesture->position());
|
||||
event->accept();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return QWidget::event(event);
|
||||
}
|
||||
|
||||
void CanvasView::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QWidget::resizeEvent(event);
|
||||
syncGeometry();
|
||||
}
|
||||
|
||||
void CanvasView::showEvent(QShowEvent *event)
|
||||
{
|
||||
QWidget::showEvent(event);
|
||||
syncGeometry();
|
||||
// The window's keys and Alt, as Swift's monitors watch them.
|
||||
qApp->installEventFilter(this);
|
||||
// Alt, Ctrl and Shift may be down already.
|
||||
readModifiers(QApplication::keyboardModifiers());
|
||||
updateCursor();
|
||||
// Another screen may scale differently, as Swift's backing changes.
|
||||
connect(window()->windowHandle(), &QWindow::screenChanged, this, &CanvasView::syncGeometry, Qt::UniqueConnection);
|
||||
// A mounted canvas takes keys; dialogs and pickers keep theirs.
|
||||
QMetaObject::invokeMethod(this, [this] {
|
||||
if (m_session.document() && !QApplication::activeModalWidget() && !m_session.showsNewDocument() && !m_session.showsImporter()
|
||||
&& !m_session.colorPicker())
|
||||
setFocus(Qt::OtherFocusReason);
|
||||
}, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void CanvasView::hideEvent(QHideEvent *event)
|
||||
{
|
||||
qApp->removeEventFilter(this);
|
||||
QWidget::hideEvent(event);
|
||||
}
|
||||
|
||||
void CanvasView::syncGeometry()
|
||||
{
|
||||
// After the layout pass, as Swift waits out SwiftUI's.
|
||||
QMetaObject::invokeMethod(this, [this] {
|
||||
const double scale = devicePixelRatio();
|
||||
const QSizeF bounds(size());
|
||||
if (m_session.viewport.viewSize == bounds && m_session.viewport.backingScale == scale)
|
||||
return;
|
||||
m_session.viewport.resize(bounds, scale, m_session.document() ? std::optional(m_session.document()->size()) : std::nullopt);
|
||||
update();
|
||||
m_session.notify();
|
||||
}, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void CanvasView::consumeFocusRequest(int request)
|
||||
{
|
||||
if (request == m_lastFocusRequest)
|
||||
return;
|
||||
m_lastFocusRequest = request;
|
||||
// An open draft leaves the keys where they are.
|
||||
QMetaObject::invokeMethod(this, [this] {
|
||||
if (!QApplication::activeModalWidget() && !m_session.textDraft())
|
||||
setFocus(Qt::OtherFocusReason);
|
||||
}, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void CanvasView::wheelEvent(QWheelEvent *event)
|
||||
{
|
||||
if (!m_session.document() || m_transformDrag || m_cropDrag || m_session.brushStroke() || m_session.warpStroke())
|
||||
return;
|
||||
// Trackpads report pixels; a wheel reports notches, lines each.
|
||||
const bool precise = !event->pixelDelta().isNull();
|
||||
const QPointF delta = precise ? QPointF(event->pixelDelta()) : QPointF(event->angleDelta()) / 120.0 * QApplication::wheelScrollLines();
|
||||
if (event->modifiers() & (Qt::ControlModifier | Qt::AltModifier)) {
|
||||
m_session.zoom(m_session.viewport.zoom() * std::exp(-delta.y() * 0.015), event->position());
|
||||
return;
|
||||
}
|
||||
const double multiplier = precise ? 1 : 12;
|
||||
m_session.viewport.translate(QSizeF(delta.x() * multiplier, delta.y() * multiplier));
|
||||
m_session.notify();
|
||||
}
|
||||
|
||||
void CanvasView::mousePressEvent(QMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::RightButton && isBrushTool(m_session.tool()) && !m_session.brushStroke() && !m_session.warpStroke() && !m_spaceHeld) {
|
||||
beginBrushTipDrag(event->position(), event->modifiers());
|
||||
return;
|
||||
}
|
||||
if (event->button() != Qt::LeftButton) {
|
||||
QWidget::mousePressEvent(event);
|
||||
return;
|
||||
}
|
||||
// Swift's mouseDown lets go of a chosen effect first.
|
||||
m_session.dropEffectSelection();
|
||||
readModifiers(event->modifiers());
|
||||
setFocus(Qt::MouseFocusReason);
|
||||
// A press starts afresh: Qt can lose a release.
|
||||
endSampling();
|
||||
if (!m_session.document() || m_session.isProjectBusy() || m_session.isImporting())
|
||||
return;
|
||||
const QPointF point = event->position();
|
||||
m_hover = point;
|
||||
// A Levels eyedropper sets its point; the panel keeps keys.
|
||||
if (m_session.levels() && m_session.levels()->sampleMode && !m_spaceHeld) {
|
||||
m_session.sampleLevels(m_session.viewport.documentPoint(point, m_session.document()->size()));
|
||||
FloatingPanel::refocus(QStringLiteral("levelsPanel"));
|
||||
return;
|
||||
}
|
||||
// Open Levels leaves the canvas to panning and zooming.
|
||||
if (m_session.levels() && !m_spaceHeld && m_session.tool() != NavigationTool::hand && m_session.tool() != NavigationTool::zoom)
|
||||
return;
|
||||
if (!m_spaceHeld && pickingPress(point))
|
||||
return;
|
||||
if (m_spaceHeld || m_session.tool() == NavigationTool::hand) {
|
||||
m_lastDragPoint = point;
|
||||
updateCursor();
|
||||
} else if (m_session.tool() == NavigationTool::move) {
|
||||
beginTransformDrag(point, event->modifiers());
|
||||
} else if (isSelectionTool(m_session.tool())) {
|
||||
lassoMouseDown(point, event->modifiers());
|
||||
updateCursor();
|
||||
} else if (m_session.tool() == NavigationTool::zoom) {
|
||||
m_zoomDrag = ZoomDrag{point, m_session.viewport.zoom(), false};
|
||||
} else if (isBrushTool(m_session.tool())) {
|
||||
brushMouseDown(point, event->modifiers());
|
||||
} else if (m_session.tool() == NavigationTool::gradient) {
|
||||
beginGradientDrag(point);
|
||||
} else if (m_session.tool() == NavigationTool::shape) {
|
||||
m_session.beginShape(m_session.viewport.documentPoint(point, m_session.document()->size()));
|
||||
} else if (m_session.tool() == NavigationTool::crop) {
|
||||
beginCropDrag(point);
|
||||
} else if (m_session.tool() == NavigationTool::type) {
|
||||
const bool triple = m_textDoubleClick.isValid() && m_textDoubleClick.elapsed() < QGuiApplication::styleHints()->mouseDoubleClickInterval()
|
||||
&& (point - m_textDoubleClickPoint).manhattanLength() < QGuiApplication::styleHints()->startDragDistance();
|
||||
m_textDoubleClick.invalidate();
|
||||
pressTextTool(point, event->modifiers(), triple ? 3 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
// A double click's second press closes a polygonal draft.
|
||||
void CanvasView::mouseDoubleClickEvent(QMouseEvent *event)
|
||||
{
|
||||
// The Type tool's second click selects a word.
|
||||
if (event->button() == Qt::LeftButton && m_session.tool() == NavigationTool::type && !m_spaceHeld && m_session.document()
|
||||
&& !m_session.isProjectBusy() && !m_session.isImporting() && !picking() && !m_session.hueTargeting()) {
|
||||
setFocus(Qt::MouseFocusReason);
|
||||
pressTextTool(event->position(), event->modifiers(), 2);
|
||||
m_textDoubleClick.start();
|
||||
m_textDoubleClickPoint = event->position();
|
||||
return;
|
||||
}
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (event->button() == Qt::LeftButton && isSelectionTool(m_session.tool()) && draft && draft->kind == LassoKind::polygonal
|
||||
&& !m_spaceHeld && !m_session.isProjectBusy() && !m_session.isImporting() && !picking() && !m_session.hueTargeting()) {
|
||||
m_session.finishLasso();
|
||||
synchronizeDisplay();
|
||||
updateCursor();
|
||||
return;
|
||||
}
|
||||
// Else, picking included, it is a press, as Swift's mouseDown.
|
||||
QWidget::mouseDoubleClickEvent(event);
|
||||
}
|
||||
|
||||
void CanvasView::mouseMoveEvent(QMouseEvent *event)
|
||||
{
|
||||
const QPointF point = event->position();
|
||||
m_hover = point;
|
||||
readModifiers(event->modifiers());
|
||||
// Without the left button a text gesture's release was lost.
|
||||
const bool held = event->buttons().testFlag(Qt::LeftButton);
|
||||
if (m_textBoxAnchor) {
|
||||
if (held)
|
||||
dragTextGesture(point);
|
||||
else
|
||||
endTextGesture();
|
||||
return;
|
||||
}
|
||||
if (m_inlineTextEditor && held && m_inlineTextEditor->drag(point))
|
||||
return;
|
||||
if (m_inlineTextEditor && !held)
|
||||
m_inlineTextEditor->release();
|
||||
if (pickingMove(point, event->buttons()) || targetingMove(point, event->buttons(), event->modifiers())
|
||||
|| cropMove(point, event->buttons(), event->modifiers()))
|
||||
return;
|
||||
if (m_transformDrag) {
|
||||
dragTransform(point, event->modifiers());
|
||||
return;
|
||||
}
|
||||
if (m_brushTipDrag) {
|
||||
dragBrushTip(point, event->modifiers());
|
||||
return;
|
||||
}
|
||||
if (!m_lastDragPoint && dragGradient(point, event->modifiers()))
|
||||
return;
|
||||
if (!m_lastDragPoint && brushMouseMove(point, event->modifiers(), event->buttons().testFlag(Qt::LeftButton)))
|
||||
return;
|
||||
// A pan with Space comes first, as Swift's lastDragPoint.
|
||||
if (!m_lastDragPoint && moveSelectionTool(point, event->modifiers()))
|
||||
return;
|
||||
if (m_session.shapeDraft() && m_session.document()) {
|
||||
// Alt has no other job here: it grows from centre.
|
||||
m_session.dragShape(m_session.viewport.documentPoint(point, m_session.document()->size()),
|
||||
event->modifiers().testFlag(Qt::ShiftModifier), event->modifiers().testFlag(Qt::AltModifier));
|
||||
synchronizeDisplay();
|
||||
return;
|
||||
}
|
||||
if (m_zoomDrag) {
|
||||
const double dx = point.x() - m_zoomDrag->start.x();
|
||||
if (std::abs(dx) >= 3)
|
||||
m_zoomDrag->moved = true;
|
||||
// Right zooms in, left out: doubling every 100 points.
|
||||
if (m_zoomDrag->moved)
|
||||
m_session.zoom(m_zoomDrag->zoom * std::pow(2, dx / 100), m_zoomDrag->start);
|
||||
return;
|
||||
}
|
||||
if (!m_lastDragPoint) {
|
||||
// Hover: the Move tool's cursor follows the handles.
|
||||
updateCursor();
|
||||
return;
|
||||
}
|
||||
m_session.viewport.translate(QSizeF(point.x() - m_lastDragPoint->x(), point.y() - m_lastDragPoint->y()));
|
||||
m_lastDragPoint = point;
|
||||
m_session.notify();
|
||||
}
|
||||
|
||||
void CanvasView::mouseReleaseEvent(QMouseEvent *event)
|
||||
{
|
||||
if (event->button() == Qt::RightButton && m_brushTipDrag) {
|
||||
endBrushTipDrag(event->position());
|
||||
return;
|
||||
}
|
||||
if (event->button() != Qt::LeftButton) {
|
||||
QWidget::mouseReleaseEvent(event);
|
||||
return;
|
||||
}
|
||||
if (m_textBoxAnchor) {
|
||||
finishTextGesture();
|
||||
return;
|
||||
}
|
||||
// Open text's press ends; the cursor follows below.
|
||||
if (m_inlineTextEditor)
|
||||
m_inlineTextEditor->release();
|
||||
if (m_zoomDrag) {
|
||||
const ZoomDrag drag = *m_zoomDrag;
|
||||
m_zoomDrag.reset();
|
||||
// A press that never moved zooms a step on release.
|
||||
if (!drag.moved)
|
||||
m_session.zoom(m_session.viewport.zoom() * (event->modifiers().testFlag(Qt::AltModifier) ? 0.5 : 2), drag.start);
|
||||
return;
|
||||
}
|
||||
m_session.snapGuides = {};
|
||||
pickingRelease();
|
||||
targetingRelease();
|
||||
brushMouseUp(event->position());
|
||||
if (m_gradientDrag) {
|
||||
m_gradientDrag.reset();
|
||||
m_session.endGradientDrag();
|
||||
}
|
||||
if (m_session.shapeDraft())
|
||||
m_session.finishShape();
|
||||
endCropDrag();
|
||||
if (m_transformDrag)
|
||||
endTransformDrag();
|
||||
releaseSelectionTool();
|
||||
m_lastDragPoint.reset();
|
||||
updateCursor();
|
||||
// A Ctrl+T edit commits nothing here: the guides still go.
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
void CanvasView::keyPressEvent(QKeyEvent *event)
|
||||
{
|
||||
// A drag swallows Alt's release: every key re-reads it.
|
||||
m_optionHeld = event->modifiers().testFlag(Qt::AltModifier) || event->key() == Qt::Key_Alt;
|
||||
m_controlHeld = event->modifiers().testFlag(Qt::ControlModifier) || event->key() == Qt::Key_Control;
|
||||
m_shiftHeld = event->modifiers().testFlag(Qt::ShiftModifier) || event->key() == Qt::Key_Shift;
|
||||
// Escape drops a text box being drawn, as Swift's first.
|
||||
if (event->key() == Qt::Key_Escape && m_textBoxAnchor) {
|
||||
endTextGesture();
|
||||
return;
|
||||
}
|
||||
// Open text is the text view: it takes every key.
|
||||
if (m_inlineTextEditor) {
|
||||
if (!m_inlineTextEditor->keyPress(*event))
|
||||
QWidget::keyPressEvent(event);
|
||||
return;
|
||||
}
|
||||
const bool plain = !(event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier));
|
||||
const bool enter = event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter;
|
||||
const std::optional<NavigationTool> tool = plain ? toolForKey(event->key()) : std::nullopt;
|
||||
const bool erase = event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete;
|
||||
if (erase && event->modifiers() == Qt::ShiftModifier) {
|
||||
// Shift-Delete: Content-Aware Fill, taken either way.
|
||||
if (m_session.canContentAwareFill())
|
||||
m_session.beginFilter(FilterKind::contentAwareFill);
|
||||
} else if (m_session.levels() && event->key() != Qt::Key_Space) {
|
||||
// Open Levels takes its keys and passes the rest on.
|
||||
if (event->key() == Qt::Key_Escape)
|
||||
m_session.cancelLevels();
|
||||
else if (enter)
|
||||
m_session.commitLevels();
|
||||
else if (event->key() == Qt::Key_P && event->modifiers().testFlag(Qt::AltModifier))
|
||||
m_session.updateLevels(m_session.levels()->settings, !m_session.levels()->preview);
|
||||
else
|
||||
QWidget::keyPressEvent(event);
|
||||
} else if (m_session.brushStroke() || m_session.warpStroke()) {
|
||||
// A stroke takes every key; Escape cancels it.
|
||||
if (event->key() == Qt::Key_Escape && !m_session.isProjectBusy()) {
|
||||
m_session.cancelBrush();
|
||||
synchronizeDisplay();
|
||||
}
|
||||
} else if (selectionKey(*event)) {
|
||||
return;
|
||||
} else if (event->key() == Qt::Key_Escape && m_session.shapeDraft()) {
|
||||
m_session.cancelShape();
|
||||
synchronizeDisplay();
|
||||
} else if ((event->key() == Qt::Key_Escape || enter) && m_session.gradientEdit()) {
|
||||
m_gradientDrag.reset();
|
||||
if (enter)
|
||||
m_session.commitGradient();
|
||||
else
|
||||
m_session.cancelGradient();
|
||||
} else if (cropKey(*event)) {
|
||||
return;
|
||||
} else if ((event->key() == Qt::Key_Escape || enter) && m_session.transformEdit()) {
|
||||
// The keys end a drag with its edit, cursor included.
|
||||
m_transformDrag.reset();
|
||||
m_dragCursor.reset();
|
||||
if (enter)
|
||||
m_session.commitTransform();
|
||||
else
|
||||
m_session.cancelTransform();
|
||||
updateCursor();
|
||||
} else if (isArrow(event->key()) && event->modifiers().testFlag(Qt::ControlModifier) && !(event->modifiers() & (Qt::AltModifier | Qt::MetaModifier))
|
||||
&& !m_session.lassoDraft() && m_session.selection() && !m_session.selection()->isEmpty()) {
|
||||
// Ctrl-arrow moves the selected pixels in any tool.
|
||||
const double step = event->modifiers().testFlag(Qt::ShiftModifier) ? 10 : 1;
|
||||
m_session.nudgePixels(event->key() == Qt::Key_Left ? -step : event->key() == Qt::Key_Right ? step : 0,
|
||||
event->key() == Qt::Key_Up ? -step : event->key() == Qt::Key_Down ? step : 0, [canvas = QPointer<CanvasView>(this)] {
|
||||
if (canvas)
|
||||
canvas->synchronizeDisplay();
|
||||
});
|
||||
} else if (m_session.tool() == NavigationTool::move && plain && isArrow(event->key())) {
|
||||
const double step = event->modifiers().testFlag(Qt::ShiftModifier) ? 10 : 1;
|
||||
m_session.nudgeLayer(event->key() == Qt::Key_Left ? -step : event->key() == Qt::Key_Right ? step : 0,
|
||||
event->key() == Qt::Key_Up ? -step : event->key() == Qt::Key_Down ? step : 0);
|
||||
} else if (erase && !(event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))) {
|
||||
m_session.deleteKeyPressed();
|
||||
} else if (event->key() == Qt::Key_Space) {
|
||||
m_spaceHeld = true;
|
||||
updateCursor();
|
||||
updateBrushCursor();
|
||||
} else if (brushKey(*event)) {
|
||||
return;
|
||||
} else if (plain && (event->key() == Qt::Key_X || event->key() == Qt::Key_D)) {
|
||||
// X swaps the palette; D brings back black and white.
|
||||
if (event->key() == Qt::Key_X)
|
||||
m_session.swapPaletteColors();
|
||||
else
|
||||
m_session.resetPaletteColors();
|
||||
} else if (tool == NavigationTool::shape && event->modifiers().testFlag(Qt::ShiftModifier) && m_session.tool() == NavigationTool::shape) {
|
||||
m_session.toggleShapeKind();
|
||||
} else if (tool) {
|
||||
m_session.selectTool(*tool);
|
||||
} else {
|
||||
QWidget::keyPressEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void CanvasView::keyReleaseEvent(QKeyEvent *event)
|
||||
{
|
||||
// Auto-repeat sends release and press pairs: not a release.
|
||||
if (event->isAutoRepeat()) {
|
||||
QWidget::keyReleaseEvent(event);
|
||||
} else if (event->key() == Qt::Key_Space) {
|
||||
m_spaceHeld = false;
|
||||
updateCursor();
|
||||
updateBrushCursor();
|
||||
} else {
|
||||
QWidget::keyReleaseEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void CanvasView::focusInEvent(QFocusEvent *event)
|
||||
{
|
||||
if (m_inlineTextEditor)
|
||||
m_inlineTextEditor->setFocused(true);
|
||||
QWidget::focusInEvent(event);
|
||||
}
|
||||
|
||||
void CanvasView::focusOutEvent(QFocusEvent *event)
|
||||
{
|
||||
if (m_inlineTextEditor) {
|
||||
m_inlineTextEditor->setFocused(false);
|
||||
m_inlineTextEditor->release();
|
||||
}
|
||||
// Qt can lose the release: box and sampling go.
|
||||
if (m_textBoxAnchor)
|
||||
endTextGesture();
|
||||
endSampling();
|
||||
// Swift's resignFirstResponder: a stroke cancels, the circle goes.
|
||||
if (!m_session.isProjectBusy())
|
||||
m_session.cancelBrush();
|
||||
m_brushPointer = std::nullopt;
|
||||
updateBrushCursor();
|
||||
cancelTransformDrag();
|
||||
endCropDrag();
|
||||
m_gradientDrag.reset();
|
||||
m_session.cancelShape();
|
||||
endSelectionGestures();
|
||||
m_spaceHeld = false;
|
||||
m_lastDragPoint.reset();
|
||||
updateCursor();
|
||||
QWidget::focusOutEvent(event);
|
||||
}
|
||||
|
||||
// Swift's mouseExited: the circle leaves with the pointer.
|
||||
void CanvasView::leaveEvent(QEvent *event)
|
||||
{
|
||||
m_brushPointer = std::nullopt;
|
||||
updateBrushCursor();
|
||||
QWidget::leaveEvent(event);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "UI/ColorPickerSheet.h"
|
||||
#include "UI/FloatingPanel.h"
|
||||
|
||||
// The Eyedropper, or Alt with Brush, Spot Healing, Gradient.
|
||||
bool CanvasView::palettePicking() const
|
||||
{
|
||||
const NavigationTool tool = m_session.tool();
|
||||
return tool == NavigationTool::eyedropper
|
||||
|| (m_optionHeld && (tool == NavigationTool::brush || tool == NavigationTool::spotHealing || tool == NavigationTool::gradient)
|
||||
&& !m_session.brushStroke() && !m_gradientDrag);
|
||||
}
|
||||
|
||||
bool CanvasView::picking() const
|
||||
{
|
||||
return palettePicking() || m_session.colorPicker() || m_session.hueSampleMode() || (m_session.levels() && m_session.levels()->sampleMode);
|
||||
}
|
||||
|
||||
// Picking or targeting begins or ends: a sampling goes.
|
||||
void CanvasView::syncPicking()
|
||||
{
|
||||
if (m_displayedPicking == picking() && m_displayedTargeting == m_session.hueTargeting())
|
||||
return;
|
||||
m_displayedPicking = picking();
|
||||
m_displayedTargeting = m_session.hueTargeting();
|
||||
endSampling();
|
||||
updateCursor();
|
||||
}
|
||||
|
||||
bool CanvasView::pickingPress(QPointF point)
|
||||
{
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
if (picking()) {
|
||||
// A colour, unless a range's eyedropper is armed.
|
||||
if (m_session.colorPicker() || (palettePicking() && !m_session.hueSampleMode())) {
|
||||
beginSampling(point);
|
||||
} else {
|
||||
m_session.sampleHueRange(pixel);
|
||||
FloatingPanel::refocus(QStringLiteral("adjustmentPanel"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!m_session.hueTargeting())
|
||||
return false;
|
||||
if (m_session.beginHueTargeting(pixel))
|
||||
m_hueTargetStart = point;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CanvasView::targetingMove(QPointF point, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
if (!m_hueTargetStart)
|
||||
return false;
|
||||
// Without the left button its release was lost.
|
||||
if (!buttons.testFlag(Qt::LeftButton)) {
|
||||
targetingRelease();
|
||||
return true;
|
||||
}
|
||||
m_session.dragHueTargeting(point.x() - m_hueTargetStart->x(), modifiers.testFlag(Qt::ControlModifier));
|
||||
// Every drag restores the cursor Alt may have changed.
|
||||
setCursor(Qt::SizeHorCursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
void CanvasView::targetingRelease()
|
||||
{
|
||||
if (!m_hueTargetStart)
|
||||
return;
|
||||
m_hueTargetStart.reset();
|
||||
m_session.endHueTargeting();
|
||||
}
|
||||
|
||||
void CanvasView::beginSampling(QPointF point)
|
||||
{
|
||||
// Alt may come with the press: take its change first.
|
||||
syncPicking();
|
||||
m_samplingOriginal = m_session.colorPicker() ? m_session.colorPicker()->color() : m_session.foregroundColor();
|
||||
m_samplingColor = true;
|
||||
sampleColor(point);
|
||||
}
|
||||
|
||||
// Swift's sampleColor: into the open picker, else the foreground.
|
||||
void CanvasView::sampleColor(QPointF point)
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!document)
|
||||
return;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, document->size());
|
||||
if (m_session.colorPicker()) {
|
||||
m_session.sampleIntoColorPicker(pixel);
|
||||
} else if (m_session.canEditPalette()) {
|
||||
if (const std::optional<PaletteColor> color = m_session.sampleCompositeColor(pixel))
|
||||
m_session.setForegroundColor(*color);
|
||||
}
|
||||
const PaletteColor sampled = m_session.colorPicker() ? m_session.colorPicker()->color() : m_session.foregroundColor();
|
||||
update(m_sampleRing.update(m_session.showsSampleRing() ? std::optional(point) : std::nullopt, m_samplingOriginal, sampled));
|
||||
}
|
||||
|
||||
void CanvasView::endSampling()
|
||||
{
|
||||
m_samplingColor = false;
|
||||
update(m_sampleRing.update(std::nullopt, m_samplingOriginal, m_sampleRing.sampled()));
|
||||
}
|
||||
|
||||
// A drag samples on; a buttonless hover shows the eyedropper.
|
||||
bool CanvasView::pickingMove(QPointF point, Qt::MouseButtons buttons)
|
||||
{
|
||||
syncPicking();
|
||||
if (m_samplingColor) {
|
||||
// Without the left button its release was lost.
|
||||
if (buttons.testFlag(Qt::LeftButton))
|
||||
sampleColor(point);
|
||||
else
|
||||
endSampling();
|
||||
return true;
|
||||
}
|
||||
if (buttons != Qt::NoButton || !picking())
|
||||
return false;
|
||||
updateCursor();
|
||||
return true;
|
||||
}
|
||||
|
||||
// The release ends sampling; the picker takes the keys back.
|
||||
void CanvasView::pickingRelease()
|
||||
{
|
||||
if (!m_samplingColor)
|
||||
return;
|
||||
endSampling();
|
||||
if (m_session.colorPicker())
|
||||
ColorPickerPanelController::refocus();
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "Logging.h"
|
||||
#include <QKeyEvent>
|
||||
#include <QPointer>
|
||||
#include <cmath>
|
||||
|
||||
// The Marquee and the Lasso on the canvas.
|
||||
namespace {
|
||||
bool isMarquee(const std::optional<LassoDraft> &draft)
|
||||
{
|
||||
return draft && (draft->kind == LassoKind::rectangle || draft->kind == LassoKind::ellipse);
|
||||
}
|
||||
}
|
||||
|
||||
// Over the selection in New mode, the move cursor.
|
||||
QCursor CanvasView::lassoCursor(Qt::KeyboardModifiers modifiers, std::optional<QPointF> location) const
|
||||
{
|
||||
const double ratio = devicePixelRatio();
|
||||
const SelectionMode mode = m_session.lassoCursorMode(modifiers.testFlag(Qt::ShiftModifier), modifiers.testFlag(Qt::AltModifier));
|
||||
// Ctrl over the selection: the scissors, or Ctrl-Alt's copy.
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
const bool command = modifiers.testFlag(Qt::ControlModifier);
|
||||
if ((command || mode == SelectionMode::replace) && document && location
|
||||
&& m_session.canMoveSelection(m_session.viewport.documentPoint(*location, document->size())))
|
||||
return command ? pixelDragCursor(modifiers.testFlag(Qt::AltModifier), ratio) : moveSelectionCursor(ratio);
|
||||
if (m_session.tool() == NavigationTool::wand)
|
||||
return wandCursor(mode, ratio);
|
||||
const SelectionIcon icon = m_session.tool() == NavigationTool::marquee
|
||||
? (m_session.marqueeKind() == LassoKind::ellipse ? SelectionIcon::ellipseMarquee : SelectionIcon::rectangleMarquee)
|
||||
: (m_session.lassoKind() == LassoKind::polygonal ? SelectionIcon::polygonalLasso : SelectionIcon::freehandLasso);
|
||||
return selectionCursor(icon, mode, ratio);
|
||||
}
|
||||
|
||||
// Freehand drags an outline; Polygonal adds a corner per click.
|
||||
void CanvasView::lassoMouseDown(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const QSizeF size = m_session.document().value().size();
|
||||
// Shift at the press means Add, never a square yet.
|
||||
m_marqueeConstrainArmed = !modifiers.testFlag(Qt::ShiftModifier);
|
||||
m_marqueeDragPixel = std::nullopt;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, size);
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (!draft || draft->kind != LassoKind::polygonal) {
|
||||
// Ctrl-drag inside the selection cuts and moves its pixels.
|
||||
if (modifiers.testFlag(Qt::ControlModifier) && m_session.canMoveSelection(pixel)) {
|
||||
if (m_session.beginPixelMove(modifiers.testFlag(Qt::AltModifier)))
|
||||
m_pixelDragStart = pixel;
|
||||
else
|
||||
qCWarning(lcApp) << "the selection holds no pixels to move";
|
||||
updateCursor();
|
||||
return;
|
||||
}
|
||||
const SelectionMode mode = m_session.selectionMode(modifiers.testFlag(Qt::ShiftModifier), modifiers.testFlag(Qt::AltModifier));
|
||||
if (mode == SelectionMode::replace && m_session.canMoveSelection(pixel) && m_session.beginSelectionMove()) {
|
||||
m_selectionDragStart = pixel;
|
||||
updateCursor();
|
||||
return;
|
||||
}
|
||||
if (m_session.tool() == NavigationTool::wand) {
|
||||
m_session.magicWand(pixel, mode);
|
||||
return;
|
||||
}
|
||||
m_session.beginLasso(pixel, mode);
|
||||
synchronizeDisplay();
|
||||
return;
|
||||
}
|
||||
// Near the first corner, with three, the outline closes.
|
||||
const QPointF first = m_session.viewport.viewPoint(draft->points.front(), size);
|
||||
if (draft->points.size() >= 3 && std::hypot(point.x() - first.x(), point.y() - first.y()) <= 8)
|
||||
m_session.finishLasso();
|
||||
else
|
||||
m_session.extendLasso(pixel);
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
// A drag or a hover; true when taken.
|
||||
bool CanvasView::moveSelectionTool(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
if (m_pixelDragStart && m_session.document()) {
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
m_session.movePixels(QSizeF(pixel.x() - m_pixelDragStart->x(), pixel.y() - m_pixelDragStart->y()));
|
||||
updateCursor();
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
if (m_selectionDragStart) {
|
||||
dragSelection(point, modifiers);
|
||||
updateMarqueeAutoscroll(point);
|
||||
updateCursor();
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (!isSelectionTool(m_session.tool()) || !m_session.document())
|
||||
return false;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
if (!draft || draft->kind == LassoKind::polygonal) {
|
||||
// Keys may have changed while the app was away.
|
||||
m_session.updateHeldSelectionKeys(modifiers.testFlag(Qt::ShiftModifier), modifiers.testFlag(Qt::AltModifier));
|
||||
updateCursor();
|
||||
if (draft)
|
||||
m_session.moveLassoCursor(pixel);
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
if (draft->kind == LassoKind::freehand) {
|
||||
m_session.extendLasso(pixel);
|
||||
} else {
|
||||
dragMarqueeDraft(pixel, modifiers);
|
||||
updateMarqueeAutoscroll(point);
|
||||
}
|
||||
synchronizeDisplay();
|
||||
return true;
|
||||
}
|
||||
|
||||
void CanvasView::releaseSelectionTool()
|
||||
{
|
||||
stopMarqueeAutoscroll();
|
||||
if (m_pixelDragStart) {
|
||||
m_pixelDragStart = std::nullopt;
|
||||
m_session.finishPixelMove([canvas = QPointer<CanvasView>(this)] {
|
||||
if (!canvas)
|
||||
return;
|
||||
canvas->synchronizeDisplay();
|
||||
canvas->updateCursor();
|
||||
});
|
||||
}
|
||||
if (m_selectionDragStart) {
|
||||
const QPointF start = *std::exchange(m_selectionDragStart, std::nullopt);
|
||||
const bool moved = m_session.selectionMoveOrigin() != m_session.selection();
|
||||
m_session.endSelectionMove();
|
||||
// The wand's click inside selects afresh; another's deselects.
|
||||
if (!moved && m_session.tool() == NavigationTool::wand)
|
||||
m_session.magicWand(start, SelectionMode::replace);
|
||||
else if (!moved)
|
||||
m_session.deselect();
|
||||
synchronizeDisplay();
|
||||
updateCursor();
|
||||
}
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (isSelectionTool(m_session.tool()) && draft && draft->kind != LassoKind::polygonal) {
|
||||
m_session.finishLasso();
|
||||
synchronizeDisplay();
|
||||
updateCursor();
|
||||
}
|
||||
}
|
||||
|
||||
// Escape, Return, Backspace and Delete on a draft; arrows nudge.
|
||||
bool CanvasView::selectionKey(const QKeyEvent &key)
|
||||
{
|
||||
const bool enter = key.key() == Qt::Key_Return || key.key() == Qt::Key_Enter;
|
||||
const bool plain = !(key.modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier));
|
||||
if (m_session.lassoDraft() && (key.key() == Qt::Key_Escape || enter || key.key() == Qt::Key_Backspace || key.key() == Qt::Key_Delete)) {
|
||||
if (key.key() == Qt::Key_Escape)
|
||||
m_session.cancelLasso();
|
||||
else if (enter)
|
||||
m_session.finishLasso();
|
||||
else
|
||||
m_session.removeLastLassoPoint();
|
||||
synchronizeDisplay();
|
||||
updateCursor();
|
||||
return true;
|
||||
}
|
||||
const std::optional<DocumentSelection> selection = m_session.selection();
|
||||
const bool arrow = key.key() == Qt::Key_Left || key.key() == Qt::Key_Right || key.key() == Qt::Key_Up || key.key() == Qt::Key_Down;
|
||||
if (isSelectionTool(m_session.tool()) && !m_session.lassoDraft() && selection && !selection->isEmpty() && arrow && plain) {
|
||||
const double step = key.modifiers().testFlag(Qt::ShiftModifier) ? 10 : 1;
|
||||
m_session.nudgeSelection(key.key() == Qt::Key_Left ? -step : key.key() == Qt::Key_Right ? step : 0,
|
||||
key.key() == Qt::Key_Up ? -step : key.key() == Qt::Key_Down ? step : 0);
|
||||
return true;
|
||||
}
|
||||
// M and L choose their tools; a repeat does nothing.
|
||||
if (plain && (key.key() == Qt::Key_M || key.key() == Qt::Key_L)) {
|
||||
if (key.isAutoRepeat())
|
||||
return true;
|
||||
if (key.key() == Qt::Key_M)
|
||||
m_session.pressMarqueeKey();
|
||||
else
|
||||
m_session.pressLassoKey();
|
||||
updateCursor();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Losing the keys ends a drag and an open outline.
|
||||
void CanvasView::endSelectionGestures()
|
||||
{
|
||||
stopMarqueeAutoscroll();
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (draft && draft->kind != LassoKind::polygonal)
|
||||
m_session.cancelLasso();
|
||||
if (m_selectionDragStart) {
|
||||
m_selectionDragStart = std::nullopt;
|
||||
m_session.endSelectionMove();
|
||||
}
|
||||
if (m_pixelDragStart) {
|
||||
m_pixelDragStart = std::nullopt;
|
||||
m_session.cancelPixelMove();
|
||||
}
|
||||
}
|
||||
|
||||
// The grabbed pixel follows the pointer; Shift keeps one axis.
|
||||
void CanvasView::dragSelection(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
if (!m_selectionDragStart || !m_session.document())
|
||||
return;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document()->size());
|
||||
QSizeF offset(pixel.x() - m_selectionDragStart->x(), pixel.y() - m_selectionDragStart->y());
|
||||
if (modifiers.testFlag(Qt::ShiftModifier)) {
|
||||
if (std::abs(offset.width()) >= std::abs(offset.height()))
|
||||
offset.setHeight(0);
|
||||
else
|
||||
offset.setWidth(0);
|
||||
}
|
||||
m_session.moveSelection(offset);
|
||||
}
|
||||
|
||||
// Alt subtracts, never from the centre; Shift squares once armed.
|
||||
void CanvasView::dragMarqueeDraft(QPointF pixel, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
if (!modifiers.testFlag(Qt::ShiftModifier))
|
||||
m_marqueeConstrainArmed = true;
|
||||
m_marqueeDragPixel = pixel;
|
||||
m_session.dragMarquee(pixel, m_marqueeConstrainArmed && modifiers.testFlag(Qt::ShiftModifier), false);
|
||||
}
|
||||
|
||||
// A frame's pan toward a pointer at the edge.
|
||||
QSizeF CanvasView::marqueeAutoscrollDelta(QPointF point) const
|
||||
{
|
||||
const QRectF bounds(QPointF(0, 0), QSizeF(size()));
|
||||
constexpr double margin = 12;
|
||||
const auto speed = [](double past) { return past <= 0 ? 0.0 : std::min(40.0, 2 + past * 0.4); };
|
||||
const double left = speed(bounds.left() + margin - point.x()), right = speed(point.x() - (bounds.right() - margin));
|
||||
const double top = speed(bounds.top() + margin - point.y()), bottom = speed(point.y() - (bounds.bottom() - margin));
|
||||
// Past the right edge the document slides left.
|
||||
return QSizeF(left - right, top - bottom);
|
||||
}
|
||||
|
||||
void CanvasView::updateMarqueeAutoscroll(QPointF point)
|
||||
{
|
||||
m_marqueeAutoscrollPoint = point;
|
||||
if (marqueeAutoscrollDelta(point) == QSizeF(0, 0)) {
|
||||
stopMarqueeAutoscroll();
|
||||
return;
|
||||
}
|
||||
if (!m_marqueeAutoscroll.isActive())
|
||||
m_marqueeAutoscroll.start();
|
||||
}
|
||||
|
||||
void CanvasView::stepMarqueeAutoscroll()
|
||||
{
|
||||
const bool marquee = isMarquee(m_session.lassoDraft());
|
||||
if (!m_marqueeAutoscrollPoint || !m_session.document() || !(marquee || m_selectionDragStart)) {
|
||||
stopMarqueeAutoscroll();
|
||||
return;
|
||||
}
|
||||
const QPointF point = *m_marqueeAutoscrollPoint;
|
||||
const QSizeF delta = marqueeAutoscrollDelta(point);
|
||||
if (delta == QSizeF(0, 0)) {
|
||||
stopMarqueeAutoscroll();
|
||||
return;
|
||||
}
|
||||
m_session.viewport.translate(delta);
|
||||
// The document moved under a still pointer: the box follows.
|
||||
if (m_selectionDragStart)
|
||||
dragSelection(point, heldModifiers());
|
||||
else
|
||||
dragMarqueeDraft(m_session.viewport.documentPoint(point, m_session.document()->size()), heldModifiers());
|
||||
m_session.notify();
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
void CanvasView::stopMarqueeAutoscroll()
|
||||
{
|
||||
m_marqueeAutoscroll.stop();
|
||||
m_marqueeAutoscrollPoint = std::nullopt;
|
||||
}
|
||||
|
||||
// Marching ants animate only while a visible selection exists.
|
||||
void CanvasView::updateAntsTimer()
|
||||
{
|
||||
const std::optional<DocumentSelection> selection = m_session.displayedSelection();
|
||||
const bool active = selection && !selection->isEmpty() && isVisible();
|
||||
if (active && !m_antsTimer.isActive())
|
||||
m_antsTimer.start();
|
||||
else if (!active && m_antsTimer.isActive())
|
||||
m_antsTimer.stop();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include <QPainterPath>
|
||||
#include <cmath>
|
||||
|
||||
void CanvasView::drawShapeDraft(double scale, const Center ¢er, QPainter &target, const QImage &clip) const
|
||||
{
|
||||
const std::optional<ShapeDraft> &draft = m_session.shapeDraft();
|
||||
// A flat or upright line has a box worth drawing.
|
||||
if (!draft || (draft->kind == ShapeKind::line ? draft->rect.width() <= 0 && draft->rect.height() <= 0 : draft->rect.isEmpty()))
|
||||
return;
|
||||
const QColor color = m_session.foregroundColor().color();
|
||||
const QPointF middle = center(draft->rect.center());
|
||||
const QRectF rect(middle.x() - draft->rect.width() * scale / 2, middle.y() - draft->rect.height() * scale / 2, draft->rect.width() * scale,
|
||||
draft->rect.height() * scale);
|
||||
std::function<void(QPainter &)> body;
|
||||
QRectF extent = rect;
|
||||
if (draft->kind == ShapeKind::line) {
|
||||
// A line's box is set only with its end.
|
||||
const std::pair<QPointF, QPointF> ends = m_session.shapeLineEnds().value();
|
||||
const double thickness = std::max(1.0, m_session.shapeLineWidth() * scale);
|
||||
// Exactly the two points dragged between, so the start holds.
|
||||
const QPointF from = center(ends.first), to = center(ends.second);
|
||||
extent = QRectF(from, to).normalized().adjusted(-thickness, -thickness, thickness, thickness);
|
||||
body = [color, thickness, from, to](QPainter &aside) { aside.fillPath(strokedLine(from, to, thickness), color); };
|
||||
} else {
|
||||
const QPainterPath shape = path(draft->kind, rect, draft->cornerRadius * scale);
|
||||
body = [color, shape](QPainter &aside) { aside.fillPath(shape, color); };
|
||||
}
|
||||
// Composed aside, so folder masks clip it as its layer.
|
||||
LayerRenderer::composite(target, QTransform(), extent, LayerSampling::smooth, InterpolationQuality::high, {.scale = scale, .clip = clip},
|
||||
extent, body);
|
||||
}
|
||||
|
||||
std::optional<CanvasView::ShapeShown> CanvasView::shownShape() const
|
||||
{
|
||||
const std::optional<ShapeDraft> &draft = m_session.shapeDraft();
|
||||
if (!draft)
|
||||
return std::nullopt;
|
||||
return ShapeShown{*draft, m_session.foregroundColor(), m_session.shapeLineWidth(), m_session.activeLayerID()};
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
|
||||
namespace {
|
||||
// Four arrows about `center`, each `reach` long, traced clockwise.
|
||||
QPainterPath fourArrowPath(QPointF center, double reach, double shaft, double head, double headLength)
|
||||
{
|
||||
const std::array<QPointF, 6> arm = {QPointF(-shaft, -reach + headLength), QPointF(-head, -reach + headLength), QPointF(0, -reach),
|
||||
QPointF(head, -reach + headLength), QPointF(shaft, -reach + headLength), QPointF(shaft, -shaft)};
|
||||
QPainterPath path;
|
||||
for (int turn = 0; turn < 4; ++turn) {
|
||||
for (QPointF point : arm) {
|
||||
for (int step = 0; step < turn; ++step)
|
||||
point = QPointF(-point.y(), point.x());
|
||||
const QPointF location = center + point;
|
||||
if (path.isEmpty())
|
||||
path.moveTo(location);
|
||||
else
|
||||
path.lineTo(location);
|
||||
}
|
||||
}
|
||||
path.closeSubpath();
|
||||
return path;
|
||||
}
|
||||
|
||||
QPixmap cursorPixmap(QSize size, double ratio)
|
||||
{
|
||||
QPixmap pixmap(size * ratio);
|
||||
pixmap.setDevicePixelRatio(ratio);
|
||||
pixmap.fill(Qt::transparent);
|
||||
return pixmap;
|
||||
}
|
||||
}
|
||||
|
||||
// Photoshop's Move pointer: the arrow with a four-way badge.
|
||||
QCursor CanvasView::moveCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(36, 36), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPointF tip(4, 3);
|
||||
const QPainterPath arrow = arrowPath().translated(tip);
|
||||
painter.setPen(QPen(Qt::white, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(arrow);
|
||||
painter.fillPath(arrow, Qt::black);
|
||||
// Heads narrow and apart: four distinct arrows at badge size.
|
||||
const QPainterPath badge = fourArrowPath(tip + QPointF(14.5, 17.5), 6.5, 0.75, 2, 2.5);
|
||||
painter.setPen(QPen(Qt::white, 1.6, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(badge);
|
||||
painter.fillPath(badge, Qt::black);
|
||||
return QCursor(pixmap, 4, 3);
|
||||
}
|
||||
|
||||
// The arrow in white: a Ctrl-drag moves the corner alone.
|
||||
QCursor CanvasView::distortCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(28, 32), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QPainterPath arrow = arrowPath().translated(QPointF(4, 3));
|
||||
painter.setPen(QPen(Qt::black, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(arrow);
|
||||
painter.fillPath(arrow, Qt::white);
|
||||
return QCursor(pixmap, 4, 3);
|
||||
}
|
||||
|
||||
// A pointing hand with Swift's dashed box beside it.
|
||||
QCursor CanvasView::loadSelectionCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(28, 32), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
QPainterPath hand;
|
||||
hand.setFillRule(Qt::WindingFill);
|
||||
hand.addRoundedRect(QRectF(8.5, 1.5, 4.5, 14), 2.2, 2.2);
|
||||
hand.addRoundedRect(QRectF(4.5, 11, 14.5, 12), 4, 4);
|
||||
painter.setPen(QPen(Qt::black, 2.2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(hand);
|
||||
painter.fillPath(hand, Qt::white);
|
||||
const QPointF tip(11, 2);
|
||||
const QRectF box(tip + QPointF(6.5, 16.5), QSizeF(8, 6));
|
||||
painter.setPen(QPen(Qt::white, 2.5));
|
||||
painter.drawRect(box);
|
||||
QPen dashed(Qt::black, 1);
|
||||
dashed.setCapStyle(Qt::FlatCap);
|
||||
dashed.setDashPattern({2, 1.5});
|
||||
painter.setPen(dashed);
|
||||
painter.drawRect(box);
|
||||
return QCursor(pixmap, int(tip.x()), int(tip.y()));
|
||||
}
|
||||
|
||||
// Two arrows chasing round a circle, haloed like the symbol.
|
||||
QCursor CanvasView::rotationCursor(double ratio)
|
||||
{
|
||||
QPixmap pixmap = cursorPixmap(QSize(24, 24), ratio);
|
||||
QPainter painter(&pixmap);
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
const QRectF ring(5, 5, 14, 14);
|
||||
QPainterPath shape;
|
||||
for (const double start : {20.0, 200.0}) {
|
||||
shape.arcMoveTo(ring, start);
|
||||
shape.arcTo(ring, start, 130);
|
||||
// The head at the arc's end, turned along it.
|
||||
const QPointF end = shape.currentPosition();
|
||||
const double tangent = (start + 130 + 90) * std::numbers::pi / 180;
|
||||
const QPointF along(std::cos(tangent), -std::sin(tangent));
|
||||
const QPointF across(-along.y(), along.x());
|
||||
shape.moveTo(end + across * 3 - along * 1.5);
|
||||
shape.lineTo(end + along * 2);
|
||||
shape.lineTo(end - across * 3 - along * 1.5);
|
||||
}
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(Qt::white, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(shape);
|
||||
painter.setPen(QPen(Qt::black, 1.6, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
|
||||
painter.drawPath(shape);
|
||||
return QCursor(pixmap, 12, 12);
|
||||
}
|
||||
|
||||
// The layer a press off the handles drags; Ctrl picks.
|
||||
std::optional<CanvasView::PressTarget> CanvasView::transformPressLayer(QPointF pixel, Qt::KeyboardModifiers modifiers) const
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!(m_session.canEditLayers() || m_session.transformEdit()) || !document)
|
||||
return std::nullopt;
|
||||
std::optional<QUuid> underPointer;
|
||||
const std::vector<ImageLayer> rendered = document->renderLayers();
|
||||
for (auto layer = rendered.rbegin(); layer != rendered.rend() && !underPointer; ++layer) {
|
||||
if (layer->asset && layer->transform.contains(pixel))
|
||||
underPointer = layer->id;
|
||||
}
|
||||
std::optional<ImageLayer> active = m_session.activeLayer();
|
||||
if (active && !(active->asset && !active->isGroup && document->effectiveVisibleIDs().contains(active->id)))
|
||||
active = std::nullopt;
|
||||
const bool picks = !m_session.transformEdit();
|
||||
const bool control = modifiers.testFlag(Qt::ControlModifier);
|
||||
if (control && picks && underPointer)
|
||||
return PressTarget{*underPointer, true};
|
||||
// A group's box drags them all; outside, unless auto-select picks.
|
||||
if (m_session.transformsAsGroup() && m_session.activeLayerID()) {
|
||||
const std::optional<LayerTransform> box = m_session.transformEdit() ? std::optional(m_session.transformEdit()->draft) : m_session.groupTransformBox();
|
||||
if ((box && box->contains(pixel)) || !(picks && m_session.transformAutoSelect()) || !underPointer)
|
||||
return PressTarget{*m_session.activeLayerID(), false};
|
||||
}
|
||||
if (active && m_session.editedTransform(*active).contains(pixel))
|
||||
return PressTarget{active->id, false};
|
||||
if (picks && (m_session.transformAutoSelect() || control) && underPointer)
|
||||
return PressTarget{*underPointer, true};
|
||||
if (active)
|
||||
return PressTarget{active->id, false};
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool CanvasView::pressMovesLayer(QPointF point, Qt::KeyboardModifiers modifiers) const
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
return document && transformPressLayer(m_session.viewport.documentPoint(point, document->size()), modifiers).has_value();
|
||||
}
|
||||
|
||||
// The Move tool's cursor; Alt offers a copy.
|
||||
QCursor CanvasView::transformCursor(QPointF point, Qt::KeyboardModifiers modifiers) const
|
||||
{
|
||||
if (m_dragCursor)
|
||||
return *m_dragCursor;
|
||||
if (m_spaceHeld)
|
||||
return QCursor(Qt::OpenHandCursor);
|
||||
if (m_session.isProjectBusy() || m_session.isImporting())
|
||||
return QCursor(Qt::ArrowCursor);
|
||||
const bool duplicate = modifiers.testFlag(Qt::AltModifier);
|
||||
const double ratio = devicePixelRatio();
|
||||
const std::optional<TransformOverlayGeometry> geometry = m_overlay.geometry();
|
||||
const std::optional<TransformDrag::Mode> hit = geometry ? geometry->hit(point) : std::nullopt;
|
||||
if (!hit) {
|
||||
if (!pressMovesLayer(point, modifiers))
|
||||
return QCursor(Qt::ArrowCursor);
|
||||
return duplicate ? duplicateCursor(ratio) : moveCursor(ratio);
|
||||
}
|
||||
if (hit->kind == TransformDrag::Kind::rotate)
|
||||
return rotationCursor(ratio);
|
||||
// Distorting (Ctrl held, or already distorted) moves corners freely.
|
||||
const std::optional<TransformEdit> &edit = m_session.transformEdit();
|
||||
const bool distorting = (edit && edit->corners) || modifiers.testFlag(Qt::ControlModifier);
|
||||
return distorting ? distortCursor(ratio) : QCursor(geometry->resizeCursor(hit->index));
|
||||
}
|
||||
|
||||
void CanvasView::beginTransformDrag(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!(m_session.canEditLayers() || m_session.transformEdit()) || !document)
|
||||
return;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, document->size());
|
||||
const std::optional<TransformOverlayGeometry> geometry = m_overlay.geometry();
|
||||
std::optional<TransformDrag::Mode> mode = geometry ? geometry->hit(point) : std::nullopt;
|
||||
if (!mode) {
|
||||
const std::optional<PressTarget> target = transformPressLayer(pixel, modifiers);
|
||||
if (!target)
|
||||
return;
|
||||
// Ctrl+Shift adds the picked layer; Ctrl alone selects it.
|
||||
if (target->picked && modifiers.testFlag(Qt::ControlModifier) && modifiers.testFlag(Qt::ShiftModifier))
|
||||
m_session.extendSelection(target->id);
|
||||
else if (target->picked)
|
||||
m_session.selectLayer(target->id);
|
||||
mode = TransformDrag::Mode{TransformDrag::Kind::move};
|
||||
}
|
||||
m_duplicatesTransformOnDrag = mode->kind == TransformDrag::Kind::move && modifiers.testFlag(Qt::AltModifier);
|
||||
if (!m_session.transformEdit())
|
||||
m_session.beginTransform(false);
|
||||
if (!m_session.transformEdit())
|
||||
return;
|
||||
// Ctrl-dragging a handle distorts; once distorted, handles keep distorting.
|
||||
if (mode->kind == TransformDrag::Kind::resize && (modifiers.testFlag(Qt::ControlModifier) || m_session.transformEdit()->corners)) {
|
||||
m_session.beginDistort();
|
||||
if (m_session.transformEdit()->corners)
|
||||
mode = TransformDrag::Mode{TransformDrag::Kind::distort, mode->index};
|
||||
}
|
||||
m_transformDrag = TransformDrag{m_session.transformEdit()->draft, pixel, *mode, m_session.transformEdit()->corners};
|
||||
const double ratio = devicePixelRatio();
|
||||
if (mode->kind == TransformDrag::Kind::resize)
|
||||
m_dragCursor = QCursor(geometry->resizeCursor(mode->index));
|
||||
else if (mode->kind == TransformDrag::Kind::rotate)
|
||||
m_dragCursor = rotationCursor(ratio);
|
||||
else if (mode->kind == TransformDrag::Kind::distort)
|
||||
m_dragCursor = distortCursor(ratio);
|
||||
else
|
||||
m_dragCursor = m_duplicatesTransformOnDrag ? duplicateCursor(ratio) : moveCursor(ratio);
|
||||
updateCursor();
|
||||
}
|
||||
|
||||
void CanvasView::dragTransform(QPointF point, Qt::KeyboardModifiers modifiers)
|
||||
{
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document().value().size());
|
||||
if (m_duplicatesTransformOnDrag) {
|
||||
m_duplicatesTransformOnDrag = false;
|
||||
m_session.beginDuplicateTransform();
|
||||
}
|
||||
if (const std::optional<Corners> corners = m_transformDrag->corners(pixel, modifiers.testFlag(Qt::ShiftModifier))) {
|
||||
m_session.previewCorners(*corners);
|
||||
synchronizeDisplay();
|
||||
return;
|
||||
}
|
||||
// Drags land on whole pixels and degrees; typing stays exact.
|
||||
LayerTransform draft = m_transformDrag->updated(pixel, m_session.locksTransformRatio(), modifiers.testFlag(Qt::ShiftModifier),
|
||||
modifiers.testFlag(Qt::AltModifier)).rounded();
|
||||
const std::optional<TransformEdit> &edit = m_session.transformEdit();
|
||||
// A move snaps to canvas and layers; Ctrl frees it.
|
||||
if (m_transformDrag->mode.kind == TransformDrag::Kind::move && !modifiers.testFlag(Qt::ControlModifier) && edit) {
|
||||
QSet<QUuid> moving;
|
||||
if (edit->group) {
|
||||
for (auto original = edit->group->originals.constBegin(); original != edit->group->originals.constEnd(); ++original)
|
||||
moving.insert(original.key());
|
||||
} else {
|
||||
moving.insert(edit->layerID);
|
||||
}
|
||||
draft = m_session.snappedMove(draft, moving, TransformSnap::distance / std::max(m_session.viewport.pointsPerPixel(), 0.0001));
|
||||
}
|
||||
m_session.previewTransform(draft);
|
||||
synchronizeDisplay();
|
||||
}
|
||||
|
||||
// The release: a drag's edit commits, Ctrl+T's waits.
|
||||
void CanvasView::endTransformDrag()
|
||||
{
|
||||
m_duplicatesTransformOnDrag = false;
|
||||
m_transformDrag.reset();
|
||||
m_dragCursor.reset();
|
||||
if (m_session.transformEdit() && !m_session.transformEdit()->persistent)
|
||||
m_session.commitTransform();
|
||||
updateCursor();
|
||||
}
|
||||
|
||||
// Losing the keys mid-drag puts the layer back.
|
||||
void CanvasView::cancelTransformDrag()
|
||||
{
|
||||
if (!m_transformDrag)
|
||||
return;
|
||||
m_duplicatesTransformOnDrag = false;
|
||||
m_session.previewTransform(m_transformDrag->original);
|
||||
if (m_session.transformEdit() && !m_session.transformEdit()->persistent)
|
||||
m_session.cancelTransform();
|
||||
m_transformDrag.reset();
|
||||
m_dragCursor.reset();
|
||||
updateCursor();
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "Document/LayerEffects+Renderer.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "Logging.h"
|
||||
#include "Rendering/AdjustmentSurface.h"
|
||||
#include "Rendering/DownsampleCache.h"
|
||||
#include "Rendering/LayerRenderer.h"
|
||||
#include "Rendering/LiveMaskRenderer.h"
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include "Rendering/TiledLayerRenderer.h"
|
||||
#include <QPaintEvent>
|
||||
#include <QPointer>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
// Swift's shadow: 35% black, blurred over fourteen points.
|
||||
void drawShadow(const QRectF &rect, QPainter &context)
|
||||
{
|
||||
constexpr int blur = 14;
|
||||
const QRectF shadow = rect.translated(0, 3);
|
||||
// Fourteen rings stack to 35% at the edge, fading out.
|
||||
const double ring = 1 - std::pow(0.65, 1.0 / blur);
|
||||
context.save();
|
||||
context.setPen(Qt::NoPen);
|
||||
context.setBrush(QColor::fromRgbF(0, 0, 0, ring));
|
||||
for (int step = blur; step >= 1; --step)
|
||||
context.drawRect(shadow.adjusted(-step, -step, step, step));
|
||||
context.restore();
|
||||
}
|
||||
|
||||
std::optional<ImageIdentity> enabledMaskID(const std::optional<LayerMask> &mask)
|
||||
{
|
||||
return mask && mask->isEnabled ? std::optional(mask->asset.identity()) : std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
CanvasView::CanvasView(EditorSession &session, QWidget *parent)
|
||||
: QWidget(parent), m_session(session), m_overlay(session), m_marqueeAutoscroll(this), m_antsTimer(this)
|
||||
{
|
||||
setObjectName(QStringLiteral("editorCanvas"));
|
||||
setAccessibleName(QStringLiteral("Canvas"));
|
||||
setFocusPolicy(Qt::StrongFocus);
|
||||
setAttribute(Qt::WA_OpaquePaintEvent);
|
||||
// The Move tool's cursor follows the pointer between presses.
|
||||
setMouseTracking(true);
|
||||
// Sixty frames a second, as Swift's; named for tests.
|
||||
m_marqueeAutoscroll.setObjectName(QStringLiteral("marqueeAutoscroll"));
|
||||
m_marqueeAutoscroll.setInterval(16);
|
||||
connect(&m_marqueeAutoscroll, &QTimer::timeout, this, &CanvasView::stepMarqueeAutoscroll);
|
||||
m_antsTimer.setObjectName(QStringLiteral("antsTimer"));
|
||||
m_antsTimer.setInterval(120);
|
||||
connect(&m_antsTimer, &QTimer::timeout, this, [this] {
|
||||
m_overlay.antsPhase = std::fmod(m_overlay.antsPhase + 1, 8.0);
|
||||
update(m_overlay.selectionRect(rect()));
|
||||
});
|
||||
}
|
||||
|
||||
CanvasView::DisplayState CanvasView::displayState() const
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
const std::optional<TransformEdit> &edit = m_session.transformEdit();
|
||||
DisplayState state{.brushRevision = m_session.brushRevision(),
|
||||
.pixelGrid = m_session.showsPixelGrid(),
|
||||
.corners = edit ? edit->corners : std::nullopt,
|
||||
.documentID = document ? std::optional(document->id) : std::nullopt,
|
||||
.size = document ? std::optional(document->size()) : std::nullopt,
|
||||
.renderBounds = renderBounds(),
|
||||
.viewport = m_session.viewport,
|
||||
.layers = {},
|
||||
.folderMasks = {}};
|
||||
if (!document)
|
||||
return state;
|
||||
// A hidden source still clips: live masks count every layer.
|
||||
const bool liveMasks = std::any_of(document->layers.begin(), document->layers.end(),
|
||||
[](const ImageLayer &layer) { return layer.maskSourceID.has_value(); });
|
||||
const std::vector<ImageLayer> rendered = liveMasks ? std::vector<ImageLayer>() : document->renderLayers();
|
||||
const QSet<QUuid> visible = document->effectiveVisibleIDs();
|
||||
for (const ImageLayer &layer : liveMasks ? document->layers : rendered) {
|
||||
// A blank layer counts while a draft sits on it.
|
||||
if (!layer.asset && !layer.adjustment && !(m_session.shapeDraft() && layer.id == m_session.activeLayerID()))
|
||||
continue;
|
||||
state.layers.push_back({.id = layer.id, .transform = m_session.displayedTransform(layer),
|
||||
.imageID = layer.asset ? std::optional(layer.asset->identity()) : std::nullopt,
|
||||
.maskID = enabledMaskID(layer.mask), .maskSourceID = layer.maskSourceID, .parentID = layer.parentID,
|
||||
.visible = visible.contains(layer.id), .opacity = layer.opacity,
|
||||
.blendMode = m_session.displayedBlendMode(layer), .maskPlacement = m_session.displayedMaskPlacement(layer),
|
||||
.adjustment = layer.adjustment, .effects = layer.effects});
|
||||
}
|
||||
for (const ImageLayer &layer : document->layers) {
|
||||
if (layer.isGroup && layer.mask)
|
||||
state.folderMasks.push_back({.id = layer.id, .maskID = enabledMaskID(layer.mask), .transform = m_session.displayedTransform(layer)});
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
// The stroke's dirty rect in view points, two points out.
|
||||
std::optional<QRectF> CanvasView::strokeDirtyRect() const
|
||||
{
|
||||
const BrushStroke *stroke = m_session.brushStroke();
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!stroke || !document || !stroke->dirtyDocumentRect())
|
||||
return std::nullopt;
|
||||
const QRectF &dirty = *stroke->dirtyDocumentRect();
|
||||
const QPointF origin = m_session.viewport.viewPoint(dirty.topLeft(), document->size());
|
||||
const double scale = m_session.viewport.pointsPerPixel();
|
||||
return QRectF(origin, QSizeF(dirty.width() * scale, dirty.height() * scale)).adjusted(-2, -2, 2, 2);
|
||||
}
|
||||
|
||||
bool CanvasView::synchronizeDisplay()
|
||||
{
|
||||
handOnStrokeSurface();
|
||||
synchronizeInlineText();
|
||||
// A text box being drawn goes with its tool.
|
||||
if (m_session.tool() != NavigationTool::type && m_textBoxRect)
|
||||
endTextGesture();
|
||||
const DisplayState state = displayState();
|
||||
bool changed = false;
|
||||
// Where the overlay draws now; a pan moves it.
|
||||
const QRect drawn = m_overlay.drawnRect(rect());
|
||||
if (m_displayedState != state) {
|
||||
// A stroke's step alone repaints where the stroke went.
|
||||
DisplayState still = state;
|
||||
still.brushRevision = m_displayedState ? m_displayedState->brushRevision : state.brushRevision;
|
||||
const std::optional<QRectF> dirty = strokeDirtyRect();
|
||||
if (m_displayedState && still == *m_displayedState && dirty)
|
||||
update(dirty->toAlignedRect());
|
||||
else
|
||||
update();
|
||||
m_displayedState = state;
|
||||
m_overlayRect = drawn;
|
||||
changed = true;
|
||||
}
|
||||
// The handles and guides repaint only where they draw.
|
||||
const std::optional<TransformOverlayGeometry> geometry = m_overlay.geometry();
|
||||
const bool blocked = m_session.isProjectBusy() || m_session.isImporting();
|
||||
const std::optional<DocumentSelection> outline = m_session.displayedSelection();
|
||||
const SelectionCursorState cursorState{m_session.marqueeKind(), m_session.lassoKind(), m_session.displayedSelectionMode()};
|
||||
const std::optional<QRectF> crop = m_overlay.cropViewRect();
|
||||
if (m_displayedGeometry != geometry || m_displayedGuides != m_session.snapGuides || m_displayedOutline != outline
|
||||
|| m_displayedDraft != m_session.lassoDraft() || m_displayedCrop != crop) {
|
||||
// Crop dimming spans the canvas: it comes and goes whole.
|
||||
if (m_displayedCrop.has_value() != crop.has_value())
|
||||
update();
|
||||
else
|
||||
update(QRegion(m_overlayRect) | QRegion(drawn));
|
||||
m_displayedCrop = crop;
|
||||
m_displayedGeometry = geometry;
|
||||
m_displayedGuides = m_session.snapGuides;
|
||||
m_displayedOutline = outline;
|
||||
m_displayedDraft = m_session.lassoDraft();
|
||||
m_overlayRect = drawn;
|
||||
updateCursor();
|
||||
} else if (m_displayedTool != m_session.tool() || m_displayedBlocked != blocked || m_displayedSelectionCursor != cursorState) {
|
||||
updateCursor();
|
||||
}
|
||||
// A shape draft redraws the view, as Swift's observation does.
|
||||
if (const std::optional<ShapeShown> shape = shownShape(); m_displayedShape != shape) {
|
||||
update();
|
||||
m_displayedShape = shape;
|
||||
}
|
||||
syncPicking();
|
||||
m_displayedTool = m_session.tool();
|
||||
m_displayedBlocked = blocked;
|
||||
m_displayedSelectionCursor = cursorState;
|
||||
updateBrushCursor();
|
||||
updateAntsTimer();
|
||||
return changed;
|
||||
}
|
||||
|
||||
// Crop shows what a frame past the canvas takes in.
|
||||
std::optional<QRectF> CanvasView::renderBounds() const
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!document)
|
||||
return std::nullopt;
|
||||
const QRectF original(QPointF(0, 0), document->size());
|
||||
// Swift's tool test is dead: frames live under Crop alone.
|
||||
return m_session.cropRect() ? original.united(*m_session.cropRect()) : original;
|
||||
}
|
||||
|
||||
void CanvasView::paintEvent(QPaintEvent *event)
|
||||
{
|
||||
// The dirty rect, image-backed: hand blends and coverage read pixels.
|
||||
QPainter painter(this);
|
||||
painter.setClipRect(event->rect());
|
||||
AdjustmentSurface::draw(painter, [&](QPainter &surface) { draw(surface, QRectF(event->rect())); });
|
||||
// Swift's overlay view: handles and guides over the pixels.
|
||||
m_overlay.draw(painter, palette());
|
||||
// Swift's stack: the ring over the overlays, the editor above.
|
||||
m_sampleRing.draw(painter);
|
||||
if (m_inlineTextEditor)
|
||||
m_inlineTextEditor->draw(painter);
|
||||
m_brushCursor.draw(painter);
|
||||
drawTextBoxDraft(painter);
|
||||
}
|
||||
|
||||
void CanvasView::draw(QPainter &context, const QRectF &dirty)
|
||||
{
|
||||
// The surround is the palette's Base: Swift's 0.105 when dark.
|
||||
context.fillRect(dirty, palette().color(QPalette::Base));
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!document)
|
||||
return;
|
||||
const CanvasViewport &viewport = m_session.viewport;
|
||||
const QRectF pixels = renderBounds().value();
|
||||
const double points = viewport.pointsPerPixel();
|
||||
const QRectF rect(viewport.viewPoint(pixels.topLeft(), document->size()), QSizeF(pixels.width() * points, pixels.height() * points));
|
||||
const QRectF bounds(QPointF(0, 0), QSizeF(size()));
|
||||
if (!rect.intersects(bounds) || !rect.intersects(dirty))
|
||||
return;
|
||||
// Inside the document its opaque fill covers the shadow.
|
||||
if (!rect.adjusted(1, 1, -1, -1).contains(dirty))
|
||||
drawShadow(rect, context);
|
||||
context.save();
|
||||
context.setClipRect(rect.intersected(dirty));
|
||||
context.fillRect(rect, QColor::fromRgbF(0.30, 0.30, 0.30));
|
||||
// Work scales with the visible viewport, not the document.
|
||||
constexpr double tile = 10;
|
||||
const QRectF visible = rect.intersected(bounds).intersected(dirty);
|
||||
if (!visible.isEmpty()) {
|
||||
const int minX = int(std::floor((visible.left() - rect.left()) / tile)), maxX = int(std::ceil((visible.right() - rect.left()) / tile));
|
||||
const int minY = int(std::floor((visible.top() - rect.top()) / tile)), maxY = int(std::ceil((visible.bottom() - rect.top()) / tile));
|
||||
for (int row = minY; row < maxY; ++row) {
|
||||
for (int column = minX; column < maxX; ++column) {
|
||||
if ((row + column) % 2 == 0)
|
||||
context.fillRect(QRectF(rect.left() + column * tile, rect.top() + row * tile, tile, tile), QColor::fromRgbF(0.35, 0.35, 0.35));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (viewport.zoom() >= crispZoom && !visible.isEmpty()) {
|
||||
drawDocumentPixels(visible, pixels, *document, context);
|
||||
} else {
|
||||
// Its own group: blend modes never meet the checkerboard.
|
||||
AdjustmentSurface::draw(context, [&](QPainter &group) {
|
||||
drawLayers(*document, points, [&](QPointF point) { return viewport.viewPoint(point, document->size()); }, group);
|
||||
});
|
||||
}
|
||||
if (m_session.showsPixelGrid() && viewport.zoom() >= pixelGridZoom && !visible.isEmpty())
|
||||
drawPixelGrid(visible, *document, context);
|
||||
context.restore();
|
||||
// A hairline astride the edge, soft as CoreGraphics strokes it.
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.setPen(QPen(QColor::fromRgbF(1, 1, 1, 0.13), 1 / viewport.backingScale));
|
||||
context.setBrush(Qt::NoBrush);
|
||||
context.drawRect(rect);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// The folder's live mask, multiplied into the coverage.
|
||||
FolderMaskClip::Applier CanvasView::liveFolderMaskClip(const BrushStroke &edit, double scale, const Center ¢er) const
|
||||
{
|
||||
return [&edit, scale, center](const QPainter &painter, QImage &coverage) {
|
||||
QImage live(coverage.size(), QImage::Format_Grayscale8);
|
||||
if (live.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
// Outside the mask's bounds stays hidden, as when committed.
|
||||
live.fill(0);
|
||||
LayerTransform transform = edit.paintTransform;
|
||||
transform.sampling = LayerSampling::nearest;
|
||||
const std::optional<ImportedImage> &base = edit.layer.mask ? std::optional(edit.layer.mask->asset) : std::nullopt;
|
||||
{
|
||||
QPainter drawing(&live);
|
||||
drawing.setTransform(painter.deviceTransform());
|
||||
// Swift's displayImage: halved near the size drawn.
|
||||
const double device = LayerRenderer::deviceScale(drawing);
|
||||
const auto shown = [device](const QImage &image, double width) {
|
||||
return DownsampleCache::shared().imageDrawnAt(image, width * device / std::max(1, image.width()));
|
||||
};
|
||||
const std::shared_ptr<const RasterSnapshot> raster = base ? base->raster : nullptr;
|
||||
const QImage image = base && !raster ? shown(base->image(), transform.size.width() * scale) : QImage();
|
||||
const QImage rasterBase = raster && !raster->base.isNull()
|
||||
? shown(raster->base, transform.size.width() * scale * raster->baseRect.width() / std::max(1, raster->width))
|
||||
: QImage();
|
||||
LayerRenderer::drawBrushPreview(image, transform, center(transform.center()), drawing, {.scale = scale},
|
||||
{.patches = edit.patches(), .pixelWidth = edit.width, .pixelHeight = edit.height, .paintingMask = false,
|
||||
.sourceRect = edit.sourceRect, .raster = raster, .rasterBase = rasterBase});
|
||||
}
|
||||
QPainter multiplying(&coverage);
|
||||
if (!multiplying.isActive())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
multiplying.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
multiplying.drawImage(QRectF(coverage.rect()), BrushRaster::alphaView(live));
|
||||
};
|
||||
}
|
||||
|
||||
void CanvasView::drawLayers(const CanvasDocument &document, double scale, const Center ¢er, QPainter &context)
|
||||
{
|
||||
m_session.effectsPreviews.prepare(document.layers);
|
||||
std::map<QUuid, ImageLayer> byID;
|
||||
for (const ImageLayer &layer : document.layers) {
|
||||
if (!byID.emplace(layer.id, layer).second)
|
||||
throw std::logic_error("a document repeats a layer id");
|
||||
}
|
||||
// A preview that lands repaints the view.
|
||||
const std::function<void()> repaint = [canvas = QPointer<CanvasView>(this)] {
|
||||
if (canvas)
|
||||
canvas->update();
|
||||
};
|
||||
const auto drawOwn = [&](QUuid id, QPainter &target, const QImage &clip) {
|
||||
// Open text shows in its editor instead.
|
||||
if (!byID.contains(id) || (m_session.textDraft() && m_session.textDraft().value().layerID == id))
|
||||
return;
|
||||
const ImageLayer &layer = byID.at(id);
|
||||
// A stroke or pixel move stands in for the pixels.
|
||||
const PixelMove *move = m_session.pixelMove();
|
||||
const std::optional<GradientEdit> &gradient = m_session.gradientEdit();
|
||||
const BrushStroke *stroke = m_session.brushStroke() && m_session.brushStroke()->layer.id == id ? m_session.brushStroke()
|
||||
: gradient && gradient->raster->layer.id == id ? gradient->raster.get()
|
||||
: move && move->raster->layer.id == id ? move->raster.get()
|
||||
: nullptr;
|
||||
if (!layer.asset && !stroke)
|
||||
return;
|
||||
// Smudge or Liquify under way: the reshaped copy, canvas-wide.
|
||||
if (const WarpStroke *warp = m_session.warpStroke(); warp && warp->layer.id == id) {
|
||||
const LayerTransform canvas{.origin = {0, 0}, .size = document.size()};
|
||||
const std::optional<QImage> mask = layer.mask ? layer.mask->clipImage(layer.maskTransform(), canvas, warp->width, warp->height, 2048)
|
||||
: std::nullopt;
|
||||
LayerRenderer::draw(warp->image(), canvas, center(canvas.center()), target,
|
||||
{.scale = scale, .opacity = layer.opacity, .blendMode = m_session.displayedBlendMode(layer),
|
||||
.mask = mask.value_or(QImage()), .clip = clip});
|
||||
return;
|
||||
}
|
||||
// A pixel stroke draws its grid by its own transform.
|
||||
const LayerTransform transform = stroke && !stroke->isMask ? stroke->paintTransform : m_session.displayedTransform(layer);
|
||||
const std::optional<LayerTransform> placement = m_session.displayedMaskPlacement(layer);
|
||||
std::optional<QImage> mask;
|
||||
if (const std::optional<QImage> distorted = m_session.maskDistortPreview(layer)) {
|
||||
mask = distorted;
|
||||
} else if (layer.mask && !placement) {
|
||||
mask = layer.mask->enabledImage();
|
||||
} else if (layer.mask) {
|
||||
// A placed mask in the layer's grid; 2048 while moving.
|
||||
const ImageLayer &owner = stroke ? stroke->layer : layer;
|
||||
const LayerTransform base = stroke ? owner.transform : transform;
|
||||
const double drawn = std::max(base.size.width(), base.size.height()) * scale * LayerRenderer::deviceScale(context);
|
||||
const double steady = std::pow(2, std::ceil(std::log2(std::max(64.0, drawn))));
|
||||
const QSize size = owner.asset ? owner.asset->size() : QSize(int(std::round(base.size.width())), int(std::round(base.size.height())));
|
||||
mask = layer.mask->clipImage(placement, base, size.width(), size.height(), m_session.transformEdit() ? std::min(2048.0, steady) : steady);
|
||||
}
|
||||
const LayerRenderer::Options options{.scale = scale, .opacity = layer.opacity, .blendMode = m_session.displayedBlendMode(layer),
|
||||
.mask = mask.value_or(QImage()), .clip = clip};
|
||||
// Swift asks twice; once, with what shows, is one request.
|
||||
const std::optional<EffectsPreviewCache::Result> effects =
|
||||
stroke ? std::nullopt : m_session.effectsPreviews.preview(layer, mask, transform, placement, repaint);
|
||||
const LayerRenderer::Options bare{.scale = scale, .opacity = layer.opacity, .blendMode = options.blendMode, .clip = clip};
|
||||
// A pending distortion warps the effects along with the layer.
|
||||
if (const auto warped = effects ? m_session.distortedEffects(layer, effects->image, effects->inset) : std::nullopt) {
|
||||
LayerRenderer::draw(warped->image, warped->transform, center(warped->transform.center()), target, bare);
|
||||
return;
|
||||
}
|
||||
// A pending distortion shows the layer warped into its shape.
|
||||
if (const std::optional<DistortPreview> distorted = m_session.distortPreview(layer)) {
|
||||
LayerRenderer::Options through = bare;
|
||||
through.mask = distorted->mask.value_or(QImage());
|
||||
LayerRenderer::draw(distorted->image, distorted->transform, center(distorted->transform.center()), target, through);
|
||||
return;
|
||||
}
|
||||
// Effects round the pixels, on a grown canvas.
|
||||
if (effects) {
|
||||
const LayerTransform grown = effects->placement.value_or(LayerEffectsRenderer::placed(transform, effects->image, effects->inset));
|
||||
LayerRenderer::draw(effects->image, grown, center(grown.center()), target, bare);
|
||||
return;
|
||||
}
|
||||
if (stroke) {
|
||||
drawStroke(*stroke, layer, transform, mask, options, scale, center, target);
|
||||
return;
|
||||
}
|
||||
// A rounded rectangle keeps its corners while it is resized.
|
||||
if (const QImage shaped = m_session.shapeTransformPreview(layer, transform); !shaped.isNull()) {
|
||||
LayerRenderer::draw(shaped, transform, center(transform.center()), target, options);
|
||||
return;
|
||||
}
|
||||
// An adjustment's or filter's preview stands in for the pixels.
|
||||
std::optional<QImage> preview = m_session.filterEdit() ? m_session.filterEdit()->previewImage(layer.id) : std::nullopt;
|
||||
if (!preview && m_session.levels())
|
||||
preview = m_session.levels()->previewImage(layer.id);
|
||||
if (!preview && m_session.hueSaturation())
|
||||
preview = m_session.hueSaturation()->previewImage(layer.id);
|
||||
if (preview)
|
||||
LayerRenderer::draw(*preview, transform, center(transform.center()), target, options);
|
||||
else if (layer.asset->raster)
|
||||
TiledLayerRenderer::drawRaster(layer.asset->raster, transform, center(transform.center()), target, options);
|
||||
else
|
||||
LayerRenderer::draw(layer.asset->image(), transform, center(transform.center()), target, options);
|
||||
};
|
||||
// Above the active layer, where the new layer will go.
|
||||
const auto drawOwnWithDraft = [&](QUuid id, QPainter &target, const QImage &clip) {
|
||||
drawOwn(id, target, clip);
|
||||
if (id == m_session.activeLayerID())
|
||||
drawShapeDraft(scale, center, target, clip);
|
||||
};
|
||||
const auto parent = [&](QUuid id) { return byID.contains(id) ? byID.at(id).parentID : std::nullopt; };
|
||||
// A mask being painted exists as the edit's tiles alone.
|
||||
const auto maskEdit = [&](QUuid id) -> const BrushStroke * {
|
||||
const BrushStroke *brush = m_session.brushStroke();
|
||||
const BrushStroke *gradient = m_session.gradientEdit() ? m_session.gradientEdit()->raster.get() : nullptr;
|
||||
for (const BrushStroke *edit : {brush, gradient}) {
|
||||
if (edit && edit->isMask && edit->layer.id == id)
|
||||
return edit;
|
||||
}
|
||||
return nullptr;
|
||||
};
|
||||
LiveMaskRenderer live([&](QUuid id) { return byID.contains(id) ? byID.at(id).maskSourceID : std::nullopt; }, drawOwnWithDraft);
|
||||
live.adjustment = [&](QUuid id) { return byID.contains(id) ? byID.at(id).adjustment : std::nullopt; };
|
||||
live.adjustmentOpacity = [&](QUuid id) { return byID.at(id).opacity; };
|
||||
live.adjustmentClip = [&](QUuid id, const QPainter &painter, QImage &coverage) {
|
||||
const ImageLayer &layer = byID.at(id);
|
||||
if (!layer.mask || !layer.mask->isEnabled)
|
||||
return;
|
||||
if (const BrushStroke *edit = maskEdit(id)) {
|
||||
liveFolderMaskClip(*edit, scale, center)(painter, coverage);
|
||||
return;
|
||||
}
|
||||
FolderMaskClip{layer.mask->asset.image(), layer.transform}.apply(center(layer.transform.center()), painter, coverage, scale);
|
||||
};
|
||||
std::vector<QUuid> ids;
|
||||
for (const ImageLayer &layer : document.renderLayers())
|
||||
ids.push_back(layer.id);
|
||||
live.prepareStacks(ids, parent, [&](QUuid id) { return byID.contains(id) ? m_session.displayedBlendMode(byID.at(id)) : LayerBlendMode::normal; });
|
||||
FolderMaskClip::draw(ids, parent, [&](QUuid id) -> std::optional<FolderMaskClip::Applier> {
|
||||
if (!byID.contains(id) || !byID.at(id).mask || !byID.at(id).mask->isEnabled)
|
||||
return std::nullopt;
|
||||
const ImageLayer &folder = byID.at(id);
|
||||
if (const BrushStroke *edit = maskEdit(id))
|
||||
return liveFolderMaskClip(*edit, scale, center);
|
||||
const LayerTransform transform = m_session.displayedTransform(folder);
|
||||
// A sharp halving near the mask's drawn size.
|
||||
const QImage image = folder.mask->asset.image();
|
||||
const double factor = transform.size.width() * scale * LayerRenderer::deviceScale(context) / std::max(1, image.width());
|
||||
const FolderMaskClip clip{DownsampleCache::shared().imageDrawnAt(image, factor), transform};
|
||||
const QPointF origin = center(transform.center());
|
||||
return [clip, origin, scale](const QPainter &painter, QImage &coverage) { clip.apply(origin, painter, coverage, scale); };
|
||||
}, context, [&](QUuid id, const QImage &clip) { live.drawComposite(id, context, clip); });
|
||||
}
|
||||
|
||||
void CanvasView::drawDocumentPixels(const QRectF &view, const QRectF &pixels, const CanvasDocument &document, QPainter &context)
|
||||
{
|
||||
const CanvasViewport &viewport = m_session.viewport;
|
||||
const QPointF topLeft = viewport.documentPoint(view.topLeft(), document.size());
|
||||
const QPointF bottomRight = viewport.documentPoint(view.bottomRight(), document.size());
|
||||
const QRectF region = QRectF(std::floor(topLeft.x()), std::floor(topLeft.y()), std::ceil(bottomRight.x()) - std::floor(topLeft.x()),
|
||||
std::ceil(bottomRight.y()) - std::floor(topLeft.y()))
|
||||
.intersected(QRectF(pixels.toAlignedRect()));
|
||||
if (region.isEmpty() || region.width() < 1 || region.height() < 1)
|
||||
return;
|
||||
QImage raster;
|
||||
try {
|
||||
raster = BrushRaster::context(int(region.width()), int(region.height()), false);
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "document pixels could not be drawn:" << error.what();
|
||||
return;
|
||||
}
|
||||
{
|
||||
QPainter painter(&raster);
|
||||
drawLayers(document, 1, [&](QPointF point) { return QPointF(point.x() - region.left(), point.y() - region.top()); }, painter);
|
||||
}
|
||||
const QPointF origin = viewport.viewPoint(region.topLeft(), document.size());
|
||||
const QRectF target(origin, QSizeF(region.width() * viewport.pointsPerPixel(), region.height() * viewport.pointsPerPixel()));
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::SmoothPixmapTransform, false);
|
||||
context.drawImage(target, raster);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// One-screen-pixel lines on document pixel boundaries, over the image only.
|
||||
void CanvasView::drawPixelGrid(const QRectF &view, const CanvasDocument &document, QPainter &context) const
|
||||
{
|
||||
const CanvasViewport &viewport = m_session.viewport;
|
||||
const double points = viewport.pointsPerPixel();
|
||||
const QRectF canvas(viewport.viewPoint(QPointF(0, 0), document.size()), QSizeF(document.width * points, document.height * points));
|
||||
const QRectF area = view.intersected(canvas);
|
||||
if (area.isEmpty())
|
||||
return;
|
||||
const QPointF first = viewport.documentPoint(area.topLeft(), document.size());
|
||||
const QPointF last = viewport.documentPoint(area.bottomRight(), document.size());
|
||||
const double hairline = 1 / viewport.backingScale;
|
||||
// Crossings fill once, as CoreGraphics fills the union.
|
||||
QPainterPath path;
|
||||
path.setFillRule(Qt::WindingFill);
|
||||
for (int column = int(std::ceil(first.x())); column <= int(std::floor(last.x())); ++column) {
|
||||
const double x = viewport.viewPoint(QPointF(column, 0), document.size()).x();
|
||||
path.addRect(QRectF(x - hairline / 2, area.top(), hairline, area.height()));
|
||||
}
|
||||
for (int row = int(std::ceil(first.y())); row <= int(std::floor(last.y())); ++row) {
|
||||
const double y = viewport.viewPoint(QPointF(0, row), document.size()).y();
|
||||
path.addRect(QRectF(area.left(), y - hairline / 2, area.width(), hairline));
|
||||
}
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.fillPath(path, QColor::fromRgbF(0.55, 0.55, 0.55, 0.45));
|
||||
context.restore();
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
#pragma once
|
||||
#include "Document/Crop.h"
|
||||
#include "Document/EditorSession.h"
|
||||
#include "Document/LayerMask.h"
|
||||
#include "Rendering/BrushCursorOverlay.h"
|
||||
#include "Rendering/InlineTextEditor.h"
|
||||
#include "Rendering/LayerEffectsSurface.h"
|
||||
#include "Rendering/SelectionIcons.h"
|
||||
#include "Rendering/LayerRenderer.h"
|
||||
#include "Rendering/SampleRingOverlay.h"
|
||||
#include "Rendering/TransformOverlay.h"
|
||||
#include <QElapsedTimer>
|
||||
#include <QPainterPath>
|
||||
#include <QTimer>
|
||||
#include <QWidget>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
// The document on screen: layers over a checkerboard.
|
||||
class CanvasView : public QWidget {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit CanvasView(EditorSession &session, QWidget *parent = nullptr);
|
||||
|
||||
// From 200% document pixels show hard-edged, as Photoshop does.
|
||||
static constexpr double crispZoom = 2;
|
||||
// The pixel grid appears from 800%.
|
||||
static constexpr double pixelGridZoom = 8;
|
||||
// Crop edges snap within this many view points.
|
||||
static constexpr double cropSnapDistance = 8;
|
||||
|
||||
// Repaints what the session changed; true when something did.
|
||||
bool synchronizeDisplay();
|
||||
// Each request the session counts up takes focus once.
|
||||
void consumeFocusRequest(int request);
|
||||
// Photoshop's duplicate pointer: a black arrow over a white one.
|
||||
static QCursor duplicateCursor(double ratio);
|
||||
// The Move pointer and the rotation grip's, drawn as paths.
|
||||
static QCursor moveCursor(double ratio);
|
||||
static QCursor rotationCursor(double ratio);
|
||||
// A white arrow: the handle under it distorts.
|
||||
static QCursor distortCursor(double ratio);
|
||||
// A badged pointing hand: Ctrl-click loads a selection.
|
||||
static QCursor loadSelectionCursor(double ratio);
|
||||
// An arrow with a dashed box: it drags the outline.
|
||||
static QCursor moveSelectionCursor(double ratio);
|
||||
// The arrow with scissors: a Ctrl-drag cuts and moves pixels.
|
||||
static QCursor movePixelsCursor(double ratio);
|
||||
// A crosshair with the tool's icon, badged + or −.
|
||||
static QCursor selectionCursor(SelectionIcon icon, SelectionMode mode, double ratio);
|
||||
// The wand, its sparkle at the hot spot, badged alike.
|
||||
static QCursor wandCursor(SelectionMode mode, double ratio);
|
||||
// Swift's eyedropper: haloed white, its tip the hot spot.
|
||||
static QCursor eyedropperCursor(double ratio);
|
||||
// The brush circle as last drawn, for tests.
|
||||
const BrushCursorOverlay &brushCursor() const { return m_brushCursor; }
|
||||
const SampleRingOverlay &sampleRing() const { return m_sampleRing; }
|
||||
// The text typed on the canvas, while one is open.
|
||||
InlineTextEditor *inlineTextEditor() const { return m_inlineTextEditor.get(); }
|
||||
|
||||
protected:
|
||||
bool event(QEvent *event) override;
|
||||
bool eventFilter(QObject *watched, QEvent *event) override;
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
void showEvent(QShowEvent *event) override;
|
||||
void hideEvent(QHideEvent *event) override;
|
||||
void wheelEvent(QWheelEvent *event) override;
|
||||
void mousePressEvent(QMouseEvent *event) override;
|
||||
void mouseMoveEvent(QMouseEvent *event) override;
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
void mouseDoubleClickEvent(QMouseEvent *event) override;
|
||||
void keyPressEvent(QKeyEvent *event) override;
|
||||
void keyReleaseEvent(QKeyEvent *event) override;
|
||||
void leaveEvent(QEvent *event) override;
|
||||
void focusInEvent(QFocusEvent *event) override;
|
||||
void focusOutEvent(QFocusEvent *event) override;
|
||||
void inputMethodEvent(QInputMethodEvent *event) override;
|
||||
QVariant inputMethodQuery(Qt::InputMethodQuery query) const override;
|
||||
|
||||
private:
|
||||
struct DisplayState {
|
||||
struct Layer {
|
||||
QUuid id;
|
||||
LayerTransform transform;
|
||||
std::optional<ImageIdentity> imageID;
|
||||
std::optional<ImageIdentity> maskID;
|
||||
std::optional<QUuid> maskSourceID;
|
||||
// Entering or leaving a masked folder changes the clip.
|
||||
std::optional<QUuid> parentID;
|
||||
bool visible;
|
||||
double opacity;
|
||||
LayerBlendMode blendMode;
|
||||
// Where the mask shows when placed apart from the layer.
|
||||
std::optional<LayerTransform> maskPlacement;
|
||||
std::optional<LayerAdjustment> adjustment;
|
||||
std::optional<LayerEffects> effects;
|
||||
friend bool operator==(const Layer &, const Layer &) = default;
|
||||
};
|
||||
// Folders have no pixels, so their masks are tracked apart.
|
||||
struct FolderMask {
|
||||
QUuid id;
|
||||
std::optional<ImageIdentity> maskID;
|
||||
LayerTransform transform;
|
||||
friend bool operator==(const FolderMask &, const FolderMask &) = default;
|
||||
};
|
||||
// Every change to a stroke, so a press repaints.
|
||||
int brushRevision;
|
||||
bool pixelGrid;
|
||||
// A distortion's corners: the warp follows them.
|
||||
std::optional<Corners> corners;
|
||||
std::optional<QUuid> documentID;
|
||||
std::optional<QSizeF> size;
|
||||
std::optional<QRectF> renderBounds;
|
||||
CanvasViewport viewport;
|
||||
std::vector<Layer> layers;
|
||||
std::vector<FolderMask> folderMasks;
|
||||
friend bool operator==(const DisplayState &, const DisplayState &) = default;
|
||||
};
|
||||
// A Zoom press: drags zoom about it, clicks step.
|
||||
struct ZoomDrag {
|
||||
QPointF start;
|
||||
double zoom;
|
||||
bool moved;
|
||||
};
|
||||
using Center = std::function<QPointF(QPointF)>;
|
||||
// What a press off the handles drags, picked or not.
|
||||
struct PressTarget {
|
||||
QUuid id;
|
||||
bool picked;
|
||||
};
|
||||
|
||||
DisplayState displayState() const;
|
||||
std::optional<QRectF> strokeDirtyRect() const;
|
||||
FolderMaskClip::Applier liveFolderMaskClip(const BrushStroke &edit, double scale, const Center ¢er) const;
|
||||
std::optional<QRectF> renderBounds() const;
|
||||
void syncGeometry();
|
||||
void draw(QPainter &context, const QRectF &dirty);
|
||||
void drawStroke(const BrushStroke &stroke, const ImageLayer &layer, const LayerTransform &transform, const std::optional<QImage> &mask,
|
||||
const LayerRenderer::Options &options, double scale, const Center ¢er, QPainter &target);
|
||||
void drawLayers(const CanvasDocument &document, double scale, const Center ¢er, QPainter &context);
|
||||
// Swift's effects surface on the canvas (EditorCanvas+Effects.cpp).
|
||||
LayerEffectsSurface *strokeSurface(const ImageLayer &layer, const BrushStroke &stroke, const std::optional<QImage> &mask);
|
||||
// The stroke is over: its surface stands in meanwhile.
|
||||
void handOnStrokeSurface();
|
||||
// The dragged shape, in the colour it will have.
|
||||
void drawShapeDraft(double scale, const Center ¢er, QPainter &target, const QImage &clip) const;
|
||||
// What the draft draws with, so a change repaints it.
|
||||
struct ShapeShown {
|
||||
ShapeDraft draft;
|
||||
PaletteColor color;
|
||||
double lineWidth;
|
||||
// The layer the draft sits above.
|
||||
std::optional<QUuid> target;
|
||||
friend bool operator==(const ShapeShown &, const ShapeShown &) = default;
|
||||
};
|
||||
std::optional<ShapeShown> shownShape() const;
|
||||
// Swift's synchronizeInlineText: the editor follows the draft.
|
||||
void synchronizeInlineText();
|
||||
// The Type tool's press: the editor's, else Swift's gesture.
|
||||
void pressTextTool(QPointF point, Qt::KeyboardModifiers modifiers, int clicks);
|
||||
void beginTextGesture(QPointF point, Qt::KeyboardModifiers modifiers, int clicks);
|
||||
void dragTextGesture(QPointF point);
|
||||
void finishTextGesture();
|
||||
void endTextGesture();
|
||||
QRectF textBoxDraftRect() const;
|
||||
void drawTextBoxDraft(QPainter &painter) const;
|
||||
void drawDocumentPixels(const QRectF &view, const QRectF &pixels, const CanvasDocument &document, QPainter &context);
|
||||
void drawPixelGrid(const QRectF &view, const CanvasDocument &document, QPainter &context) const;
|
||||
void updateCursor();
|
||||
static QPainterPath arrowPath();
|
||||
Qt::KeyboardModifiers heldModifiers() const;
|
||||
void readModifiers(Qt::KeyboardModifiers modifiers);
|
||||
void modifiersChanged();
|
||||
std::optional<PressTarget> transformPressLayer(QPointF pixel, Qt::KeyboardModifiers modifiers) const;
|
||||
bool pressMovesLayer(QPointF point, Qt::KeyboardModifiers modifiers) const;
|
||||
QCursor transformCursor(QPointF point, Qt::KeyboardModifiers modifiers) const;
|
||||
void beginTransformDrag(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void dragTransform(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void endTransformDrag();
|
||||
void cancelTransformDrag();
|
||||
// Swift's lasso gestures (EditorCanvas+Selection.cpp).
|
||||
QCursor lassoCursor(Qt::KeyboardModifiers modifiers, std::optional<QPointF> location) const;
|
||||
static QCursor pixelDragCursor(bool duplicate, double ratio);
|
||||
void lassoMouseDown(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
bool moveSelectionTool(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void releaseSelectionTool();
|
||||
bool selectionKey(const QKeyEvent &key);
|
||||
void endSelectionGestures();
|
||||
void dragSelection(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void dragMarqueeDraft(QPointF pixel, Qt::KeyboardModifiers modifiers);
|
||||
QSizeF marqueeAutoscrollDelta(QPointF point) const;
|
||||
void updateMarqueeAutoscroll(QPointF point);
|
||||
void stepMarqueeAutoscroll();
|
||||
void stopMarqueeAutoscroll();
|
||||
void updateAntsTimer();
|
||||
// Swift's brush gestures (EditorCanvas+Brush.cpp).
|
||||
void brushMouseDown(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
bool brushMouseMove(QPointF point, Qt::KeyboardModifiers modifiers, bool dragging);
|
||||
void brushMouseUp(QPointF point);
|
||||
void beginBrushTipDrag(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void dragBrushTip(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void endBrushTipDrag(QPointF point);
|
||||
void updateBrushCursor();
|
||||
// Clone Stamp's preview: one click's coverage, and the source there.
|
||||
QImage cloneTip(double diameter, double hardness);
|
||||
QImage clonePreview(QPointF center, double diameter, const CanvasDocument &document);
|
||||
bool brushKey(const QKeyEvent &key);
|
||||
// Swift's gradient gestures (EditorCanvas+Gradient.cpp).
|
||||
void beginGradientDrag(QPointF point);
|
||||
bool dragGradient(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
// Shift keeps a line to 45° steps, as Photoshop.
|
||||
static QPointF snapped(QPointF point, QPointF anchor);
|
||||
bool brushBracket(const QString &text);
|
||||
// Swift's colour sampling (EditorCanvas+Picking.cpp).
|
||||
bool palettePicking() const;
|
||||
bool picking() const;
|
||||
void syncPicking();
|
||||
void beginSampling(QPointF point);
|
||||
void sampleColor(QPointF point);
|
||||
void endSampling();
|
||||
bool pickingMove(QPointF point, Qt::MouseButtons buttons);
|
||||
void pickingRelease();
|
||||
// A sampling or targeting press, with Space up.
|
||||
bool pickingPress(QPointF point);
|
||||
// Swift's crop gestures (EditorCanvas+Crop.cpp).
|
||||
std::optional<int> cropRegion(QPointF point) const;
|
||||
QCursor cropCursor(QPointF point) const;
|
||||
void beginCropDrag(QPointF point);
|
||||
bool cropMove(QPointF point, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers);
|
||||
void dragCrop(QPointF point, Qt::KeyboardModifiers modifiers);
|
||||
void endCropDrag();
|
||||
bool cropKey(const QKeyEvent &key);
|
||||
// Swift's targeted drag: right raises; Ctrl drags the hue.
|
||||
bool targetingMove(QPointF point, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers);
|
||||
void targetingRelease();
|
||||
|
||||
EditorSession &m_session;
|
||||
TransformOverlay m_overlay;
|
||||
std::optional<TransformOverlayGeometry> m_displayedGeometry;
|
||||
SnapGuides m_displayedGuides;
|
||||
// Where the overlay last drew, repainted with the next drawing.
|
||||
QRect m_overlayRect;
|
||||
std::optional<TransformDrag> m_transformDrag;
|
||||
// The drag's cursor, kept until the release.
|
||||
std::optional<QCursor> m_dragCursor;
|
||||
bool m_duplicatesTransformOnDrag = false;
|
||||
// The last pointer position over the canvas.
|
||||
std::optional<QPointF> m_hover;
|
||||
bool m_controlHeld = false;
|
||||
// Busy or importing shows the arrow; tracked for refreshes.
|
||||
bool m_displayedBlocked = false;
|
||||
std::optional<DisplayState> m_displayedState;
|
||||
std::optional<NavigationTool> m_displayedTool;
|
||||
int m_lastFocusRequest = 0;
|
||||
bool m_spaceHeld = false;
|
||||
bool m_optionHeld = false;
|
||||
std::optional<QPointF> m_lastDragPoint;
|
||||
std::optional<ZoomDrag> m_zoomDrag;
|
||||
bool m_shiftHeld = false;
|
||||
// Document point where a drag of the outline began.
|
||||
std::optional<QPointF> m_selectionDragStart;
|
||||
// Where a Ctrl-drag of selected pixels began, in document pixels.
|
||||
std::optional<QPointF> m_pixelDragStart;
|
||||
// Shift at the press chose Add; pressed afresh it squares.
|
||||
bool m_marqueeConstrainArmed = true;
|
||||
std::optional<QPointF> m_marqueeDragPixel;
|
||||
// Against the canvas edge the view pans toward the pointer.
|
||||
QTimer m_marqueeAutoscroll;
|
||||
std::optional<QPointF> m_marqueeAutoscrollPoint;
|
||||
QTimer m_antsTimer;
|
||||
std::optional<DocumentSelection> m_displayedOutline;
|
||||
std::optional<LassoDraft> m_displayedDraft;
|
||||
std::optional<ShapeShown> m_displayedShape;
|
||||
// What the lasso cursor last showed: kinds and mode.
|
||||
struct SelectionCursorState {
|
||||
LassoKind marquee;
|
||||
LassoKind lasso;
|
||||
SelectionMode mode;
|
||||
friend bool operator==(const SelectionCursorState &, const SelectionCursorState &) = default;
|
||||
};
|
||||
std::optional<SelectionCursorState> m_displayedSelectionCursor;
|
||||
BrushCursorOverlay m_brushCursor;
|
||||
std::unique_ptr<InlineTextEditor> m_inlineTextEditor;
|
||||
// A text box being drawn, in document pixels.
|
||||
std::optional<QPointF> m_textBoxAnchor;
|
||||
std::optional<QRectF> m_textBoxRect;
|
||||
// Qt lacks triple clicks: a press soon after a double.
|
||||
QElapsedTimer m_textDoubleClick;
|
||||
QPointF m_textDoubleClickPoint;
|
||||
// The circle's centre in view points; none off the canvas.
|
||||
std::optional<QPointF> m_brushPointer;
|
||||
// Shift's line keeps to the axis its first pixels chose.
|
||||
std::optional<QPointF> m_brushAxisAnchor;
|
||||
std::optional<bool> m_brushAxisHorizontal;
|
||||
std::optional<QPointF> m_brushLastPixel;
|
||||
// A right-drag: size or hardness from the press's values.
|
||||
struct BrushTipDrag {
|
||||
QPointF start;
|
||||
double diameter;
|
||||
double hardness;
|
||||
bool hardnessShown;
|
||||
};
|
||||
std::optional<BrushTipDrag> m_brushTipDrag;
|
||||
// Swift's cloneTipCache: rebuilt when size or hardness change.
|
||||
struct CloneTip {
|
||||
double diameter;
|
||||
double hardness;
|
||||
QImage image;
|
||||
};
|
||||
std::optional<CloneTip> m_cloneTip;
|
||||
// Which end of the pending gradient a drag moves.
|
||||
enum class GradientHandle { start, end };
|
||||
std::optional<GradientHandle> m_gradientDrag;
|
||||
// Swift's ClonePreviewKey: what the preview depends on.
|
||||
struct ClonePreviewKey {
|
||||
QPointF center;
|
||||
double diameter;
|
||||
double scale;
|
||||
int revision;
|
||||
int undoCount;
|
||||
bool allLayers;
|
||||
std::optional<QUuid> layerID;
|
||||
friend bool operator==(const ClonePreviewKey &, const ClonePreviewKey &) = default;
|
||||
};
|
||||
struct ClonePreview {
|
||||
ClonePreviewKey key;
|
||||
QImage image;
|
||||
};
|
||||
std::optional<ClonePreview> m_clonePreview;
|
||||
SampleRingOverlay m_sampleRing;
|
||||
// The painted layer's effects, made as its stroke starts.
|
||||
std::unique_ptr<LayerEffectsSurface> m_strokeSurface;
|
||||
// The colour a sampling press began from, for the ring.
|
||||
PaletteColor m_samplingOriginal = PaletteColor::black();
|
||||
bool m_samplingColor = false;
|
||||
bool m_displayedPicking = false;
|
||||
bool m_displayedTargeting = false;
|
||||
// Where a targeted drag began, in view points.
|
||||
std::optional<QPointF> m_hueTargetStart;
|
||||
std::optional<CropDrag> m_cropDrag;
|
||||
// Built at the press: the zoom holds still mid-drag.
|
||||
std::optional<CropSnap> m_cropSnap;
|
||||
// The crop frame as last shown, in view points.
|
||||
std::optional<QRectF> m_displayedCrop;
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
#include "Rendering/EffectsPreviewCache.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "Document/LayerEffects+Renderer.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "Logging.h"
|
||||
#include <QTimer>
|
||||
#include <cmath>
|
||||
#include <set>
|
||||
|
||||
EffectsPreviewCache::EffectsPreviewCache(QObject *parent) : QObject(parent)
|
||||
{
|
||||
m_worker.setMaxThreadCount(1);
|
||||
}
|
||||
|
||||
EffectsPreviewCache::~EffectsPreviewCache()
|
||||
{
|
||||
// Queued renders go; the pool waits for the one running.
|
||||
m_worker.clear();
|
||||
}
|
||||
|
||||
bool EffectsPreviewCache::Request::matches(const Request &other) const
|
||||
{
|
||||
// A move only moves the image; a placed mask resamples.
|
||||
const bool sameMaskGeometry = (!maskSource && !other.maskSource) || (!placement && !other.placement)
|
||||
|| (placement == other.placement && transform == other.transform);
|
||||
return image.identity() == other.image.identity() && maskSource == other.maskSource && sameMaskGeometry && effects == other.effects
|
||||
&& sideLimit == other.sideLimit;
|
||||
}
|
||||
|
||||
void EffectsPreviewCache::seed(QUuid id, const QImage &image, const LayerTransform &placement)
|
||||
{
|
||||
// A render under way is for the pixels this replaces.
|
||||
cancel(id);
|
||||
m_seeds.insert_or_assign(id, Result{image, 0, placement});
|
||||
}
|
||||
|
||||
std::optional<EffectsPreviewCache::Result> EffectsPreviewCache::rendered(QUuid id) const
|
||||
{
|
||||
if (m_entries.contains(id) && m_entries.at(id).result)
|
||||
return m_entries.at(id).result;
|
||||
return m_seeds.contains(id) ? std::optional(m_seeds.at(id)) : std::nullopt;
|
||||
}
|
||||
|
||||
void EffectsPreviewCache::prepare(const std::vector<ImageLayer> &layers)
|
||||
{
|
||||
std::set<QUuid> ids;
|
||||
for (const ImageLayer &layer : layers) {
|
||||
if (layer.effects && !layer.effects->visible().isEmpty())
|
||||
ids.insert(layer.id);
|
||||
}
|
||||
for (auto entry = m_entries.begin(); entry != m_entries.end();) {
|
||||
if (ids.contains(entry->first)) {
|
||||
++entry;
|
||||
continue;
|
||||
}
|
||||
entry->second.request.cancelled->store(true);
|
||||
entry = m_entries.erase(entry);
|
||||
}
|
||||
std::erase_if(m_seeds, [&](const auto &seed) { return !ids.contains(seed.first); });
|
||||
// About 64 MiB of output shared by every effect layer.
|
||||
m_sideLimit = std::min(1536, std::max(32, int(std::sqrt(16'777'216.0 / double(std::max<size_t>(1, ids.size()))))));
|
||||
}
|
||||
|
||||
std::optional<EffectsPreviewCache::Result> EffectsPreviewCache::preview(const ImageLayer &layer, const std::optional<QImage> &mask,
|
||||
const LayerTransform &transform,
|
||||
const std::optional<LayerTransform> &maskPlacement,
|
||||
const std::function<void()> &completion)
|
||||
{
|
||||
const LayerEffects effects = layer.effects.value_or(LayerEffects()).visible();
|
||||
if (!layer.asset || effects.isEmpty() || !effects.isValid()) {
|
||||
cancel(layer.id);
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::optional<ImageIdentity> maskSource = layer.mask && layer.mask->isEnabled ? std::optional(layer.mask->asset.identity()) : std::nullopt;
|
||||
const Request request{QUuid::createUuid(), *layer.asset, mask, maskSource, maskPlacement, transform, effects, m_sideLimit,
|
||||
std::make_shared<std::atomic<bool>>(false)};
|
||||
if (m_entries.contains(layer.id) && m_entries.at(layer.id).request.matches(request))
|
||||
return m_entries.at(layer.id).result;
|
||||
std::optional<Result> previous;
|
||||
if (m_entries.contains(layer.id)) {
|
||||
const Entry &old = m_entries.at(layer.id);
|
||||
old.request.cancelled->store(true);
|
||||
// Kept while the settings change on the same pixels.
|
||||
if (old.request.image.identity() == request.image.identity() && old.request.maskSource == maskSource
|
||||
&& old.request.effects.kinds() == effects.kinds())
|
||||
previous = old.result;
|
||||
}
|
||||
if (!previous && m_seeds.contains(layer.id))
|
||||
previous = m_seeds.at(layer.id);
|
||||
m_entries.insert_or_assign(layer.id, Entry{request, previous});
|
||||
const QUuid layerID = layer.id;
|
||||
QTimer::singleShot(60, this, [this, request, layerID, completion] {
|
||||
m_worker.start([this, request, layerID, completion] {
|
||||
if (request.cancelled->load())
|
||||
return;
|
||||
const std::optional<Result> result = render(request);
|
||||
if (request.cancelled->load())
|
||||
return;
|
||||
QMetaObject::invokeMethod(this, [this, layerID, id = request.id, result, completion] { land(layerID, id, result, completion); },
|
||||
Qt::QueuedConnection);
|
||||
});
|
||||
});
|
||||
return previous;
|
||||
}
|
||||
|
||||
void EffectsPreviewCache::land(QUuid layerID, QUuid requestID, const std::optional<Result> &result, const std::function<void()> &completion)
|
||||
{
|
||||
if (!m_entries.contains(layerID) || m_entries.at(layerID).request.id != requestID)
|
||||
return;
|
||||
m_entries.at(layerID).result = result;
|
||||
if (result)
|
||||
m_seeds.erase(layerID);
|
||||
completion();
|
||||
}
|
||||
|
||||
void EffectsPreviewCache::cancel(QUuid id)
|
||||
{
|
||||
if (!m_entries.contains(id))
|
||||
return;
|
||||
m_entries.at(id).request.cancelled->store(true);
|
||||
m_entries.erase(id);
|
||||
}
|
||||
|
||||
std::optional<EffectsPreviewCache::Result> EffectsPreviewCache::render(const Request &request)
|
||||
{
|
||||
try {
|
||||
// A painted layer flattens here, off the UI thread.
|
||||
const QImage image = request.image.image();
|
||||
const double margin = LayerEffectsRenderer::margin(request.effects);
|
||||
// The margins count too; even a 500px stroke stays bounded.
|
||||
const double factor = std::min(1.0, double(request.sideLimit - 8) / (double(std::max(image.width(), image.height())) + 2 * margin));
|
||||
const int width = std::max(1, int(std::round(image.width() * factor)));
|
||||
const int height = std::max(1, int(std::round(image.height() * factor)));
|
||||
// Swift's high quality: each axis filtered by its own measure.
|
||||
const auto resized = [&](const QImage &source, bool mask) {
|
||||
// A mask travels as alpha, so its values pass exactly.
|
||||
const QImage scaled = (mask ? BrushRaster::alphaView(source) : source)
|
||||
.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)
|
||||
.convertToFormat(mask ? QImage::Format_Alpha8 : QImage::Format_RGBA8888_Premultiplied);
|
||||
const QImage result = mask ? QImage(scaled.constBits(), width, height, scaled.bytesPerLine(), QImage::Format_Grayscale8).copy() : scaled;
|
||||
if (result.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
return result;
|
||||
};
|
||||
const QImage pixels = factor == 1 ? image : resized(image, false);
|
||||
const std::optional<QImage> mask = request.mask ? std::optional(factor == 1 ? *request.mask : resized(*request.mask, true)) : std::nullopt;
|
||||
LayerEffects effects = request.effects;
|
||||
if (effects.stroke)
|
||||
effects.stroke->size *= factor;
|
||||
if (effects.shadow) {
|
||||
effects.shadow->distance *= factor;
|
||||
effects.shadow->blur *= factor;
|
||||
}
|
||||
// Swift forgets the inner shadow, which then shows too wide.
|
||||
if (effects.innerShadow) {
|
||||
effects.innerShadow->distance *= factor;
|
||||
effects.innerShadow->blur *= factor;
|
||||
}
|
||||
const LayerEffectsRenderer::Rendered rendered = LayerEffectsRenderer::render(pixels, mask, effects);
|
||||
return Result{rendered.image, rendered.inset, std::nullopt};
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "an effects preview could not be made:" << error.what();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
#include "Document/EditorSession+Model.h"
|
||||
#include <QObject>
|
||||
#include <QThreadPool>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
|
||||
// Swift's EffectsPreviewCache: canvas previews off the UI thread.
|
||||
class EffectsPreviewCache : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit EffectsPreviewCache(QObject *parent = nullptr);
|
||||
~EffectsPreviewCache() override;
|
||||
// Swift's tuple; a seed alone carries where it belongs.
|
||||
struct Result {
|
||||
QImage image;
|
||||
double inset;
|
||||
std::optional<LayerTransform> placement;
|
||||
};
|
||||
// Shown at `placement` until a fresh preview lands.
|
||||
void seed(QUuid id, const QImage &image, const LayerTransform &placement);
|
||||
// What is already rendered, asking for nothing new.
|
||||
std::optional<Result> rendered(QUuid id) const;
|
||||
// Drops layers without effects; they share the pixel budget.
|
||||
void prepare(const std::vector<ImageLayer> &layers);
|
||||
// The last result; `completion` runs once a new one lands.
|
||||
std::optional<Result> preview(const ImageLayer &layer, const std::optional<QImage> &mask, const LayerTransform &transform,
|
||||
const std::optional<LayerTransform> &maskPlacement, const std::function<void()> &completion);
|
||||
|
||||
private:
|
||||
struct Request {
|
||||
QUuid id;
|
||||
ImportedImage image;
|
||||
std::optional<QImage> mask;
|
||||
// Swift's `===` on the mask's enabled image.
|
||||
std::optional<ImageIdentity> maskSource;
|
||||
std::optional<LayerTransform> placement;
|
||||
LayerTransform transform;
|
||||
LayerEffects effects;
|
||||
int sideLimit;
|
||||
std::shared_ptr<std::atomic<bool>> cancelled;
|
||||
bool matches(const Request &other) const;
|
||||
};
|
||||
struct Entry {
|
||||
Request request;
|
||||
std::optional<Result> result;
|
||||
};
|
||||
static std::optional<Result> render(const Request &request);
|
||||
void cancel(QUuid id);
|
||||
void land(QUuid layerID, QUuid requestID, const std::optional<Result> &result, const std::function<void()> &completion);
|
||||
|
||||
std::map<QUuid, Entry> m_entries;
|
||||
// Warped effects handed in, shown until the worker catches up.
|
||||
std::map<QUuid, Result> m_seeds;
|
||||
int m_sideLimit = 1536;
|
||||
// Swift's serial queue: one render at a time.
|
||||
QThreadPool m_worker;
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
#include "Rendering/EyedropperIcon.h"
|
||||
#include <QPainterPath>
|
||||
|
||||
namespace {
|
||||
// The glyph stands turned 45 degrees about the grid's middle.
|
||||
QTransform turned()
|
||||
{
|
||||
return QTransform().translate(9, 9).rotate(45);
|
||||
}
|
||||
|
||||
constexpr QPointF tubeTip(0, 8.4);
|
||||
}
|
||||
|
||||
QPointF EyedropperIcon::tip()
|
||||
{
|
||||
return turned().map(tubeTip);
|
||||
}
|
||||
|
||||
void EyedropperIcon::paint(QPainter &painter)
|
||||
{
|
||||
// A bulb at the top right; a tube below.
|
||||
painter.save();
|
||||
painter.setTransform(turned(), true);
|
||||
painter.fillRect(QRectF(-2.4, -8.6, 4.8, 4.4), painter.pen().color());
|
||||
painter.drawLine(QPointF(-3.6, -3.6), QPointF(3.6, -3.6));
|
||||
QPainterPath tube(QPointF(-1.7, -3.6));
|
||||
tube.lineTo(QPointF(-1.7, 5.2));
|
||||
tube.lineTo(tubeTip);
|
||||
tube.lineTo(QPointF(1.7, 5.2));
|
||||
tube.lineTo(QPointF(1.7, -3.6));
|
||||
painter.drawPath(tube);
|
||||
painter.restore();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <QPainter>
|
||||
#include <QPointF>
|
||||
|
||||
// SF Symbols' eyedropper, which the rail and the cursor share.
|
||||
namespace EyedropperIcon {
|
||||
// The tube's tip, bottom left, on the 18-point grid.
|
||||
QPointF tip();
|
||||
// Draws with the painter's pen, as the rail's icons.
|
||||
void paint(QPainter &painter);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "Rendering/HslBlend.h"
|
||||
#include "Rendering/PoolMap.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include <QtConcurrent>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
using Color = std::array<float, 3>;
|
||||
|
||||
float lum(const Color &color)
|
||||
{
|
||||
return 0.3f * color[0] + 0.59f * color[1] + 0.11f * color[2];
|
||||
}
|
||||
|
||||
Color clipColor(Color color)
|
||||
{
|
||||
const float l = lum(color);
|
||||
const float low = std::min({color[0], color[1], color[2]}), high = std::max({color[0], color[1], color[2]});
|
||||
for (float &channel : color) {
|
||||
if (low < 0)
|
||||
channel = l + (channel - l) * l / (l - low);
|
||||
if (high > 1)
|
||||
channel = l + (channel - l) * (1 - l) / (high - l);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
Color setLum(Color color, float l)
|
||||
{
|
||||
const float shift = l - lum(color);
|
||||
for (float &channel : color)
|
||||
channel += shift;
|
||||
return clipColor(color);
|
||||
}
|
||||
|
||||
float sat(const Color &color)
|
||||
{
|
||||
return std::max({color[0], color[1], color[2]}) - std::min({color[0], color[1], color[2]});
|
||||
}
|
||||
|
||||
Color setSat(const Color &color, float s)
|
||||
{
|
||||
std::array<int, 3> order{0, 1, 2};
|
||||
std::sort(order.begin(), order.end(), [&](int lhs, int rhs) { return color[lhs] < color[rhs]; });
|
||||
const int low = order[0], middle = order[1], high = order[2];
|
||||
Color result{0, 0, 0};
|
||||
if (color[high] > color[low]) {
|
||||
result[middle] = (color[middle] - color[low]) * s / (color[high] - color[low]);
|
||||
result[high] = s;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Color mixed(LayerBlendMode mode, const Color &backdrop, const Color &source)
|
||||
{
|
||||
switch (mode) {
|
||||
case LayerBlendMode::hue:
|
||||
return setLum(setSat(source, sat(backdrop)), lum(backdrop));
|
||||
case LayerBlendMode::saturation:
|
||||
return setLum(setSat(backdrop, sat(source)), lum(backdrop));
|
||||
case LayerBlendMode::color:
|
||||
return setLum(source, lum(backdrop));
|
||||
case LayerBlendMode::luminosity:
|
||||
return setLum(backdrop, lum(source));
|
||||
default:
|
||||
throw std::logic_error("HslBlend handles only the four non-separable modes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool HslBlend::handles(LayerBlendMode mode)
|
||||
{
|
||||
return mode == LayerBlendMode::hue || mode == LayerBlendMode::saturation || mode == LayerBlendMode::color
|
||||
|| mode == LayerBlendMode::luminosity;
|
||||
}
|
||||
|
||||
QImage HslBlend::blend(const QImage &backdrop, const QImage &source, LayerBlendMode mode, double opacity)
|
||||
{
|
||||
if (backdrop.size() != source.size() || backdrop.format() != QImage::Format_RGBA8888_Premultiplied
|
||||
|| source.format() != QImage::Format_RGBA8888_Premultiplied)
|
||||
throw std::logic_error("HslBlend needs two RGBA8888 premultiplied images of one size");
|
||||
// Checked here: a worker's exception would come back wrapped.
|
||||
if (!handles(mode))
|
||||
throw std::logic_error("HslBlend blends hue, saturation, color and luminosity alone");
|
||||
QImage result(backdrop.size(), QImage::Format_RGBA8888_Premultiplied);
|
||||
if (result.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
// Pointers taken first: `scanLine` detaches, which would race.
|
||||
const uchar *const lower = backdrop.constBits(), *const upper = source.constBits();
|
||||
uchar *const target = result.bits();
|
||||
const qsizetype lowerStride = backdrop.bytesPerLine(), upperStride = source.bytesPerLine(), targetStride = result.bytesPerLine();
|
||||
std::vector<int> rows;
|
||||
try {
|
||||
rows.resize(size_t(result.height()));
|
||||
} catch (const std::bad_alloc &) {
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
}
|
||||
std::iota(rows.begin(), rows.end(), 0);
|
||||
// Each pixel stands alone: rows blend side by side.
|
||||
PoolMap::blocking(rows, [&](int y) {
|
||||
const uchar *below = lower + y * lowerStride, *above = upper + y * upperStride;
|
||||
uchar *out = target + y * targetStride;
|
||||
for (int x = 0; x < result.width(); ++x, below += 4, above += 4, out += 4) {
|
||||
const float sourceAlpha = above[3] / 255.0f * float(opacity), backdropAlpha = below[3] / 255.0f;
|
||||
if (sourceAlpha <= 0) {
|
||||
std::copy_n(below, 4, out);
|
||||
continue;
|
||||
}
|
||||
Color sourceColor{0, 0, 0}, backdropColor{0, 0, 0};
|
||||
for (int channel = 0; channel < 3; ++channel) {
|
||||
sourceColor[channel] = above[channel] / float(above[3]);
|
||||
backdropColor[channel] = below[3] ? below[channel] / float(below[3]) : 0;
|
||||
}
|
||||
const Color both = mixed(mode, backdropColor, sourceColor);
|
||||
const float alpha = sourceAlpha + backdropAlpha - sourceAlpha * backdropAlpha;
|
||||
out[3] = uchar(std::clamp(int(alpha * 255 + 0.5f), 0, 255));
|
||||
for (int channel = 0; channel < 3; ++channel) {
|
||||
const float value = sourceColor[channel] * sourceAlpha * (1 - backdropAlpha)
|
||||
+ backdropColor[channel] * backdropAlpha * (1 - sourceAlpha)
|
||||
+ both[channel] * sourceAlpha * backdropAlpha;
|
||||
// Premultiplied color never exceeds its alpha.
|
||||
out[channel] = uchar(std::clamp(int(value * 255 + 0.5f), 0, int(out[3])));
|
||||
}
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "Document/LayerAppearance.h"
|
||||
#include <QImage>
|
||||
|
||||
// Hue, Saturation, Color, Luminosity: PDF blend modes QPainter lacks.
|
||||
namespace HslBlend {
|
||||
bool handles(LayerBlendMode mode);
|
||||
// Source over backdrop, same size, both RGBA8888 premultiplied.
|
||||
QImage blend(const QImage &backdrop, const QImage &source, LayerBlendMode mode, double opacity);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
#include "Document/EditorSession.h"
|
||||
#include "Rendering/InlineTextEditor.h"
|
||||
#include "Rendering/TextLayout.h"
|
||||
#include <QKeyEvent>
|
||||
#include <QTextBoundaryFinder>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace {
|
||||
bool isArrow(int key)
|
||||
{
|
||||
return key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down;
|
||||
}
|
||||
|
||||
// What a text view types, as Qt's text fields judge.
|
||||
bool isTyping(const QKeyEvent &event)
|
||||
{
|
||||
const QString text = event.text();
|
||||
if (text.isEmpty())
|
||||
return false;
|
||||
const QChar first = text.at(0);
|
||||
if (first.category() == QChar::Other_Format)
|
||||
return true;
|
||||
// Ctrl alone is a command; AltGr (Ctrl with Alt) types.
|
||||
if (event.modifiers() == Qt::ControlModifier || event.modifiers() == (Qt::ShiftModifier | Qt::ControlModifier))
|
||||
return false;
|
||||
return first.isPrint() || first.category() == QChar::Other_PrivateUse || (first.isHighSurrogate() && text.size() > 1 && text.at(1).isLowSurrogate());
|
||||
}
|
||||
}
|
||||
|
||||
bool InlineTextEditor::claims(const QKeyEvent &event)
|
||||
{
|
||||
// The text view's shortcuts, and the fills' text meanings.
|
||||
constexpr std::array standard{QKeySequence::SelectAll, QKeySequence::Copy, QKeySequence::Cut, QKeySequence::Paste, QKeySequence::Undo, QKeySequence::Redo};
|
||||
if (std::any_of(standard.begin(), standard.end(), [&](QKeySequence::StandardKey key) { return event.matches(key); }))
|
||||
return true;
|
||||
return event.key() == Qt::Key_Backspace;
|
||||
}
|
||||
|
||||
bool InlineTextEditor::keyPress(const QKeyEvent &event)
|
||||
{
|
||||
const Qt::KeyboardModifiers modifiers = event.modifiers();
|
||||
const int key = event.key();
|
||||
const bool enter = key == Qt::Key_Return || key == Qt::Key_Enter;
|
||||
if (key == Qt::Key_Escape) {
|
||||
m_session.cancelText();
|
||||
} else if (modifiers.testFlag(Qt::AltModifier) && isArrow(key)) {
|
||||
// Alt with the arrows sets spacing, as Swift's Option.
|
||||
changeSpacing(key, modifiers.testFlag(Qt::ShiftModifier) ? 10 : 1);
|
||||
} else if (enter && modifiers.testFlag(Qt::ControlModifier)) {
|
||||
m_session.finishText();
|
||||
} else if (erase(event)) {
|
||||
// Deletions come first: X11 binds Alt+Backspace to Undo.
|
||||
} else if (event.matches(QKeySequence::Undo)) {
|
||||
undo();
|
||||
} else if (event.matches(QKeySequence::Redo)) {
|
||||
redo();
|
||||
} else if (event.matches(QKeySequence::Cut)) {
|
||||
cut();
|
||||
} else if (event.matches(QKeySequence::Copy)) {
|
||||
copy();
|
||||
} else if (event.matches(QKeySequence::Paste)) {
|
||||
paste();
|
||||
} else if (event.matches(QKeySequence::SelectAll)) {
|
||||
selectAll();
|
||||
} else if (move(event)) {
|
||||
return true;
|
||||
} else if (enter) {
|
||||
replace(selection(), QStringLiteral("\n"), Edit::typing);
|
||||
} else if (key == Qt::Key_Tab && !(modifiers & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))) {
|
||||
replace(selection(), QStringLiteral("\t"), Edit::typing);
|
||||
} else if (isTyping(event)) {
|
||||
replace(selection(), event.text(), Edit::typing);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deletions: a selection, else what the key reaches.
|
||||
bool InlineTextEditor::erase(const QKeyEvent &event)
|
||||
{
|
||||
const Qt::KeyboardModifiers modifiers = event.modifiers() & ~(Qt::KeypadModifier | Qt::ShiftModifier);
|
||||
const bool back = event.key() == Qt::Key_Backspace, forward = event.key() == Qt::Key_Delete;
|
||||
if ((!back && !forward) || (modifiers != Qt::NoModifier && modifiers != Qt::AltModifier && modifiers != Qt::ControlModifier))
|
||||
return false;
|
||||
// Shift+Delete is X11's Cut.
|
||||
if (forward && event.matches(QKeySequence::Cut))
|
||||
return false;
|
||||
TextRange range = selection();
|
||||
if (range.isEmpty()) {
|
||||
// Alt reaches a word, Ctrl the line, as Swift's fills.
|
||||
const int reach = modifiers == Qt::AltModifier ? (back ? previousWordStart(m_position) : nextWordEnd(m_position))
|
||||
: modifiers == Qt::ControlModifier ? lineBound(forward)
|
||||
: back ? previousCharacter(m_position)
|
||||
: nextCharacter(m_position);
|
||||
range = {std::min(reach, m_position), std::max(reach, m_position)};
|
||||
}
|
||||
if (!range.isEmpty())
|
||||
replace(range, QString(), Edit::deleting);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Qt's movement keys, as the app's text fields take them.
|
||||
bool InlineTextEditor::move(const QKeyEvent &event)
|
||||
{
|
||||
const TextRange range = selection();
|
||||
const auto matches = [&](QKeySequence::StandardKey move, QKeySequence::StandardKey select) {
|
||||
return event.matches(move) ? std::optional(false) : event.matches(select) ? std::optional(true) : std::nullopt;
|
||||
};
|
||||
// Right goes back in right-to-left text, as Qt's fields.
|
||||
const bool rtl = rightToLeft();
|
||||
const int back = rtl ? nextCharacter(m_position) : previousCharacter(m_position);
|
||||
const int on = rtl ? previousCharacter(m_position) : nextCharacter(m_position);
|
||||
if (const std::optional<bool> extend = matches(QKeySequence::MoveToNextChar, QKeySequence::SelectNextChar))
|
||||
moveTo(!*extend && !range.isEmpty() ? (rtl ? range.start : range.end) : on, *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToPreviousChar, QKeySequence::SelectPreviousChar))
|
||||
moveTo(!*extend && !range.isEmpty() ? (rtl ? range.end : range.start) : back, *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToNextWord, QKeySequence::SelectNextWord))
|
||||
moveTo(rtl ? previousWordStart(m_position) : nextWordEnd(m_position), *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToPreviousWord, QKeySequence::SelectPreviousWord))
|
||||
moveTo(rtl ? nextWordEnd(m_position) : previousWordStart(m_position), *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToNextLine, QKeySequence::SelectNextLine))
|
||||
moveTo(verticalTarget(1), *extend, true);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToPreviousLine, QKeySequence::SelectPreviousLine))
|
||||
moveTo(verticalTarget(-1), *extend, true);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToStartOfLine, QKeySequence::SelectStartOfLine))
|
||||
moveTo(lineBound(false), *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToEndOfLine, QKeySequence::SelectEndOfLine))
|
||||
moveTo(lineBound(true), *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToStartOfDocument, QKeySequence::SelectStartOfDocument))
|
||||
moveTo(0, *extend);
|
||||
else if (const std::optional<bool> extend = matches(QKeySequence::MoveToEndOfDocument, QKeySequence::SelectEndOfDocument))
|
||||
moveTo(int(style().content.size()), *extend);
|
||||
else
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Whether the caret's paragraph reads right to left.
|
||||
bool InlineTextEditor::rightToLeft() const
|
||||
{
|
||||
const QString &content = style().content;
|
||||
int start = m_position, end = m_position;
|
||||
while (start > 0 && !separates(content.at(start - 1)))
|
||||
--start;
|
||||
while (end < content.size() && !separates(content.at(end)))
|
||||
++end;
|
||||
return QStringView(content).mid(start, end - start).isRightToLeft();
|
||||
}
|
||||
|
||||
// Cocoa's paragraph separators, as `TextLines` parts paragraphs.
|
||||
bool InlineTextEditor::separates(QChar character)
|
||||
{
|
||||
return character == u'\n' || character == u'\r' || character == QChar::ParagraphSeparator;
|
||||
}
|
||||
|
||||
TextRange InlineTextEditor::spanning(int anchor, int position)
|
||||
{
|
||||
return {std::min(anchor, position), std::max(anchor, position)};
|
||||
}
|
||||
|
||||
TextRange InlineTextEditor::selection() const
|
||||
{
|
||||
return spanning(m_anchor, m_position);
|
||||
}
|
||||
|
||||
void InlineTextEditor::replace(TextRange range, const QString &text, std::optional<Edit> edit)
|
||||
{
|
||||
const QString content = style().content;
|
||||
// Swift's shouldChangeTextIn: 100,000 UTF-16 units at most.
|
||||
if (content.size() - (range.end - range.start) + text.size() > 100'000)
|
||||
return;
|
||||
if (!edit || edit != m_lastEdit)
|
||||
m_undo.push_back(m_composing ? m_composing->before : Snapshot{content, m_anchor, m_position});
|
||||
m_redo.clear();
|
||||
m_lastEdit = edit;
|
||||
m_composing.reset();
|
||||
m_anchor = m_position = range.start + int(text.size());
|
||||
publish(QString(content).replace(range.start, range.end - range.start, text));
|
||||
}
|
||||
|
||||
// Swift's textDidChange: the draft takes the text view's string.
|
||||
void InlineTextEditor::publish(const QString &content)
|
||||
{
|
||||
// An edit ends a drag or resize, like a press.
|
||||
release();
|
||||
TextDraft draft = m_session.textDraft().value();
|
||||
draft.style.content = content;
|
||||
m_goalX.reset();
|
||||
showCaret();
|
||||
m_session.setTextDraft(draft);
|
||||
}
|
||||
|
||||
void InlineTextEditor::moveTo(int position, bool extend, bool keepGoal)
|
||||
{
|
||||
m_position = position;
|
||||
if (!extend)
|
||||
m_anchor = position;
|
||||
if (!keepGoal)
|
||||
m_goalX.reset();
|
||||
m_lastEdit.reset();
|
||||
showCaret();
|
||||
updateInputMethod();
|
||||
}
|
||||
|
||||
void InlineTextEditor::restore(std::vector<Snapshot> &from, std::vector<Snapshot> &to)
|
||||
{
|
||||
if (from.empty())
|
||||
return;
|
||||
to.push_back(m_composing ? m_composing->before : Snapshot{style().content, m_anchor, m_position});
|
||||
const Snapshot snapshot = from.back();
|
||||
from.pop_back();
|
||||
m_lastEdit.reset();
|
||||
m_composing.reset();
|
||||
m_anchor = snapshot.anchor;
|
||||
m_position = snapshot.position;
|
||||
publish(snapshot.content);
|
||||
}
|
||||
|
||||
void InlineTextEditor::undo()
|
||||
{
|
||||
restore(m_undo, m_redo);
|
||||
}
|
||||
|
||||
void InlineTextEditor::redo()
|
||||
{
|
||||
restore(m_redo, m_undo);
|
||||
}
|
||||
|
||||
void InlineTextEditor::changeSpacing(int key, double step)
|
||||
{
|
||||
// A resize would write back the style it began with.
|
||||
release();
|
||||
m_session.changeTextStyle([key, step](LayerTextStyle &style) {
|
||||
if (key == Qt::Key_Left || key == Qt::Key_Right)
|
||||
style.tracking += key == Qt::Key_Left ? -step : step;
|
||||
// Up closes the lines, counting from Auto's height.
|
||||
else
|
||||
style.leading = key == Qt::Key_Up ? std::max(1.0, style.lineHeight() - step) : style.lineHeight() + step;
|
||||
});
|
||||
}
|
||||
|
||||
int InlineTextEditor::nextCharacter(int position) const
|
||||
{
|
||||
QTextBoundaryFinder finder(QTextBoundaryFinder::Grapheme, style().content);
|
||||
finder.setPosition(position);
|
||||
const qsizetype next = finder.toNextBoundary();
|
||||
return next < 0 ? int(style().content.size()) : int(next);
|
||||
}
|
||||
|
||||
int InlineTextEditor::previousCharacter(int position) const
|
||||
{
|
||||
QTextBoundaryFinder finder(QTextBoundaryFinder::Grapheme, style().content);
|
||||
finder.setPosition(position);
|
||||
return int(std::max<qsizetype>(finder.toPreviousBoundary(), 0));
|
||||
}
|
||||
|
||||
// NSTextView's word moves: to a word's end, or its start.
|
||||
int InlineTextEditor::nextWordEnd(int position) const
|
||||
{
|
||||
QTextBoundaryFinder finder(QTextBoundaryFinder::Word, style().content);
|
||||
finder.setPosition(position);
|
||||
for (qsizetype at = finder.toNextBoundary(); at >= 0; at = finder.toNextBoundary()) {
|
||||
if (finder.boundaryReasons().testFlag(QTextBoundaryFinder::EndOfItem))
|
||||
return int(at);
|
||||
}
|
||||
return int(style().content.size());
|
||||
}
|
||||
|
||||
int InlineTextEditor::previousWordStart(int position) const
|
||||
{
|
||||
QTextBoundaryFinder finder(QTextBoundaryFinder::Word, style().content);
|
||||
finder.setPosition(position);
|
||||
for (qsizetype at = finder.toPreviousBoundary(); at >= 0; at = finder.toPreviousBoundary()) {
|
||||
if (finder.boundaryReasons().testFlag(QTextBoundaryFinder::StartOfItem))
|
||||
return int(at);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The caret's line's start or end, else the text's.
|
||||
int InlineTextEditor::lineBound(bool end) const
|
||||
{
|
||||
const std::optional<int> line = m_lines->lineOf(m_position);
|
||||
if (!line)
|
||||
return end ? int(style().content.size()) : 0;
|
||||
return end ? m_lines->lineEnd(*line) : m_lines->lineStart(*line);
|
||||
}
|
||||
|
||||
// Above line one: the start; below the last: the end.
|
||||
int InlineTextEditor::verticalTarget(int direction)
|
||||
{
|
||||
const std::optional<int> line = m_lines->lineOf(m_position);
|
||||
if (!line)
|
||||
return m_position;
|
||||
const double x = m_goalX.value_or(m_lines->caret(m_position).value().x());
|
||||
m_goalX = x;
|
||||
const int target = *line + direction;
|
||||
if (target < 0)
|
||||
return 0;
|
||||
if (target >= m_lines->lineCount())
|
||||
return int(style().content.size());
|
||||
return m_lines->position(target, x);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
#include "Document/EditorSession.h"
|
||||
#include "Rendering/InlineTextEditor.h"
|
||||
#include "Rendering/TextLayout.h"
|
||||
#include <QClipboard>
|
||||
#include <QGuiApplication>
|
||||
#include <QInputMethodEvent>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
|
||||
void InlineTextEditor::cut()
|
||||
{
|
||||
const Snapshot around = plain();
|
||||
if (spanning(around.anchor, around.position).isEmpty())
|
||||
return;
|
||||
copy();
|
||||
change(QString());
|
||||
}
|
||||
|
||||
void InlineTextEditor::copy() const
|
||||
{
|
||||
const Snapshot around = plain();
|
||||
const TextRange range = spanning(around.anchor, around.position);
|
||||
if (!range.isEmpty())
|
||||
QGuiApplication::clipboard()->setText(around.content.mid(range.start, range.end - range.start));
|
||||
}
|
||||
|
||||
// Swift's paste is pasteAsPlainText.
|
||||
void InlineTextEditor::paste()
|
||||
{
|
||||
const QString text = QGuiApplication::clipboard()->text();
|
||||
if (!text.isEmpty())
|
||||
change(text);
|
||||
}
|
||||
|
||||
void InlineTextEditor::selectAll()
|
||||
{
|
||||
// Around a preedit, which follows the cursor to the end.
|
||||
if (m_composing) {
|
||||
m_lastEdit.reset();
|
||||
const QString text = plain().content;
|
||||
settle(text, 0, int(text.size()));
|
||||
return;
|
||||
}
|
||||
m_anchor = 0;
|
||||
moveTo(int(style().content.size()), true);
|
||||
}
|
||||
|
||||
// The text around a preedit, which Qt's fields keep apart.
|
||||
InlineTextEditor::Snapshot InlineTextEditor::plain() const
|
||||
{
|
||||
if (!m_composing)
|
||||
return {style().content, m_anchor, m_position};
|
||||
const TextRange marked = m_composing->marked;
|
||||
return {QString(style().content).remove(marked.start, marked.end - marked.start), m_composing->anchor, marked.start};
|
||||
}
|
||||
|
||||
// A clipboard command replaces the selection around a preedit.
|
||||
void InlineTextEditor::change(const QString &text)
|
||||
{
|
||||
const Snapshot around = plain();
|
||||
const TextRange range = spanning(around.anchor, around.position);
|
||||
if (style().content.size() - (range.end - range.start) + text.size() > 100'000)
|
||||
return;
|
||||
m_undo.push_back(around);
|
||||
m_redo.clear();
|
||||
m_lastEdit.reset();
|
||||
const int cursor = range.start + int(text.size());
|
||||
settle(QString(around.content).replace(range.start, range.end - range.start, text), cursor, cursor);
|
||||
}
|
||||
|
||||
// The preedit returns to the cursor, as Qt shows it.
|
||||
void InlineTextEditor::settle(QString text, int anchor, int cursor)
|
||||
{
|
||||
if (m_composing) {
|
||||
const TextRange marked = m_composing->marked;
|
||||
const QString preedit = style().content.mid(marked.start, marked.end - marked.start);
|
||||
const int caret = m_position - marked.start;
|
||||
m_composing->before = {text, anchor, cursor};
|
||||
m_composing->anchor = anchor;
|
||||
m_composing->marked = {cursor, cursor + int(preedit.size())};
|
||||
text.insert(cursor, preedit);
|
||||
anchor = cursor = cursor + caret;
|
||||
}
|
||||
m_anchor = anchor;
|
||||
m_position = cursor;
|
||||
publish(text);
|
||||
}
|
||||
|
||||
// Marked text sits in the content, as in NSTextView's storage.
|
||||
void InlineTextEditor::inputMethod(const QInputMethodEvent &event)
|
||||
{
|
||||
const QString commit = event.commitString(), preedit = event.preeditString();
|
||||
const QList<QInputMethodEvent::Attribute> attributes = event.attributes();
|
||||
const auto selecting = std::find_if(attributes.begin(), attributes.end(), [](const auto &attribute) { return attribute.type == QInputMethodEvent::Selection; });
|
||||
// Qt's steps, on the text without the preedit.
|
||||
QString text = style().content, shown;
|
||||
int cursor = m_position, anchor = m_anchor;
|
||||
if (m_composing) {
|
||||
const TextRange marked = m_composing->marked;
|
||||
shown = text.mid(marked.start, marked.end - marked.start);
|
||||
text.remove(marked.start, marked.end - marked.start);
|
||||
cursor = marked.start;
|
||||
anchor = m_composing->anchor;
|
||||
}
|
||||
const bool input = !commit.isEmpty() || preedit != shown || event.replacementLength() > 0;
|
||||
if (!input && !m_composing && selecting == attributes.end())
|
||||
return;
|
||||
// Input takes the selection first, as Qt's fields.
|
||||
const TextRange selected{std::min(anchor, cursor), std::max(anchor, cursor)};
|
||||
const bool takes = input && !selected.isEmpty();
|
||||
if (takes) {
|
||||
text.remove(selected.start, selected.end - selected.start);
|
||||
cursor = selected.start;
|
||||
}
|
||||
// Where Qt leaves the cursor when nothing commits.
|
||||
int after = cursor;
|
||||
if (event.replacementStart() <= 0)
|
||||
after += int(commit.size()) - std::min(-event.replacementStart(), event.replacementLength());
|
||||
const int start = std::clamp(cursor + event.replacementStart(), 0, int(text.size()));
|
||||
const int end = event.replacementLength() > 0 && start + event.replacementLength() <= text.size() ? start + event.replacementLength() : start;
|
||||
if (text.size() - (end - start) + commit.size() + preedit.size() > 100'000)
|
||||
return;
|
||||
// A preedit records nothing; what lands makes a typing step.
|
||||
const Snapshot before = m_composing ? m_composing->before : Snapshot{style().content, m_anchor, m_position};
|
||||
const bool lands = takes || end > start || !commit.isEmpty();
|
||||
if (lands) {
|
||||
if (m_lastEdit != Edit::typing)
|
||||
m_undo.push_back(before);
|
||||
m_redo.clear();
|
||||
m_lastEdit = Edit::typing;
|
||||
}
|
||||
text.replace(start, end - start, commit);
|
||||
cursor = commit.isEmpty() ? std::clamp(after, 0, int(text.size())) : start + int(commit.size());
|
||||
if (input)
|
||||
anchor = cursor;
|
||||
// The input method's own move ends a typing run.
|
||||
if (selecting != attributes.end()) {
|
||||
cursor = std::clamp(selecting->start + selecting->length, 0, int(text.size()));
|
||||
anchor = selecting->length ? std::clamp(selecting->start, 0, int(text.size())) : cursor;
|
||||
m_lastEdit.reset();
|
||||
}
|
||||
m_composing.reset();
|
||||
if (preedit.isEmpty()) {
|
||||
m_anchor = anchor;
|
||||
m_position = cursor;
|
||||
} else {
|
||||
compose(preedit, attributes, lands ? Snapshot{text, anchor, cursor} : before, anchor, text, cursor);
|
||||
}
|
||||
publish(text);
|
||||
}
|
||||
|
||||
// The preedit goes in at the cursor, with Qt's attributes.
|
||||
void InlineTextEditor::compose(const QString &preedit, const QList<QInputMethodEvent::Attribute> &attributes, const Snapshot &before, int anchor,
|
||||
QString &text, int cursor)
|
||||
{
|
||||
const int length = int(preedit.size());
|
||||
Composing composing{.marked = {cursor, cursor + length}, .anchor = anchor, .before = before};
|
||||
int caret = length;
|
||||
for (const QInputMethodEvent::Attribute &attribute : attributes) {
|
||||
const int start = std::clamp(attribute.start, 0, length);
|
||||
if (attribute.type == QInputMethodEvent::Cursor) {
|
||||
caret = start;
|
||||
composing.caretHidden = attribute.length == 0;
|
||||
if (attribute.value.typeId() == QMetaType::QColor)
|
||||
composing.caretColour = attribute.value.value<QColor>();
|
||||
} else if (attribute.type == QInputMethodEvent::TextFormat) {
|
||||
// Qt's fields pass over a format that is not one.
|
||||
const QTextCharFormat format = qvariant_cast<QTextFormat>(attribute.value).toCharFormat();
|
||||
const int end = std::clamp(attribute.start + attribute.length, start, length);
|
||||
if (format.isValid())
|
||||
composing.formats << QTextLayout::FormatRange{start, end - start, format};
|
||||
}
|
||||
}
|
||||
text.insert(cursor, preedit);
|
||||
m_anchor = m_position = cursor + caret;
|
||||
m_composing = composing;
|
||||
}
|
||||
|
||||
// The selection shown: the input method's keeps beside the preedit.
|
||||
TextRange InlineTextEditor::shownSelection() const
|
||||
{
|
||||
if (!m_composing)
|
||||
return selection();
|
||||
const TextRange marked = m_composing->marked;
|
||||
const int length = marked.end - marked.start;
|
||||
const TextRange range = spanning(m_composing->anchor, marked.start);
|
||||
return {range.start < marked.start ? range.start : range.start + length, range.end <= marked.start ? range.end : range.end + length};
|
||||
}
|
||||
|
||||
QVariant InlineTextEditor::inputMethodQuery(Qt::InputMethodQuery query) const
|
||||
{
|
||||
const QString &content = style().content;
|
||||
const std::optional<TextRange> marked = this->marked();
|
||||
const int cursor = marked ? marked->start : m_position, anchor = m_composing ? m_composing->anchor : m_anchor;
|
||||
const QString surrounding = marked ? QString(content).remove(marked->start, marked->end - marked->start) : content;
|
||||
switch (query) {
|
||||
case Qt::ImEnabled:
|
||||
return true;
|
||||
case Qt::ImHints:
|
||||
return int(Qt::ImhMultiLine);
|
||||
case Qt::ImFont:
|
||||
return TextLayout::font(style());
|
||||
case Qt::ImCursorRectangle: {
|
||||
const double padding = LayerTextStyle::padding;
|
||||
const QRectF caret = m_lines->caret(m_position).value_or(QRectF(0, 0, 1, style().lineHeight())).translated(padding, padding);
|
||||
return textTransform().mapRect(caret);
|
||||
}
|
||||
case Qt::ImSurroundingText:
|
||||
return surrounding;
|
||||
case Qt::ImCursorPosition:
|
||||
return cursor;
|
||||
case Qt::ImAnchorPosition:
|
||||
return anchor;
|
||||
case Qt::ImCurrentSelection:
|
||||
return surrounding.mid(spanning(anchor, cursor).start, std::abs(anchor - cursor));
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
#include "Document/EditorSession.h"
|
||||
#include "Document/Selection.h"
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include "Rendering/InlineTextEditor.h"
|
||||
#include <QGuiApplication>
|
||||
#include <QInputMethod>
|
||||
#include <QPainter>
|
||||
#include <QTextBoundaryFinder>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
|
||||
// Swift's hitTest: the handles' bands, then the box.
|
||||
bool InlineTextEditor::press(QPointF point, Qt::KeyboardModifiers modifiers, int clicks)
|
||||
{
|
||||
// A press starts afresh: Qt can lose a release.
|
||||
release();
|
||||
const std::optional<int> handle = handleAt(point);
|
||||
const QRectF box(QPointF(0, 0), m_logicalSize);
|
||||
const QPointF local = boxTransform().inverted().map(point);
|
||||
if (!handle && !box.contains(local))
|
||||
return false;
|
||||
if (handle) {
|
||||
land();
|
||||
beginResize(*handle, point);
|
||||
return true;
|
||||
}
|
||||
// A click in the padding, the editor's own, does nothing.
|
||||
const double padding = LayerTextStyle::padding;
|
||||
if (box.adjusted(padding, padding, -padding, -padding).contains(local))
|
||||
pressText(point, modifiers, clicks);
|
||||
return true;
|
||||
}
|
||||
|
||||
// NSTextView's clicks: a caret, a word, a paragraph; Shift extends.
|
||||
void InlineTextEditor::pressText(QPointF point, Qt::KeyboardModifiers modifiers, int clicks)
|
||||
{
|
||||
land();
|
||||
m_selecting = true;
|
||||
// Shift extends by the last click's unit while that stands.
|
||||
if (clicks == 1 && modifiers.testFlag(Qt::ShiftModifier)) {
|
||||
if (!m_tracking || m_tracking->anchor != m_anchor || m_tracking->position != m_position)
|
||||
m_tracking = Tracking{{m_anchor, m_anchor}, 1, m_anchor, m_position};
|
||||
drag(point);
|
||||
return;
|
||||
}
|
||||
const int position = positionAt(point, false);
|
||||
const TextRange unit = clicks == 1 ? TextRange{position, position} : unitAt(positionAt(point, true), clicks);
|
||||
m_anchor = unit.start;
|
||||
moveTo(unit.end, true);
|
||||
m_tracking = Tracking{unit, clicks, m_anchor, m_position};
|
||||
}
|
||||
|
||||
// A drag selects by its click's unit from its start.
|
||||
bool InlineTextEditor::drag(QPointF point)
|
||||
{
|
||||
if (m_resize) {
|
||||
resizeTo(point);
|
||||
return true;
|
||||
}
|
||||
if (!m_selecting)
|
||||
return false;
|
||||
Tracking &tracking = m_tracking.value();
|
||||
const int position = positionAt(point, false);
|
||||
const TextRange unit = tracking.clicks == 1 ? TextRange{position, position} : unitAt(positionAt(point, true), tracking.clicks);
|
||||
if (unit.start < tracking.origin.start) {
|
||||
m_anchor = tracking.origin.end;
|
||||
moveTo(unit.start, true);
|
||||
} else {
|
||||
m_anchor = tracking.origin.start;
|
||||
moveTo(unit.end, true);
|
||||
}
|
||||
tracking.anchor = m_anchor;
|
||||
tracking.position = m_position;
|
||||
return true;
|
||||
}
|
||||
|
||||
// The unit stays for Shift; the press itself ends.
|
||||
void InlineTextEditor::release()
|
||||
{
|
||||
m_resize.reset();
|
||||
m_selecting = false;
|
||||
}
|
||||
|
||||
std::optional<QCursor> InlineTextEditor::cursorAt(QPointF point) const
|
||||
{
|
||||
const std::optional<int> handle = m_resize ? std::optional(m_resize->handle) : handleAt(point);
|
||||
if (!handle)
|
||||
return std::nullopt;
|
||||
// Swift's frame positions, turned with the box by eighths.
|
||||
static constexpr std::array<int, 8> positions{0, 1, 2, 3, 0, 1, 2, 3};
|
||||
static constexpr std::array shapes{Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor, Qt::SizeHorCursor};
|
||||
const std::optional<TextDraft> &draft = m_session.textDraft();
|
||||
const double rotation = draft && draft->transform ? draft->transform->rotation : 0;
|
||||
// Reduced first: Swift's Int holds turns an int cannot.
|
||||
const int turns = (int(std::round(std::fmod(rotation, 360) / 45)) % 8 + 8) % 8;
|
||||
return QCursor(shapes[size_t((positions[size_t(*handle)] + turns) % 4)]);
|
||||
}
|
||||
|
||||
// Swift's handle(at:): a band along each edge, in box units.
|
||||
std::optional<int> InlineTextEditor::handleAt(QPointF point) const
|
||||
{
|
||||
const QPointF local = boxTransform().inverted().map(point);
|
||||
const double width = m_logicalSize.width(), height = m_logicalSize.height();
|
||||
// Ten points to a six-point handle, as the Move box.
|
||||
const double reach = std::min(m_handleSize * 10 / 6, std::min(width, height) / 3);
|
||||
if (local.x() < -reach || local.x() > width + reach || local.y() < -reach || local.y() > height + reach)
|
||||
return std::nullopt;
|
||||
const bool left = local.x() <= reach, right = local.x() >= width - reach;
|
||||
const bool top = local.y() <= reach, bottom = local.y() >= height - reach;
|
||||
if (left && top)
|
||||
return 0;
|
||||
if (right && top)
|
||||
return 2;
|
||||
if (right && bottom)
|
||||
return 4;
|
||||
if (left && bottom)
|
||||
return 6;
|
||||
if (top)
|
||||
return 1;
|
||||
if (right)
|
||||
return 3;
|
||||
if (bottom)
|
||||
return 5;
|
||||
if (left)
|
||||
return 7;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// The text position under a point, through the text's mirror.
|
||||
int InlineTextEditor::positionAt(QPointF point, bool onCharacter) const
|
||||
{
|
||||
if (m_lines->lineCount() == 0)
|
||||
return 0;
|
||||
const double padding = LayerTextStyle::padding;
|
||||
const QPointF text = textTransform().inverted().map(point) - QPointF(padding, padding);
|
||||
// Above the lines is the start, below them the end.
|
||||
if (text.y() < 0)
|
||||
return 0;
|
||||
// A double first: a far drag passes int's range.
|
||||
const double line = std::floor(text.y() / style().lineHeight());
|
||||
if (line >= m_lines->lineCount())
|
||||
return m_lines->lineEnd(m_lines->lineCount() - 1);
|
||||
return onCharacter ? m_lines->character(int(line), text.x()) : m_lines->position(int(line), text.x());
|
||||
}
|
||||
|
||||
// A double click's word; a triple click's paragraph and break.
|
||||
TextRange InlineTextEditor::unitAt(int position, int clicks) const
|
||||
{
|
||||
const QString &content = style().content;
|
||||
if (clicks == 2) {
|
||||
// Past the text, its last word; after a break, none.
|
||||
const QChar last = content.isEmpty() ? QChar() : content.back();
|
||||
if (content.isEmpty() || (position == content.size() && (separates(last) || last == QChar::LineSeparator)))
|
||||
return {position, position};
|
||||
QTextBoundaryFinder finder(QTextBoundaryFinder::Word, content);
|
||||
finder.setPosition(std::min(position, int(content.size()) - 1));
|
||||
if (!finder.isAtBoundary())
|
||||
finder.toPreviousBoundary();
|
||||
const int start = int(finder.position());
|
||||
return {start, int(finder.toNextBoundary())};
|
||||
}
|
||||
int start = position, end = position;
|
||||
while (start > 0 && !separates(content.at(start - 1)))
|
||||
--start;
|
||||
while (end < content.size() && !separates(content.at(end)))
|
||||
++end;
|
||||
if (end < content.size())
|
||||
end += content.mid(end, 2) == QStringLiteral("\r\n") ? 2 : 1;
|
||||
return {start, end};
|
||||
}
|
||||
|
||||
// Clicks commit a preedit, as Qt asks, or land it.
|
||||
void InlineTextEditor::land()
|
||||
{
|
||||
if (!m_composing)
|
||||
return;
|
||||
QGuiApplication::inputMethod()->commit();
|
||||
if (!m_composing)
|
||||
return;
|
||||
QInputMethodEvent commit;
|
||||
commit.setCommitString(style().content.mid(m_composing->marked.start, m_composing->marked.end - m_composing->marked.start));
|
||||
inputMethod(commit);
|
||||
}
|
||||
|
||||
// Swift's handle press: point text becomes a box, as sized.
|
||||
void InlineTextEditor::beginResize(int handle, QPointF point)
|
||||
{
|
||||
TextDraft draft = m_session.textDraft().value();
|
||||
if (!draft.style.boxSize) {
|
||||
draft.style.boxSize = m_logicalSize;
|
||||
draft.transform = m_shownTransform;
|
||||
m_session.setTextDraft(draft);
|
||||
}
|
||||
m_resize = Resize{handle, draft, m_shownTransform, m_session.viewport.documentPoint(point, m_session.document().value().size())};
|
||||
}
|
||||
|
||||
// Swift's mouseDragged: the box in its frame, 16 pixels least.
|
||||
void InlineTextEditor::resizeTo(QPointF point)
|
||||
{
|
||||
const Resize &resize = m_resize.value();
|
||||
const LayerTransform &old = resize.transform;
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, m_session.document().value().size());
|
||||
const double dx = pixel.x() - resize.start.x(), dy = pixel.y() - resize.start.y();
|
||||
const double localX = dx * std::cos(old.radians()) + dy * std::sin(old.radians());
|
||||
const double localY = -dx * std::sin(old.radians()) + dy * std::cos(old.radians());
|
||||
const QPointF unit = LayerTransform::handles[size_t(resize.handle)];
|
||||
const QSizeF source = resize.draft.style.boxSize.value();
|
||||
const double minWidth = 16 * old.size.width() / source.width(), minHeight = 16 * old.size.height() / source.height();
|
||||
double left = 0, top = 0, right = old.size.width(), bottom = old.size.height();
|
||||
if (unit.x() == 0)
|
||||
left = std::min(localX, right - minWidth);
|
||||
if (unit.x() == 1)
|
||||
right = std::max(left + minWidth, right + localX);
|
||||
if (unit.y() == 0)
|
||||
top = std::min(localY, bottom - minHeight);
|
||||
if (unit.y() == 1)
|
||||
bottom = std::max(top + minHeight, bottom + localY);
|
||||
TextDraft draft = resize.draft;
|
||||
draft.style.boxSize = QSizeF(std::round((right - left) * source.width() / old.size.width()), std::round((bottom - top) * source.height() / old.size.height()));
|
||||
if (!draft.style.boxIsValid())
|
||||
return;
|
||||
LayerTransform transform = old;
|
||||
transform.size = QSizeF(draft.style.boxSize->width() * old.size.width() / source.width(), draft.style.boxSize->height() * old.size.height() / source.height());
|
||||
// The edge not dragged stays put, however the box turns.
|
||||
transform.origin += old.point(QPointF(left / old.size.width(), top / old.size.height())) - transform.point(QPointF(0, 0));
|
||||
if (!transform.isValid())
|
||||
return;
|
||||
draft.origin = transform.origin;
|
||||
draft.transform = transform;
|
||||
m_session.setTextDraft(draft);
|
||||
}
|
||||
|
||||
void CanvasView::pressTextTool(QPointF point, Qt::KeyboardModifiers modifiers, int clicks)
|
||||
{
|
||||
// A box whose release was lost goes first.
|
||||
if (m_textBoxAnchor)
|
||||
endTextGesture();
|
||||
if (m_inlineTextEditor && m_inlineTextEditor->press(point, modifiers, clicks)) {
|
||||
updateCursor();
|
||||
return;
|
||||
}
|
||||
beginTextGesture(point, modifiers, clicks);
|
||||
}
|
||||
|
||||
// Swift's beginTextGesture: open the text there, else draw a box.
|
||||
void CanvasView::beginTextGesture(QPointF point, Qt::KeyboardModifiers modifiers, int clicks)
|
||||
{
|
||||
if (!m_session.finishText())
|
||||
return;
|
||||
const CanvasDocument &document = m_session.document().value();
|
||||
const QPointF pixel = m_session.viewport.documentPoint(point, document.size());
|
||||
const QSet<QUuid> visible = document.effectiveVisibleIDs();
|
||||
for (auto layer = document.layers.rbegin(); layer != document.layers.rend(); ++layer) {
|
||||
if (!visible.contains(layer->id) || !layer->liveText() || !layer->transform.contains(pixel))
|
||||
continue;
|
||||
m_session.selectLayer(QUuid(layer->id));
|
||||
m_session.editActiveText();
|
||||
if (m_inlineTextEditor)
|
||||
m_inlineTextEditor->pressText(point, modifiers, clicks);
|
||||
return;
|
||||
}
|
||||
m_textBoxAnchor = pixel;
|
||||
m_textBoxRect = QRectF(pixel, QSizeF(0, 0));
|
||||
}
|
||||
|
||||
void CanvasView::dragTextGesture(QPointF point)
|
||||
{
|
||||
// Swift's guard: a document undone mid-drag takes nothing.
|
||||
if (!m_session.document())
|
||||
return;
|
||||
const QRectF before = textBoxDraftRect();
|
||||
m_textBoxRect = DragBox::rect(m_textBoxAnchor.value(), m_session.viewport.documentPoint(point, m_session.document().value().size()), false, false);
|
||||
update((before | textBoxDraftRect()).adjusted(-2, -2, 2, 2).toAlignedRect());
|
||||
}
|
||||
|
||||
// Under four pixels a drag is a click: point text.
|
||||
void CanvasView::finishTextGesture()
|
||||
{
|
||||
const QRectF rect = m_textBoxRect.value();
|
||||
endTextGesture();
|
||||
if (rect.width() < 4 && rect.height() < 4)
|
||||
m_session.beginText(rect.topLeft(), true);
|
||||
else
|
||||
m_session.beginText(rect);
|
||||
}
|
||||
|
||||
// The box being drawn goes, repainted away.
|
||||
void CanvasView::endTextGesture()
|
||||
{
|
||||
update(textBoxDraftRect().adjusted(-2, -2, 2, 2).toAlignedRect());
|
||||
m_textBoxAnchor.reset();
|
||||
m_textBoxRect.reset();
|
||||
}
|
||||
|
||||
// Where the box being drawn shows, in view points.
|
||||
QRectF CanvasView::textBoxDraftRect() const
|
||||
{
|
||||
if (!m_textBoxRect || !m_session.document())
|
||||
return QRectF();
|
||||
const QPointF origin = m_session.viewport.viewPoint(m_textBoxRect->topLeft(), m_session.document().value().size());
|
||||
return QRectF(origin, m_textBoxRect->size() * m_session.viewport.pointsPerPixel());
|
||||
}
|
||||
|
||||
void CanvasView::drawTextBoxDraft(QPainter &painter) const
|
||||
{
|
||||
if (!m_textBoxRect)
|
||||
return;
|
||||
painter.save();
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
painter.setPen(QPen(palette().color(QPalette::Highlight), 1));
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawRect(textBoxDraftRect());
|
||||
painter.restore();
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
#include "Rendering/InlineTextEditor.h"
|
||||
#include "Document/EditorSession.h"
|
||||
#include "Rendering/EditorCanvas.h"
|
||||
#include <QApplication>
|
||||
#include <QGuiApplication>
|
||||
#include <QInputMethod>
|
||||
#include <QLineEdit>
|
||||
#include <QPainter>
|
||||
#include <QPointer>
|
||||
#include <QStyleHints>
|
||||
#include <cmath>
|
||||
|
||||
InlineTextEditor::InlineTextEditor(EditorSession &session, QWidget &canvas) : m_session(session), m_canvas(canvas)
|
||||
{
|
||||
// NSTextView's insertion point blinks at the system's pace.
|
||||
m_blink.setObjectName(QStringLiteral("caretBlink"));
|
||||
m_blink.setParent(&canvas);
|
||||
m_blink.setInterval(QGuiApplication::styleHints()->cursorFlashTime() / 2);
|
||||
QObject::connect(&m_blink, &QTimer::timeout, &m_blink, [this] {
|
||||
m_caretShown = !m_caretShown;
|
||||
repaint();
|
||||
});
|
||||
}
|
||||
|
||||
void InlineTextEditor::synchronize(const TextDraft &draft)
|
||||
{
|
||||
// A draft needs a document, and holds it open.
|
||||
const CanvasDocument &document = m_session.document().value();
|
||||
const bool fresh = m_draftID != draft.id;
|
||||
m_draftID = draft.id;
|
||||
// Another draft starts afresh: no steps, nothing composing.
|
||||
if (fresh) {
|
||||
m_undo.clear();
|
||||
m_redo.clear();
|
||||
m_lastEdit.reset();
|
||||
m_composing.reset();
|
||||
}
|
||||
const LayerTextStyle &style = draft.style;
|
||||
// Point text has no box: it is what is typed.
|
||||
m_logicalSize = EditorSession::textBoxSize(style);
|
||||
LayerTransform transform = draft.transform.value_or(LayerTransform{.origin = draft.origin, .size = m_logicalSize});
|
||||
// Point text grows at its layer's scale, corner kept.
|
||||
const int index = draft.layerID ? indexOf(document.layers, *draft.layerID) : -1;
|
||||
if (!style.boxSize && draft.transform && index >= 0 && document.layers[size_t(index)].asset) {
|
||||
const double factor = transform.size.width() / document.layers[size_t(index)].asset->size().width();
|
||||
const QPointF anchor = transform.point(QPointF(0, 0));
|
||||
transform.size = m_logicalSize * factor;
|
||||
transform.origin += anchor - transform.point(QPointF(0, 0));
|
||||
}
|
||||
m_shownTransform = transform;
|
||||
const double scale = m_session.viewport.pointsPerPixel();
|
||||
m_handleSize = std::max(2.0, 6 / std::max(0.01, scale * transform.size.width() / m_logicalSize.width()));
|
||||
// Content from elsewhere clamps the selection, as Swift's.
|
||||
if (m_shownStyle != style && !m_composing) {
|
||||
m_anchor = std::min(m_anchor, int(style.content.size()));
|
||||
m_position = std::min(m_position, int(style.content.size()));
|
||||
// Swift sets the selection anew: a click's unit goes.
|
||||
m_tracking.reset();
|
||||
m_selecting = false;
|
||||
}
|
||||
m_shownStyle = style;
|
||||
const double padding = LayerTextStyle::padding;
|
||||
m_lines = std::make_unique<TextLines>(
|
||||
style, QSizeF(std::max(1.0, m_logicalSize.width() - 2 * padding), std::max(1.0, m_logicalSize.height() - 2 * padding)));
|
||||
updateInputMethod();
|
||||
if (!fresh)
|
||||
return;
|
||||
// The text view takes the keys, sparing a text field.
|
||||
QMetaObject::invokeMethod(
|
||||
&m_canvas,
|
||||
[canvas = QPointer<QWidget>(&m_canvas), session = &m_session, id = draft.id] {
|
||||
if (!canvas || !session->textDraft() || session->textDraft().value().id != id || qobject_cast<QLineEdit *>(QApplication::focusWidget()))
|
||||
return;
|
||||
canvas->setFocus(Qt::OtherFocusReason);
|
||||
},
|
||||
Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
QTransform InlineTextEditor::boxTransform() const
|
||||
{
|
||||
const QPointF origin = m_session.viewport.documentRect(m_session.document().value().size()).topLeft();
|
||||
const double scale = m_session.viewport.pointsPerPixel();
|
||||
const QPointF centre = m_shownTransform.center();
|
||||
const QSizeF size = m_shownTransform.size;
|
||||
// Unit square to document as LayerTransform::point, then view.
|
||||
const QTransform layer = QTransform::fromTranslate(centre.x(), centre.y())
|
||||
.rotate(m_shownTransform.rotation)
|
||||
.translate(-size.width() / 2, -size.height() / 2)
|
||||
.scale(size.width() / m_logicalSize.width(), size.height() / m_logicalSize.height());
|
||||
return layer * QTransform::fromTranslate(origin.x(), origin.y()).scale(scale, scale);
|
||||
}
|
||||
|
||||
QTransform InlineTextEditor::textTransform() const
|
||||
{
|
||||
// Swift mirrors the text surface about its middle.
|
||||
const QPointF middle(m_logicalSize.width() / 2, m_logicalSize.height() / 2);
|
||||
const QTransform mirror = QTransform::fromTranslate(middle.x(), middle.y())
|
||||
.scale(m_shownTransform.flipX ? -1 : 1, m_shownTransform.flipY ? -1 : 1)
|
||||
.translate(-middle.x(), -middle.y());
|
||||
return mirror * boxTransform();
|
||||
}
|
||||
|
||||
void InlineTextEditor::draw(QPainter &painter) const
|
||||
{
|
||||
if (!m_lines)
|
||||
return;
|
||||
painter.save();
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
const QPalette palette = m_canvas.palette();
|
||||
// The frame and handles first: Swift's text view draws above.
|
||||
painter.setTransform(boxTransform());
|
||||
const QColor accent = palette.color(QPalette::Highlight);
|
||||
const double width = m_logicalSize.width(), height = m_logicalSize.height(), inset = m_handleSize / 12;
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.setPen(QPen(accent, m_handleSize / 6, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
|
||||
painter.drawRect(QRectF(0, 0, width, height).adjusted(inset, inset, -inset, -inset));
|
||||
painter.setPen(QPen(accent, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
|
||||
for (const QPointF &unit : LayerTransform::handles) {
|
||||
const QRectF handle(unit.x() * width - m_handleSize / 2, unit.y() * height - m_handleSize / 2, m_handleSize, m_handleSize);
|
||||
painter.fillRect(handle, Qt::white);
|
||||
painter.drawRect(handle);
|
||||
}
|
||||
// Text that does not fit: a plus in a corner.
|
||||
if (m_lines->overflows()) {
|
||||
const QPointF centre(LayerTransform::handles[4].x() * width, LayerTransform::handles[4].y() * height);
|
||||
const double arm = m_handleSize * 0.42;
|
||||
painter.setPen(QPen(Qt::black, m_handleSize / 6, Qt::SolidLine, Qt::FlatCap));
|
||||
painter.drawLine(centre - QPointF(arm, 0), centre + QPointF(arm, 0));
|
||||
painter.drawLine(centre - QPointF(0, arm), centre + QPointF(0, arm));
|
||||
}
|
||||
const double padding = LayerTextStyle::padding;
|
||||
painter.setTransform(textTransform());
|
||||
const QColor ink = QColor::fromRgbF(float(style().red), float(style().green), float(style().blue));
|
||||
painter.setPen(ink);
|
||||
const QColor highlight = palette.color(m_focused ? QPalette::Active : QPalette::Inactive, QPalette::Highlight);
|
||||
// The input method's formats, else NSTextView's underline.
|
||||
QList<QTextLayout::FormatRange> formats;
|
||||
if (m_composing) {
|
||||
for (QTextLayout::FormatRange format : m_composing->formats) {
|
||||
format.start += m_composing->marked.start;
|
||||
formats << format;
|
||||
}
|
||||
if (formats.isEmpty()) {
|
||||
QTextCharFormat underline;
|
||||
underline.setFontUnderline(true);
|
||||
formats << QTextLayout::FormatRange{m_composing->marked.start, m_composing->marked.end - m_composing->marked.start, underline};
|
||||
}
|
||||
}
|
||||
m_lines->draw(painter, QPointF(padding, padding), shownSelection(), formats, highlight);
|
||||
// The insertion point shows where nothing is selected.
|
||||
const bool hidden = m_composing && m_composing->caretHidden;
|
||||
if (const std::optional<QRectF> caret = m_lines->caret(m_position); caret && caretShown() && selection().isEmpty() && !hidden)
|
||||
painter.fillRect(caret->translated(padding, padding), m_composing ? m_composing->caretColour.value_or(ink) : ink);
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
QRectF InlineTextEditor::drawnRect() const
|
||||
{
|
||||
if (!m_lines)
|
||||
return QRectF();
|
||||
// Handles overhang; tight lines rise, the caret's line falls.
|
||||
const double margin = m_handleSize + std::max(style().fontSize, style().lineHeight());
|
||||
const QRectF box = QRectF(QPointF(0, 0), m_logicalSize).adjusted(-margin, -margin, margin, margin);
|
||||
return boxTransform().mapRect(box).adjusted(-2, -2, 2, 2);
|
||||
}
|
||||
|
||||
void InlineTextEditor::setFocused(bool focused)
|
||||
{
|
||||
m_focused = focused;
|
||||
showCaret();
|
||||
}
|
||||
|
||||
void InlineTextEditor::showCaret()
|
||||
{
|
||||
m_caretShown = true;
|
||||
if (m_focused && m_blink.interval() > 0)
|
||||
m_blink.start();
|
||||
else
|
||||
m_blink.stop();
|
||||
repaint();
|
||||
}
|
||||
|
||||
void InlineTextEditor::repaint() const
|
||||
{
|
||||
m_canvas.update(drawnRect().toAlignedRect());
|
||||
}
|
||||
|
||||
// Qt's updateMicroFocus: input methods follow the caret.
|
||||
void InlineTextEditor::updateInputMethod() const
|
||||
{
|
||||
if (QGuiApplication::focusObject() == &m_canvas)
|
||||
QGuiApplication::inputMethod()->update(Qt::ImQueryInput);
|
||||
}
|
||||
|
||||
// Swift's synchronizeInlineText: the editor follows the draft.
|
||||
void CanvasView::synchronizeInlineText()
|
||||
{
|
||||
const std::optional<TextDraft> &draft = m_session.textDraft();
|
||||
if (!draft) {
|
||||
// Its layer shows whole again, as Swift's needsDisplay.
|
||||
if (m_inlineTextEditor) {
|
||||
update();
|
||||
m_inlineTextEditor.reset();
|
||||
setAttribute(Qt::WA_InputMethodEnabled, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A new draft repaints the canvas, as Swift's needsDisplay.
|
||||
if (!m_inlineTextEditor || m_inlineTextEditor->draftID() != draft->id)
|
||||
update();
|
||||
const bool fresh = !m_inlineTextEditor;
|
||||
if (fresh)
|
||||
m_inlineTextEditor = std::make_unique<InlineTextEditor>(m_session, *this);
|
||||
const QRectF before = m_inlineTextEditor->drawnRect();
|
||||
m_inlineTextEditor->synchronize(*draft);
|
||||
update((before | m_inlineTextEditor->drawnRect()).toAlignedRect());
|
||||
if (!fresh)
|
||||
return;
|
||||
m_inlineTextEditor->setFocused(hasFocus());
|
||||
// Input methods compose into the draft, as a text view.
|
||||
setAttribute(Qt::WA_InputMethodEnabled, true);
|
||||
}
|
||||
|
||||
void CanvasView::inputMethodEvent(QInputMethodEvent *event)
|
||||
{
|
||||
if (!m_inlineTextEditor) {
|
||||
QWidget::inputMethodEvent(event);
|
||||
return;
|
||||
}
|
||||
m_inlineTextEditor->inputMethod(*event);
|
||||
event->accept();
|
||||
}
|
||||
|
||||
QVariant CanvasView::inputMethodQuery(Qt::InputMethodQuery query) const
|
||||
{
|
||||
return m_inlineTextEditor ? m_inlineTextEditor->inputMethodQuery(query) : QWidget::inputMethodQuery(query);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
#pragma once
|
||||
#include "Document/TypeTool.h"
|
||||
#include "Rendering/TextLayout.h"
|
||||
#include <QInputMethodEvent>
|
||||
#include <QCursor>
|
||||
#include <QTimer>
|
||||
#include <QTransform>
|
||||
#include <QVariant>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
class EditorSession;
|
||||
class QKeyEvent;
|
||||
class QPainter;
|
||||
class QWidget;
|
||||
|
||||
// Swift's InlineTextEditor and its text view, painted by the canvas.
|
||||
class InlineTextEditor {
|
||||
public:
|
||||
InlineTextEditor(EditorSession &session, QWidget &canvas);
|
||||
// Swift's synchronize: size, placement, content and style.
|
||||
void synchronize(const TextDraft &draft);
|
||||
QUuid draftID() const { return m_draftID; }
|
||||
// The text view's bounds, in layer pixels.
|
||||
QSizeF logicalSize() const { return m_logicalSize; }
|
||||
// Point text grows as typed, so this is what shows.
|
||||
LayerTransform shownTransform() const { return m_shownTransform; }
|
||||
double handleSize() const { return m_handleSize; }
|
||||
// Layer pixels to view points, without the layer's flips.
|
||||
QTransform boxTransform() const;
|
||||
// The text surface's own mapping, flipped with its layer.
|
||||
QTransform textTransform() const;
|
||||
void draw(QPainter &painter) const;
|
||||
// Where the editor draws, in view points.
|
||||
QRectF drawnRect() const;
|
||||
// The text view's keys; false leaves a key unused.
|
||||
bool keyPress(const QKeyEvent &event);
|
||||
// Keys the editor takes ahead of the menus' shortcuts.
|
||||
static bool claims(const QKeyEvent &event);
|
||||
void inputMethod(const QInputMethodEvent &event);
|
||||
QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
|
||||
// The caret shows, blinking, while the canvas has focus.
|
||||
void setFocused(bool focused);
|
||||
// The pointer: handles resize, the text view selects.
|
||||
bool press(QPointF point, Qt::KeyboardModifiers modifiers, int clicks);
|
||||
// NSTextView's click, wherever it lands, as the canvas forwards it.
|
||||
void pressText(QPointF point, Qt::KeyboardModifiers modifiers, int clicks);
|
||||
bool drag(QPointF point);
|
||||
void release();
|
||||
// A handle's cursor under the point, turned with the box.
|
||||
std::optional<QCursor> cursorAt(QPointF point) const;
|
||||
// NSText's actions, as the Edit menu sends them.
|
||||
void undo();
|
||||
void redo();
|
||||
void cut();
|
||||
void copy() const;
|
||||
void paste();
|
||||
void selectAll();
|
||||
// The text view's selection: an anchor and the caret.
|
||||
int anchor() const { return m_anchor; }
|
||||
int caretPosition() const { return m_position; }
|
||||
std::optional<TextRange> marked() const { return m_composing ? std::optional(m_composing->marked) : std::nullopt; }
|
||||
bool caretShown() const { return m_focused && m_caretShown; }
|
||||
|
||||
private:
|
||||
struct Snapshot {
|
||||
QString content;
|
||||
int anchor;
|
||||
int position;
|
||||
};
|
||||
// An input method's preedit, which Qt keeps out of history.
|
||||
struct Composing {
|
||||
TextRange marked;
|
||||
// Qt keeps a selection beside the preedit, without it.
|
||||
int anchor;
|
||||
// Formats count from the preedit's start.
|
||||
QList<QTextLayout::FormatRange> formats = {};
|
||||
bool caretHidden = false;
|
||||
std::optional<QColor> caretColour = std::nullopt;
|
||||
// The text before the preedit, for its landing step.
|
||||
Snapshot before;
|
||||
};
|
||||
// A handle's drag: the draft and box it began from.
|
||||
struct Resize {
|
||||
int handle;
|
||||
TextDraft draft;
|
||||
LayerTransform transform;
|
||||
QPointF start;
|
||||
};
|
||||
// A click's unit, kept for Shift while its selection stands.
|
||||
struct Tracking {
|
||||
TextRange origin;
|
||||
int clicks;
|
||||
int anchor;
|
||||
int position;
|
||||
};
|
||||
// Runs of these coalesce into one undo step, as NSTextView's.
|
||||
enum class Edit { typing, deleting };
|
||||
const LayerTextStyle &style() const { return m_shownStyle.value(); }
|
||||
static TextRange spanning(int anchor, int position);
|
||||
TextRange selection() const;
|
||||
void replace(TextRange range, const QString &text, std::optional<Edit> edit);
|
||||
void publish(const QString &content);
|
||||
void moveTo(int position, bool extend, bool keepGoal = false);
|
||||
void restore(std::vector<Snapshot> &from, std::vector<Snapshot> &to);
|
||||
void changeSpacing(int key, double step);
|
||||
bool move(const QKeyEvent &event);
|
||||
bool rightToLeft() const;
|
||||
static bool separates(QChar character);
|
||||
std::optional<int> handleAt(QPointF point) const;
|
||||
int positionAt(QPointF point, bool onCharacter) const;
|
||||
TextRange unitAt(int position, int clicks) const;
|
||||
void land();
|
||||
void beginResize(int handle, QPointF point);
|
||||
void resizeTo(QPointF point);
|
||||
void compose(const QString &preedit, const QList<QInputMethodEvent::Attribute> &attributes, const Snapshot &before, int anchor, QString &text,
|
||||
int cursor);
|
||||
TextRange shownSelection() const;
|
||||
Snapshot plain() const;
|
||||
void change(const QString &text);
|
||||
void settle(QString text, int anchor, int cursor);
|
||||
bool erase(const QKeyEvent &event);
|
||||
int nextCharacter(int position) const;
|
||||
int previousCharacter(int position) const;
|
||||
int nextWordEnd(int position) const;
|
||||
int previousWordStart(int position) const;
|
||||
int lineBound(bool end) const;
|
||||
int verticalTarget(int direction);
|
||||
void showCaret();
|
||||
void repaint() const;
|
||||
void updateInputMethod() const;
|
||||
|
||||
EditorSession &m_session;
|
||||
QWidget &m_canvas;
|
||||
QUuid m_draftID;
|
||||
std::optional<LayerTextStyle> m_shownStyle;
|
||||
QSizeF m_logicalSize{360, 160};
|
||||
LayerTransform m_shownTransform;
|
||||
double m_handleSize = 6;
|
||||
std::unique_ptr<TextLines> m_lines;
|
||||
int m_anchor = 0;
|
||||
int m_position = 0;
|
||||
std::optional<Composing> m_composing;
|
||||
// Up and Down keep the caret's first x, as NSTextView.
|
||||
std::optional<double> m_goalX;
|
||||
std::vector<Snapshot> m_undo;
|
||||
std::vector<Snapshot> m_redo;
|
||||
std::optional<Edit> m_lastEdit;
|
||||
std::optional<Resize> m_resize;
|
||||
std::optional<Tracking> m_tracking;
|
||||
// The button that began a selection is still down.
|
||||
bool m_selecting = false;
|
||||
QTimer m_blink;
|
||||
bool m_focused = false;
|
||||
bool m_caretShown = true;
|
||||
};
|
||||
@@ -0,0 +1,235 @@
|
||||
#include "Rendering/LayerEffectsKernel.h"
|
||||
#include "Rendering/PoolMap.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include <QtConcurrent>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
|
||||
// Metal's kernels, pass after pass, in float as the shader.
|
||||
namespace {
|
||||
using Buffer = std::unique_ptr<float[]>;
|
||||
|
||||
// Allocated by the caller, where a failure throws.
|
||||
template <typename Value> std::unique_ptr<Value[]> allocated(qint64 count)
|
||||
{
|
||||
std::unique_ptr<Value[]> made(new (std::nothrow) Value[size_t(count)]);
|
||||
if (!made)
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
return made;
|
||||
}
|
||||
|
||||
Buffer buffer(qint64 count)
|
||||
{
|
||||
return allocated<float>(count);
|
||||
}
|
||||
|
||||
// Bands of 32 lines side by side: Metal's thread groups.
|
||||
void bands(int count, const std::function<void(int band, int line)> &line)
|
||||
{
|
||||
std::vector<int> firsts;
|
||||
for (int first = 0; first < count; first += 32)
|
||||
firsts.push_back(first);
|
||||
PoolMap::blocking(firsts, [&](int first) {
|
||||
for (int index = first; index < std::min(count, first + 32); ++index)
|
||||
line(first / 32, index);
|
||||
});
|
||||
}
|
||||
|
||||
float mixed(float from, float to, float amount)
|
||||
{
|
||||
return from + (to - from) * amount;
|
||||
}
|
||||
|
||||
// Swift's extreme: a sliding window, each index in once.
|
||||
void spreadLine(const float *input, float *output, int count, qsizetype step, int reach, bool smallest, int *queue)
|
||||
{
|
||||
int head = 0, tail = 0, next = 0;
|
||||
for (int center = 0; center < count; ++center) {
|
||||
while (next <= std::min(count - 1, center + reach)) {
|
||||
const float value = input[next * step];
|
||||
while (tail > head) {
|
||||
const float previous = input[queue[tail - 1] * step];
|
||||
if (smallest ? previous < value : previous > value)
|
||||
break;
|
||||
--tail;
|
||||
}
|
||||
queue[tail++] = next++;
|
||||
}
|
||||
while (head < tail && queue[head] < center - reach)
|
||||
++head;
|
||||
// Past the edges Metal reads nothing: the smallest is none.
|
||||
const bool outside = center < reach || center + reach >= count;
|
||||
output[center * step] = smallest && outside ? 0.f : input[queue[head] * step];
|
||||
}
|
||||
}
|
||||
|
||||
// Metal's spread, rows then columns: its loops' maxima.
|
||||
void spread(const float *source, float *across, float *result, int width, int height, int reach, bool smallest)
|
||||
{
|
||||
// A queue a band, as long as that pass's lines.
|
||||
const qsizetype rows = qsizetype(height + 31) / 32 * width, columns = qsizetype(width + 31) / 32 * height;
|
||||
const std::unique_ptr<int[]> queues = allocated<int>(std::max(rows, columns));
|
||||
bands(height, [&](int band, int y) {
|
||||
spreadLine(source + qsizetype(y) * width, across + qsizetype(y) * width, width, 1, reach, smallest, queues.get() + qsizetype(band) * width);
|
||||
});
|
||||
bands(width, [&](int band, int x) { spreadLine(across + x, result + x, height, width, reach, smallest, queues.get() + qsizetype(band) * height); });
|
||||
}
|
||||
|
||||
void shifted(const float *source, float *result, int width, int height, float dx, float dy)
|
||||
{
|
||||
bands(height, [&](int, int y) {
|
||||
for (int x = 0; x < width; ++x) {
|
||||
const float sx = float(x) - dx, sy = float(y) - dy;
|
||||
float value = 0.f;
|
||||
// Between pixels, so a shadow moves smoothly.
|
||||
if (sx >= 0.f && sy >= 0.f && sx <= float(width - 1) && sy <= float(height - 1)) {
|
||||
const int x0 = int(std::floor(sx)), y0 = int(std::floor(sy));
|
||||
const int x1 = std::min(x0 + 1, width - 1), y1 = std::min(y0 + 1, height - 1);
|
||||
const float fx = sx - float(x0), fy = sy - float(y0);
|
||||
const float top = mixed(source[qsizetype(y0) * width + x0], source[qsizetype(y0) * width + x1], fx);
|
||||
const float bottom = mixed(source[qsizetype(y1) * width + x0], source[qsizetype(y1) * width + x1], fx);
|
||||
value = mixed(top, bottom, fy);
|
||||
}
|
||||
result[qsizetype(y) * width + x] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Metal's blur, rows then columns, taps added in order.
|
||||
void blurred(float *values, float *scratch, int width, int height, float sigma)
|
||||
{
|
||||
if (!(sigma > 0.01f))
|
||||
return;
|
||||
const int radius = std::max(1, int(std::lround(sigma * 3)));
|
||||
// Valid effects blur at most 500, a radius of 750.
|
||||
std::array<float, 1501> weights;
|
||||
if (radius > 750)
|
||||
throw std::logic_error("an effect blurs past its bounds");
|
||||
float total = 0;
|
||||
for (int offset = -radius; offset <= radius; ++offset) {
|
||||
weights[size_t(offset + radius)] = std::exp(-float(offset * offset) / (2.f * sigma * sigma));
|
||||
total += weights[size_t(offset + radius)];
|
||||
}
|
||||
bands(height, [&](int, int y) {
|
||||
const float *row = values + qsizetype(y) * width;
|
||||
for (int x = 0; x < width; ++x) {
|
||||
float sum = 0;
|
||||
for (int offset = -radius; offset <= radius; ++offset)
|
||||
sum += weights[size_t(offset + radius)] * row[std::clamp(x + offset, 0, width - 1)];
|
||||
scratch[qsizetype(y) * width + x] = sum / total;
|
||||
}
|
||||
});
|
||||
bands(height, [&](int, int y) {
|
||||
float *out = values + qsizetype(y) * width;
|
||||
std::fill(out, out + width, 0.f);
|
||||
for (int offset = -radius; offset <= radius; ++offset) {
|
||||
const float weight = weights[size_t(offset + radius)];
|
||||
const float *in = scratch + qsizetype(std::clamp(y + offset, 0, height - 1)) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
out[x] += weight * in[x];
|
||||
}
|
||||
for (int x = 0; x < width; ++x)
|
||||
out[x] /= total;
|
||||
});
|
||||
}
|
||||
|
||||
// Source over: a colour, at a coverage, onto the rest.
|
||||
void over(float (&colour)[3], float &alpha, const PaletteColor &paint, float coverage)
|
||||
{
|
||||
colour[0] = float(paint.red) * coverage + colour[0] * (1.f - coverage);
|
||||
colour[1] = float(paint.green) * coverage + colour[1] * (1.f - coverage);
|
||||
colour[2] = float(paint.blue) * coverage + colour[2] * (1.f - coverage);
|
||||
alpha = coverage + alpha * (1.f - coverage);
|
||||
}
|
||||
|
||||
uchar byte(float value)
|
||||
{
|
||||
return uchar(std::clamp(value, 0.f, 1.f) * 255.f + 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
QImage LayerEffectsKernel::render(const QImage &pixels, const LayerEffects &effects)
|
||||
{
|
||||
const int width = pixels.width(), height = pixels.height();
|
||||
const qint64 count = qint64(width) * height;
|
||||
// Past Metal's 80 million Swift draws on its CPU.
|
||||
if (count <= 0 || count > 100'000'000)
|
||||
throw ExportError(ExportError::Kind::tooLarge);
|
||||
const QImage source = pixels.convertToFormat(QImage::Format_RGBA8888_Premultiplied);
|
||||
if (source.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
const Buffer shape = buffer(count);
|
||||
bands(height, [&](int, int y) {
|
||||
const uchar *row = source.constScanLine(y);
|
||||
for (int x = 0; x < width; ++x)
|
||||
shape[qsizetype(y) * width + x] = float(row[x * 4 + 3]) / 255.f;
|
||||
});
|
||||
const std::optional<StrokeEffect> stroke = effects.stroke && effects.stroke->isEnabled() && effects.stroke->size > 0 && effects.stroke->opacity > 0
|
||||
? effects.stroke : std::nullopt;
|
||||
Buffer ring;
|
||||
if (stroke) {
|
||||
const Buffer across = buffer(count), moved = buffer(count);
|
||||
ring = buffer(count);
|
||||
spread(shape.get(), across.get(), moved.get(), width, height, std::max(1, int(std::lround(stroke->size))), stroke->inside);
|
||||
for (qint64 index = 0; index < count; ++index)
|
||||
ring[index] = std::clamp(stroke->inside ? shape[index] - moved[index] : moved[index] - shape[index], 0.f, 1.f);
|
||||
}
|
||||
const std::optional<ShadowEffect> shadow = effects.shadow && effects.shadow->isEnabled() && effects.shadow->opacity > 0 ? effects.shadow : std::nullopt;
|
||||
Buffer cast;
|
||||
if (shadow) {
|
||||
cast = buffer(count);
|
||||
const QSizeF offset = shadow->offset();
|
||||
shifted(shape.get(), cast.get(), width, height, float(offset.width()), float(offset.height()));
|
||||
blurred(cast.get(), buffer(count).get(), width, height, float(shadow->blur / 2));
|
||||
}
|
||||
const std::optional<InnerShadowEffect> inner = effects.innerShadow && effects.innerShadow->isEnabled() && effects.innerShadow->opacity > 0
|
||||
? effects.innerShadow : std::nullopt;
|
||||
Buffer inside;
|
||||
if (inner) {
|
||||
inside = buffer(count);
|
||||
const QSizeF offset = inner->offset();
|
||||
shifted(shape.get(), inside.get(), width, height, float(offset.width()), float(offset.height()));
|
||||
blurred(inside.get(), buffer(count).get(), width, height, float(inner->blur / 2));
|
||||
// What lies outside the layer, softened, kept to its shape.
|
||||
for (qint64 index = 0; index < count; ++index)
|
||||
inside[index] = std::clamp(shape[index] * (1.f - inside[index]), 0.f, 1.f);
|
||||
}
|
||||
const std::optional<ColorOverlayEffect> overlay = effects.colorOverlay && effects.colorOverlay->isEnabled() && effects.colorOverlay->opacity > 0
|
||||
? effects.colorOverlay : std::nullopt;
|
||||
QImage result = BrushRaster::context(width, height, false);
|
||||
// Taken once: scanLine() detaches, which workers must not race.
|
||||
uchar *const bits = result.bits();
|
||||
const qsizetype stride = result.bytesPerLine();
|
||||
// Shadow, outside stroke, pixels, overlay, inner shadow, inside stroke.
|
||||
bands(height, [&](int, int y) {
|
||||
const uchar *in = source.constScanLine(y);
|
||||
uchar *out = bits + y * stride;
|
||||
for (int x = 0; x < width; ++x) {
|
||||
const qsizetype index = qsizetype(y) * width + x;
|
||||
float colour[3] = {0, 0, 0}, alpha = 0;
|
||||
if (shadow)
|
||||
over(colour, alpha, shadow->color(), std::clamp(cast[index] * float(shadow->opacity), 0.f, 1.f));
|
||||
const float strokeCoverage = stroke ? std::clamp(ring[index] * float(stroke->opacity), 0.f, 1.f) : 0.f;
|
||||
if (stroke && !stroke->inside)
|
||||
over(colour, alpha, stroke->color(), strokeCoverage);
|
||||
const float sourceAlpha = float(in[x * 4 + 3]) / 255.f;
|
||||
for (int channel = 0; channel < 3; ++channel)
|
||||
colour[channel] = float(in[x * 4 + channel]) / 255.f + colour[channel] * (1.f - sourceAlpha);
|
||||
alpha = sourceAlpha + alpha * (1.f - sourceAlpha);
|
||||
if (overlay)
|
||||
over(colour, alpha, overlay->color(), std::clamp(shape[index] * float(overlay->opacity), 0.f, 1.f));
|
||||
if (inner)
|
||||
over(colour, alpha, inner->color(), std::clamp(inside[index] * float(inner->opacity), 0.f, 1.f));
|
||||
if (stroke && stroke->inside)
|
||||
over(colour, alpha, stroke->color(), strokeCoverage);
|
||||
out[x * 4] = byte(colour[0]);
|
||||
out[x * 4 + 1] = byte(colour[1]);
|
||||
out[x * 4 + 2] = byte(colour[2]);
|
||||
out[x * 4 + 3] = byte(alpha);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include "Document/LayerEffects.h"
|
||||
#include <QImage>
|
||||
|
||||
// Swift's MetalLayerEffects: its passes on the CPU, in float.
|
||||
namespace LayerEffectsKernel {
|
||||
// The shown layer with room round it; same size back.
|
||||
QImage render(const QImage &pixels, const LayerEffects &effects);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
#include "Rendering/LayerEffectsSurface.h"
|
||||
#include "Document/LayerEffects+Renderer.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "Logging.h"
|
||||
#include "Rendering/LayerEffectsKernel.h"
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include <QPainter>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
QRectF integral(const QRectF &rect)
|
||||
{
|
||||
return QRectF(QPointF(std::floor(rect.left()), std::floor(rect.top())), QPointF(std::ceil(rect.right()), std::ceil(rect.bottom())));
|
||||
}
|
||||
}
|
||||
|
||||
LayerEffectsSurface::LayerEffectsSurface(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect, double margin, QImage context)
|
||||
: layerID(layerID), grid(grid), sourceRect(sourceRect), margin(margin), m_effects(effects), m_context(std::move(context))
|
||||
{
|
||||
}
|
||||
|
||||
std::unique_ptr<LayerEffectsSurface> LayerEffectsSurface::make(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect)
|
||||
{
|
||||
const double margin = LayerEffectsRenderer::margin(effects);
|
||||
const qint64 width = qint64(grid.width() + margin * 2), height = qint64(grid.height() + margin * 2);
|
||||
if (width * height > 80'000'000) {
|
||||
qCWarning(lcRendering) << "an effects surface passes its pixel budget:" << width << "x" << height;
|
||||
return nullptr;
|
||||
}
|
||||
try {
|
||||
QImage context = BrushRaster::context(int(width), int(height), false);
|
||||
return std::unique_ptr<LayerEffectsSurface>(new LayerEffectsSurface(layerID, effects, grid, sourceRect, margin, std::move(context)));
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "an effects surface could not be allocated:" << error.what();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool LayerEffectsSurface::matches(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect) const
|
||||
{
|
||||
return this->layerID == layerID && m_effects == effects && this->grid == grid && this->sourceRect == sourceRect;
|
||||
}
|
||||
|
||||
// How far a change reaches: all within may need redoing.
|
||||
double LayerEffectsSurface::reach() const
|
||||
{
|
||||
double reach = 1;
|
||||
if (m_effects.stroke)
|
||||
reach = std::max(reach, m_effects.stroke->size + 2);
|
||||
if (m_effects.shadow)
|
||||
reach = std::max(reach, m_effects.shadow->distance + m_effects.shadow->blur * 3 + 2);
|
||||
// Swift forgets the inner shadow, whose blur reaches as far.
|
||||
if (m_effects.innerShadow)
|
||||
reach = std::max(reach, m_effects.innerShadow->distance + m_effects.innerShadow->blur * 3 + 2);
|
||||
return reach;
|
||||
}
|
||||
|
||||
void LayerEffectsSurface::update(const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches, const std::optional<QImage> &mask)
|
||||
{
|
||||
std::optional<QRectF> dirty;
|
||||
std::map<std::pair<qint64, qint64>, qint64> seen;
|
||||
for (const BrushPatch &patch : patches) {
|
||||
const std::pair<qint64, qint64> key(qint64(patch.rect.left()), qint64(patch.rect.top()));
|
||||
seen.insert_or_assign(key, patch.image.cacheKey());
|
||||
if (!m_taken.contains(key) || m_taken.at(key) != patch.image.cacheKey())
|
||||
dirty = dirty ? dirty->united(patch.rect) : patch.rect;
|
||||
}
|
||||
const bool first = !m_image;
|
||||
const std::optional<QRectF> region = first ? std::optional(QRectF(QPointF(0, 0), grid).adjusted(-margin, -margin, margin, margin)) : dirty;
|
||||
if (!region)
|
||||
return;
|
||||
try {
|
||||
compose(*region, base, patches, mask);
|
||||
// Taken once redone: a failed pass is tried again.
|
||||
m_taken = seen;
|
||||
m_image = m_context;
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "a painted layer's effects could not be redone:" << error.what();
|
||||
}
|
||||
}
|
||||
|
||||
// One region anew: its effects, with the pixels in them.
|
||||
void LayerEffectsSurface::compose(const QRectF ®ion, const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<QImage> &mask)
|
||||
{
|
||||
const QRectF bounds = QRectF(QPointF(0, 0), grid).adjusted(-margin, -margin, margin, margin);
|
||||
// Widened by the reach: Swift's margin misses inside effects.
|
||||
const double reach = this->reach();
|
||||
const QRectF inner = integral(region.adjusted(-reach, -reach, reach, reach)).intersected(bounds);
|
||||
// What reaches `inner`, cut where the export's padding ends.
|
||||
const QRectF outer = integral(inner.adjusted(-reach, -reach, reach, reach)).intersected(bounds);
|
||||
const QImage built = LayerEffectsKernel::render(window(outer, base, patches, mask), m_effects);
|
||||
// Painted on a copy: one without memory changes nothing.
|
||||
QImage next = m_context;
|
||||
QPainter painter(&next);
|
||||
if (!painter.isActive())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
// In the surface the grid starts at the margin.
|
||||
BrushRaster::draw(built, inner.translated(margin, margin), painter, inner.translated(-outer.left(), -outer.top()));
|
||||
painter.end();
|
||||
m_context = next;
|
||||
}
|
||||
|
||||
// The layer as painted so far: pixels, tiles, mask.
|
||||
QImage LayerEffectsSurface::window(const QRectF ®ion, const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<QImage> &mask) const
|
||||
{
|
||||
QImage window = BrushRaster::context(int(region.width()), int(region.height()), false);
|
||||
QPainter painter(&window);
|
||||
painter.translate(-region.left(), -region.top());
|
||||
if (base && base->raster)
|
||||
base->raster->draw(sourceRect, painter);
|
||||
else if (base)
|
||||
BrushRaster::draw(base->image(), sourceRect, painter);
|
||||
for (const BrushPatch &patch : patches) {
|
||||
if (patch.rect.intersects(region))
|
||||
BrushRaster::draw(patch.image, patch.rect, painter);
|
||||
}
|
||||
if (mask) {
|
||||
// Only the layer's own pixels show through the mask.
|
||||
painter.setRenderHint(QPainter::SmoothPixmapTransform);
|
||||
painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
painter.drawImage(sourceRect, BrushRaster::alphaView(*mask));
|
||||
}
|
||||
return window;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "Document/LayerEffects.h"
|
||||
#include <QImage>
|
||||
#include <QUuid>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
// Swift's LayerEffectsSurface: effects redone only where paint lands.
|
||||
class LayerEffectsSurface {
|
||||
public:
|
||||
// Swift's init?: none past 80 million pixels, logged. Effects shown.
|
||||
static std::unique_ptr<LayerEffectsSurface> make(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect);
|
||||
// Whether it still fits the stroke and settings.
|
||||
bool matches(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect) const;
|
||||
// Everything at first, then only where the paint changed.
|
||||
void update(const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches, const std::optional<QImage> &mask);
|
||||
const std::optional<QImage> &image() const { return m_image; }
|
||||
|
||||
const QUuid layerID;
|
||||
// The stroke's grid in layer pixels, the layer's own inside.
|
||||
const QSizeF grid;
|
||||
const QRectF sourceRect;
|
||||
// The room the effects need round the pixels.
|
||||
const double margin;
|
||||
// Where it was last drawn, handed on at the end.
|
||||
std::optional<LayerTransform> placement;
|
||||
|
||||
private:
|
||||
LayerEffectsSurface(QUuid layerID, const LayerEffects &effects, QSizeF grid, QRectF sourceRect, double margin, QImage context);
|
||||
double reach() const;
|
||||
void compose(const QRectF ®ion, const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<QImage> &mask);
|
||||
QImage window(const QRectF ®ion, const std::optional<ImportedImage> &base, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<QImage> &mask) const;
|
||||
|
||||
const LayerEffects m_effects;
|
||||
QImage m_context;
|
||||
// Each tile's origin and the pixels last taken from it.
|
||||
std::map<std::pair<qint64, qint64>, qint64> m_taken;
|
||||
std::optional<QImage> m_image;
|
||||
};
|
||||
@@ -0,0 +1,318 @@
|
||||
#include "Rendering/LayerRenderer.h"
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "Rendering/DownsampleCache.h"
|
||||
#include "Rendering/HslBlend.h"
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include <QPainterPath>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
QPainter::CompositionMode compositionMode(LayerBlendMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case LayerBlendMode::normal:
|
||||
return QPainter::CompositionMode_SourceOver;
|
||||
case LayerBlendMode::multiply:
|
||||
return QPainter::CompositionMode_Multiply;
|
||||
case LayerBlendMode::screen:
|
||||
return QPainter::CompositionMode_Screen;
|
||||
case LayerBlendMode::overlay:
|
||||
return QPainter::CompositionMode_Overlay;
|
||||
case LayerBlendMode::darken:
|
||||
return QPainter::CompositionMode_Darken;
|
||||
case LayerBlendMode::lighten:
|
||||
return QPainter::CompositionMode_Lighten;
|
||||
case LayerBlendMode::difference:
|
||||
return QPainter::CompositionMode_Difference;
|
||||
case LayerBlendMode::colorDodge:
|
||||
return QPainter::CompositionMode_ColorDodge;
|
||||
case LayerBlendMode::colorBurn:
|
||||
return QPainter::CompositionMode_ColorBurn;
|
||||
default:
|
||||
throw std::logic_error("QPainter has no composition mode for this blend mode");
|
||||
}
|
||||
}
|
||||
|
||||
void setSampling(QPainter &painter, InterpolationQuality quality, LayerSampling sampling)
|
||||
{
|
||||
painter.setRenderHint(QPainter::SmoothPixmapTransform, quality != InterpolationQuality::none);
|
||||
painter.setRenderHint(QPainter::Antialiasing, sampling != LayerSampling::nearest);
|
||||
}
|
||||
}
|
||||
|
||||
void LayerRenderer::draw(const QImage &image, const LayerTransform &transform, QPointF center, QPainter &context,
|
||||
const Options &options)
|
||||
{
|
||||
const double width = transform.size.width() * options.scale, height = transform.size.height() * options.scale;
|
||||
// Large reductions draw from sharp halvings; QPainter does the rest.
|
||||
const double device = deviceScale(context);
|
||||
const Reduced source = reduced(image, width, device, transform.sampling);
|
||||
const InterpolationQuality quality = interpolation(
|
||||
transform.sampling, width * device / std::max(1, image.width()) * (1 << source.level));
|
||||
const QRectF bounds(-width / 2, -height / 2, width, height);
|
||||
QTransform placement;
|
||||
placement.translate(center.x(), center.y());
|
||||
placement.rotateRadians(transform.radians());
|
||||
placement.scale(transform.flipX ? -1 : 1, transform.flipY ? -1 : 1);
|
||||
|
||||
if (options.mask.isNull() && options.clip.isNull() && !HslBlend::handles(options.blendMode)) {
|
||||
const QPainter::CompositionMode mode = compositionMode(options.blendMode);
|
||||
context.save();
|
||||
context.setOpacity(options.opacity);
|
||||
context.setCompositionMode(mode);
|
||||
setSampling(context, quality, transform.sampling);
|
||||
context.setTransform(placement, true);
|
||||
context.drawImage(coverage(source, bounds), source.image);
|
||||
context.restore();
|
||||
return;
|
||||
}
|
||||
|
||||
composite(context, placement, coverage(source, bounds), transform.sampling, quality, options, bounds,
|
||||
[&](QPainter &aside) { aside.drawImage(coverage(source, bounds), source.image); });
|
||||
}
|
||||
|
||||
void LayerRenderer::drawBrushPreview(const QImage &image, const LayerTransform &transform, QPointF center, QPainter &context,
|
||||
const Options &options, const BrushPreview &preview)
|
||||
{
|
||||
if (preview.pixelWidth <= 0 || preview.pixelHeight <= 0)
|
||||
throw std::logic_error("a brush preview needs a pixel grid");
|
||||
const double width = transform.size.width() * options.scale, height = transform.size.height() * options.scale;
|
||||
const QRectF bounds(-width / 2, -height / 2, width, height);
|
||||
const auto mapped = [](const QRectF &source, const QRectF &into, double columns, double rows) {
|
||||
return QRectF(into.left() + source.left() / columns * into.width(), into.top() + source.top() / rows * into.height(),
|
||||
source.width() / columns * into.width(), source.height() / rows * into.height());
|
||||
};
|
||||
const auto tile = [&](const BrushPatch &patch) { return mapped(patch.rect, bounds, preview.pixelWidth, preview.pixelHeight); };
|
||||
const QRectF originalBounds = preview.sourceRect ? mapped(*preview.sourceRect, bounds, preview.pixelWidth, preview.pixelHeight) : bounds;
|
||||
// A raster is a source: naming one never flattens it.
|
||||
const bool hasSource = !image.isNull() || preview.raster;
|
||||
const auto drawSource = [&](QPainter &aside) {
|
||||
if (!preview.raster) {
|
||||
aside.drawImage(originalBounds, image);
|
||||
return;
|
||||
}
|
||||
const RasterSnapshot &raster = *preview.raster;
|
||||
const QImage &base = preview.rasterBase.isNull() ? raster.base : preview.rasterBase;
|
||||
if (!base.isNull()) {
|
||||
// A cropped raster's base shows only inside the source bounds.
|
||||
aside.save();
|
||||
aside.setClipRect(originalBounds, Qt::IntersectClip);
|
||||
aside.drawImage(mapped(raster.baseRect, originalBounds, raster.width, raster.height), base);
|
||||
aside.restore();
|
||||
}
|
||||
const QRectF visible = BrushRaster::visibleRect(aside);
|
||||
for (const BrushPatch &patch : raster.patches) {
|
||||
const QRectF target = mapped(patch.rect, originalBounds, raster.width, raster.height);
|
||||
if (target.intersects(visible))
|
||||
aside.drawImage(target, patch.image);
|
||||
}
|
||||
};
|
||||
QTransform placement;
|
||||
placement.translate(center.x(), center.y());
|
||||
placement.rotateRadians(transform.radians());
|
||||
placement.scale(transform.flipX ? -1 : 1, transform.flipY ? -1 : 1);
|
||||
QRectF extent = bounds;
|
||||
for (const BrushPatch &patch : preview.patches)
|
||||
extent = extent.united(tile(patch));
|
||||
// Tiles replace what lies under them, with hard edges.
|
||||
const auto body = [&](QPainter &aside) {
|
||||
aside.setCompositionMode(QPainter::CompositionMode_Source);
|
||||
if (hasSource) {
|
||||
// The source shows inside the grid only.
|
||||
aside.save();
|
||||
aside.setClipRect(bounds, Qt::IntersectClip);
|
||||
drawSource(aside);
|
||||
aside.restore();
|
||||
}
|
||||
for (const BrushPatch &patch : preview.patches) {
|
||||
if (!preview.paintingMask)
|
||||
aside.drawImage(tile(patch), patch.image);
|
||||
}
|
||||
};
|
||||
// A tile's part outside the old raster; paths fill odd-even.
|
||||
const auto outside = [&](const QRectF &rect) {
|
||||
QPainterPath path;
|
||||
path.addRect(rect);
|
||||
if (const QRectF overlap = rect.intersected(originalBounds); !overlap.isEmpty())
|
||||
path.addRect(overlap);
|
||||
return path;
|
||||
};
|
||||
const auto veil = [&](QPainter &masking) {
|
||||
masking.setCompositionMode(QPainter::CompositionMode_Source);
|
||||
for (const BrushPatch &patch : preview.patches) {
|
||||
// Painted coverage replaces the mask; paint outside is revealed.
|
||||
if (preview.paintingMask)
|
||||
masking.drawImage(tile(patch), BrushRaster::alphaView(patch.image));
|
||||
else
|
||||
masking.fillPath(outside(tile(patch)), Qt::black);
|
||||
}
|
||||
};
|
||||
const bool veiled = preview.paintingMask || !options.mask.isNull();
|
||||
// Nearest keeps every edge hard; the quality is the layer's.
|
||||
composite(context, placement, extent, LayerSampling::nearest, quality(transform.sampling), options, originalBounds, body,
|
||||
veiled ? std::function<void(QPainter &)>(veil) : std::function<void(QPainter &)>());
|
||||
}
|
||||
|
||||
void LayerRenderer::composite(QPainter &context, const QTransform &placement, const QRectF &extent, LayerSampling sampling,
|
||||
InterpolationQuality quality, const Options &options, const QRectF &maskBounds,
|
||||
const std::function<void(QPainter &)> &body, const std::function<void(QPainter &)> &veil)
|
||||
{
|
||||
// Qt has no mask clip: the layer composes aside first.
|
||||
const QTransform toDevice = placement * context.deviceTransform();
|
||||
const QRect deviceBounds(0, 0, context.device()->width(), context.device()->height());
|
||||
const QRect area = toDevice.mapRect(extent).toAlignedRect()
|
||||
.intersected(context.deviceTransform().mapRect(BrushRaster::visibleRect(context)).toAlignedRect())
|
||||
.intersected(deviceBounds);
|
||||
if (area.isEmpty())
|
||||
return;
|
||||
const QTransform toSurface = toDevice * QTransform::fromTranslate(-area.left(), -area.top());
|
||||
QImage surface(area.size(), QImage::Format_RGBA8888_Premultiplied);
|
||||
if (surface.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
surface.fill(0);
|
||||
{
|
||||
QPainter aside(&surface);
|
||||
setSampling(aside, quality, sampling);
|
||||
aside.setTransform(toSurface);
|
||||
body(aside);
|
||||
}
|
||||
if (!options.mask.isNull() || veil) {
|
||||
QImage shown(area.size(), QImage::Format_Alpha8);
|
||||
if (shown.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
// Nothing outside a mask survives; without one, all shows.
|
||||
shown.fill(options.mask.isNull() ? 255 : 0);
|
||||
{
|
||||
QPainter masking(&shown);
|
||||
setSampling(masking, quality, sampling);
|
||||
masking.setTransform(toSurface);
|
||||
if (!options.mask.isNull()) {
|
||||
const Reduced clip = reduced(options.mask, maskBounds.width(), deviceScale(context), sampling);
|
||||
masking.drawImage(coverage(clip, maskBounds), BrushRaster::alphaView(clip.image));
|
||||
}
|
||||
if (veil)
|
||||
veil(masking);
|
||||
}
|
||||
QPainter multiplying(&surface);
|
||||
multiplying.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
multiplying.drawImage(QRectF(surface.rect()), shown);
|
||||
}
|
||||
if (!options.clip.isNull()) {
|
||||
if (options.clip.format() != QImage::Format_Alpha8 || options.clip.size() != deviceBounds.size())
|
||||
throw std::logic_error("a folder clip must be device-sized alpha coverage");
|
||||
QPainter clipping(&surface);
|
||||
clipping.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
clipping.drawImage(QRectF(surface.rect()), options.clip, QRectF(area));
|
||||
}
|
||||
// Everything that can throw happens before the painter changes.
|
||||
const bool byHand = HslBlend::handles(options.blendMode);
|
||||
QImage composed = surface;
|
||||
if (byHand) {
|
||||
const QImage *target = dynamic_cast<const QImage *>(context.device());
|
||||
if (!target)
|
||||
throw std::logic_error("hue, saturation, color and luminosity need an image-backed painter");
|
||||
const QImage backdrop = target->copy(area).convertToFormat(QImage::Format_RGBA8888_Premultiplied);
|
||||
if (backdrop.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
composed = HslBlend::blend(backdrop, surface, options.blendMode, options.opacity);
|
||||
}
|
||||
const QPainter::CompositionMode mode = byHand ? QPainter::CompositionMode_Source : compositionMode(options.blendMode);
|
||||
context.save();
|
||||
context.setWorldTransform(context.deviceTransform().inverted() * context.worldTransform());
|
||||
context.setOpacity(byHand ? 1 : options.opacity);
|
||||
context.setCompositionMode(mode);
|
||||
context.drawImage(QRectF(area), composed);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The mode where alpha-white equals a clip of that coverage.
|
||||
QPainter::CompositionMode underCoverage(QPainter::CompositionMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
// These erase where the source is clear; clips do not.
|
||||
case QPainter::CompositionMode_Source:
|
||||
case QPainter::CompositionMode_Plus:
|
||||
return QPainter::CompositionMode_SourceOver;
|
||||
case QPainter::CompositionMode_Clear:
|
||||
return QPainter::CompositionMode_DestinationOut;
|
||||
case QPainter::CompositionMode_SourceIn:
|
||||
return QPainter::CompositionMode_SourceAtop;
|
||||
case QPainter::CompositionMode_SourceOut:
|
||||
return QPainter::CompositionMode_Xor;
|
||||
case QPainter::CompositionMode_DestinationIn:
|
||||
return QPainter::CompositionMode_Destination;
|
||||
case QPainter::CompositionMode_DestinationAtop:
|
||||
return QPainter::CompositionMode_DestinationOver;
|
||||
default:
|
||||
// The rest are linear in the source, clear pixels kept.
|
||||
if (mode >= QPainter::RasterOp_SourceOrDestination)
|
||||
throw std::logic_error("coverage has no meaning under a raster operation");
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void LayerRenderer::drawCoverage(const QImage &image, const LayerTransform &transform, QPainter &context)
|
||||
{
|
||||
if (image.format() != QImage::Format_Grayscale8)
|
||||
throw std::logic_error("coverage is drawn from a gray mask");
|
||||
const QPainter::CompositionMode mode = underCoverage(context.compositionMode());
|
||||
// Opacity is coverage too only where the mode is linear.
|
||||
if (mode != context.compositionMode() && context.opacity() < 1)
|
||||
throw std::logic_error("this composition mode takes no opacity under coverage");
|
||||
const QRectF bounds(-transform.size.width() / 2, -transform.size.height() / 2, transform.size.width(), transform.size.height());
|
||||
// CoreGraphics filters a shrinking mask; QPainter needs the halvings.
|
||||
const Reduced source = reduced(image, transform.size.width(), deviceScale(context), transform.sampling);
|
||||
// White, the mask as its alpha: the painter's mode blends.
|
||||
QImage white(source.image.size(), QImage::Format_ARGB32_Premultiplied);
|
||||
if (white.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
for (int y = 0; y < white.height(); ++y) {
|
||||
const uchar *mask = source.image.constScanLine(y);
|
||||
QRgb *pixels = reinterpret_cast<QRgb *>(white.scanLine(y));
|
||||
for (int x = 0; x < white.width(); ++x)
|
||||
pixels[x] = mask[x] * 0x01010101u;
|
||||
}
|
||||
QTransform placement;
|
||||
placement.translate(transform.center().x(), transform.center().y());
|
||||
placement.rotateRadians(transform.radians());
|
||||
placement.scale(transform.flipX ? -1 : 1, transform.flipY ? -1 : 1);
|
||||
context.save();
|
||||
setSampling(context, quality(transform.sampling), transform.sampling);
|
||||
context.setCompositionMode(mode);
|
||||
context.setTransform(placement, true);
|
||||
context.drawImage(coverage(source, bounds), white);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
InterpolationQuality LayerRenderer::interpolation(LayerSampling sampling, double finalFactor)
|
||||
{
|
||||
if (sampling == LayerSampling::nearest)
|
||||
return InterpolationQuality::none;
|
||||
return finalFactor <= 1 ? InterpolationQuality::low : quality(sampling);
|
||||
}
|
||||
|
||||
LayerRenderer::Reduced LayerRenderer::reduced(const QImage &image, double width, double device, LayerSampling sampling)
|
||||
{
|
||||
if (sampling == LayerSampling::nearest)
|
||||
return {image, 0, 1, 1};
|
||||
const int level = DownsampleCache::level(width * device / std::max(1, image.width()));
|
||||
const DownsampleCache::Reduced result = DownsampleCache::shared().imageAtLevel(image, level);
|
||||
return {result.image, result.level,
|
||||
double(result.image.width() << result.level) / std::max(1, image.width()),
|
||||
double(result.image.height() << result.level) / std::max(1, image.height())};
|
||||
}
|
||||
|
||||
QRectF LayerRenderer::coverage(const Reduced &reduced, const QRectF &bounds)
|
||||
{
|
||||
return {bounds.left(), bounds.top(), bounds.width() * reduced.widthScale, bounds.height() * reduced.heightScale};
|
||||
}
|
||||
|
||||
double LayerRenderer::deviceScale(const QPainter &context)
|
||||
{
|
||||
const QTransform device = context.deviceTransform();
|
||||
return std::hypot(device.m11(), device.m12());
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "Document/LayerAppearance.h"
|
||||
#include "Document/LayerTransform.h"
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
class RasterSnapshot;
|
||||
|
||||
// Draws layers top-left, shared by the canvas and export.
|
||||
namespace LayerRenderer {
|
||||
struct Options {
|
||||
double scale = 1;
|
||||
double opacity = 1;
|
||||
LayerBlendMode blendMode = LayerBlendMode::normal;
|
||||
// A null image means no mask.
|
||||
QImage mask = QImage();
|
||||
// Folder masks as device-sized alpha coverage; null means none.
|
||||
QImage clip = QImage();
|
||||
};
|
||||
|
||||
// An image halved for a large reduction, and its overhang.
|
||||
struct Reduced {
|
||||
QImage image;
|
||||
int level;
|
||||
double widthScale;
|
||||
double heightScale;
|
||||
};
|
||||
|
||||
// Replacement tiles over a source, in a pixel grid.
|
||||
struct BrushPreview {
|
||||
std::vector<BrushPatch> patches;
|
||||
int pixelWidth;
|
||||
int pixelHeight;
|
||||
// Patches are coverage the source shows through.
|
||||
bool paintingMask;
|
||||
// Where the source sits in the grid; absent means everywhere.
|
||||
std::optional<QRectF> sourceRect = std::nullopt;
|
||||
// A painted source, drawn from its tiles.
|
||||
std::shared_ptr<const RasterSnapshot> raster = nullptr;
|
||||
// Stands in for the raster's base when not null.
|
||||
QImage rasterBase = QImage();
|
||||
};
|
||||
|
||||
void draw(const QImage &image, const LayerTransform &transform, QPointF center, QPainter &context,
|
||||
const Options &options = {});
|
||||
// Fills white through a gray mask, as the painter blends.
|
||||
void drawCoverage(const QImage &image, const LayerTransform &transform, QPainter &context);
|
||||
// Previews tiles without a full-size raster; blends exactly once.
|
||||
void drawBrushPreview(const QImage &image, const LayerTransform &transform, QPointF center, QPainter &context,
|
||||
const Options &options, const BrushPreview &preview);
|
||||
// Composes a layer aside, composites it once; `veil` repaints coverage.
|
||||
void composite(QPainter &context, const QTransform &placement, const QRectF &extent, LayerSampling sampling,
|
||||
InterpolationQuality quality, const Options &options, const QRectF &maskBounds,
|
||||
const std::function<void(QPainter &)> &body, const std::function<void(QPainter &)> &veil = {});
|
||||
InterpolationQuality interpolation(LayerSampling sampling, double finalFactor);
|
||||
Reduced reduced(const QImage &image, double width, double device, LayerSampling sampling);
|
||||
QRectF coverage(const Reduced &reduced, const QRectF &bounds);
|
||||
double deviceScale(const QPainter &context);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
#include "Rendering/LiveMaskRenderer.h"
|
||||
#include "IO/ImageExporter.h"
|
||||
#include "Logging.h"
|
||||
#include "Rendering/LayerRenderer.h"
|
||||
|
||||
extern "C" {
|
||||
#include "BrushPixels.h"
|
||||
}
|
||||
|
||||
LiveMaskRenderer::LiveMaskRenderer(Source source, DrawOwn drawOwn, qint64 pixelBudget)
|
||||
: m_source(std::move(source)), m_drawOwn(std::move(drawOwn)), m_pixelBudget(pixelBudget)
|
||||
{
|
||||
}
|
||||
|
||||
void LiveMaskRenderer::prepareStacks(const std::vector<QUuid> &ids, const std::function<std::optional<QUuid>(QUuid)> &parent,
|
||||
const std::function<LayerBlendMode(QUuid)> &blend)
|
||||
{
|
||||
for (const QUuid &id : ids)
|
||||
m_modes.insert(id, blend(id));
|
||||
for (size_t index = 0; index < ids.size(); ++index) {
|
||||
const QUuid base = ids[index];
|
||||
if (m_source(base))
|
||||
continue;
|
||||
std::vector<QUuid> children;
|
||||
for (size_t next = index + 1; next < ids.size(); ++next) {
|
||||
if (m_source(ids[next]) != base || parent(ids[next]) != parent(base))
|
||||
break;
|
||||
children.push_back(ids[next]);
|
||||
}
|
||||
if (children.empty())
|
||||
continue;
|
||||
m_stackModes.insert(base, blend(base));
|
||||
m_stacked.unite(QSet<QUuid>(children.begin(), children.end()));
|
||||
m_stacks.insert(base, std::move(children));
|
||||
}
|
||||
}
|
||||
|
||||
void LiveMaskRenderer::drawComposite(QUuid id, QPainter &context, const QImage &clip)
|
||||
{
|
||||
if (m_stacked.contains(id))
|
||||
return;
|
||||
// Clipped, an adjustment draws inside its base's stack alone.
|
||||
if (adjustment(id)) {
|
||||
if (!m_source(id))
|
||||
adjust(id, context, clip);
|
||||
return;
|
||||
}
|
||||
const auto children = m_stacks.constFind(id);
|
||||
const QSize device(context.device()->width(), context.device()->height());
|
||||
QImage group, alpha;
|
||||
if (children != m_stacks.constEnd() && fits(context)) {
|
||||
group = QImage(device, QImage::Format_RGBA8888_Premultiplied);
|
||||
alpha = QImage(device, QImage::Format_Grayscale8);
|
||||
if (group.isNull() || alpha.isNull())
|
||||
qCWarning(lcRendering) << "a clipping stack could not be allocated:" << device;
|
||||
}
|
||||
if (group.isNull() || alpha.isNull()) {
|
||||
// Without a group each child draws alone, through the base.
|
||||
if (children != m_stacks.constEnd()) {
|
||||
for (const QUuid &child : *children)
|
||||
m_stacked.remove(child);
|
||||
}
|
||||
draw(id, context, clip);
|
||||
return;
|
||||
}
|
||||
group.fill(0);
|
||||
{
|
||||
QPainter painter(&group);
|
||||
painter.setTransform(context.deviceTransform());
|
||||
m_drawOwn(id, painter, QImage());
|
||||
}
|
||||
// Children blend at the base's full coverage; its alpha returns.
|
||||
layer_extract_alpha(group.constBits(), size_t(group.bytesPerLine()), alpha.bits(), size_t(alpha.bytesPerLine()),
|
||||
size_t(device.width()), size_t(device.height()));
|
||||
layer_unpremultiply_opaque(group.bits(), size_t(group.bytesPerLine()), size_t(device.width()), size_t(device.height()));
|
||||
{
|
||||
QPainter painter(&group);
|
||||
painter.setTransform(context.deviceTransform());
|
||||
for (const QUuid &child : *children) {
|
||||
if (adjustment(child))
|
||||
adjust(child, painter, QImage());
|
||||
else
|
||||
m_drawOwn(child, painter, QImage());
|
||||
}
|
||||
}
|
||||
layer_restore_alpha(group.bits(), size_t(group.bytesPerLine()), alpha.constBits(), size_t(alpha.bytesPerLine()),
|
||||
size_t(device.width()), size_t(device.height()));
|
||||
// Device pixels already: one to one, at the painter's opacity.
|
||||
LayerRenderer::composite(context, context.deviceTransform().inverted(), QRectF(group.rect()), LayerSampling::nearest,
|
||||
InterpolationQuality::none, {.opacity = context.opacity(), .blendMode = m_stackModes.value(id), .clip = clip}, QRectF(),
|
||||
[&](QPainter &aside) { aside.drawImage(QRectF(group.rect()), group); });
|
||||
}
|
||||
|
||||
void LiveMaskRenderer::draw(QUuid id, QPainter &context, const QImage &clip)
|
||||
{
|
||||
// drawOwn's painter changes end here, even when it throws.
|
||||
struct Saved {
|
||||
QPainter &painter;
|
||||
explicit Saved(QPainter &context) : painter(context) { painter.save(); }
|
||||
~Saved() { painter.restore(); }
|
||||
} saved(context);
|
||||
const std::optional<QUuid> sourceID = m_source(id);
|
||||
if (!sourceID) {
|
||||
m_drawOwn(id, context, clip);
|
||||
return;
|
||||
}
|
||||
const std::optional<QImage> shown = coverage(*sourceID, context);
|
||||
if (!shown)
|
||||
return;
|
||||
QImage combined = *shown;
|
||||
if (!clip.isNull()) {
|
||||
// A failed copy of the cached coverage must not pass.
|
||||
QPainter multiplying(&combined);
|
||||
if (!multiplying.isActive())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
multiplying.setCompositionMode(QPainter::CompositionMode_DestinationIn);
|
||||
multiplying.drawImage(QRectF(combined.rect()), clip);
|
||||
}
|
||||
m_drawOwn(id, context, combined);
|
||||
}
|
||||
|
||||
bool LiveMaskRenderer::fits(const QPainter &context) const
|
||||
{
|
||||
const qint64 width = context.device()->width(), height = context.device()->height();
|
||||
return width > 0 && height > 0 && width * height <= m_pixelBudget;
|
||||
}
|
||||
|
||||
std::optional<QImage> LiveMaskRenderer::coverage(QUuid id, const QPainter &context)
|
||||
{
|
||||
if (const auto found = m_cache.constFind(id); found != m_cache.constEnd())
|
||||
return *found;
|
||||
if (!fits(context))
|
||||
qCWarning(lcRendering) << "clip coverage passes its pixel budget:" << context.device()->width() << "x" << context.device()->height();
|
||||
if (m_visiting.contains(id) || m_visiting.size() >= 256 || !fits(context))
|
||||
return std::nullopt;
|
||||
struct Visit {
|
||||
QSet<QUuid> &visiting;
|
||||
QUuid id;
|
||||
~Visit() { visiting.remove(id); }
|
||||
} visit{m_visiting, id};
|
||||
m_visiting.insert(id);
|
||||
const QSize device(context.device()->width(), context.device()->height());
|
||||
QImage pixels(device, QImage::Format_RGBA8888_Premultiplied), gray(device, QImage::Format_Alpha8);
|
||||
if (pixels.isNull() || gray.isNull()) {
|
||||
qCWarning(lcRendering) << "clip coverage could not be allocated:" << device;
|
||||
return std::nullopt;
|
||||
}
|
||||
pixels.fill(0);
|
||||
{
|
||||
QPainter painter(&pixels);
|
||||
painter.setTransform(context.deviceTransform());
|
||||
draw(id, painter);
|
||||
}
|
||||
layer_extract_alpha(pixels.constBits(), size_t(pixels.bytesPerLine()), gray.bits(), size_t(gray.bytesPerLine()),
|
||||
size_t(device.width()), size_t(device.height()));
|
||||
m_cache.insert(id, gray);
|
||||
return gray;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Colours blend at full coverage; the original alpha then returns.
|
||||
QImage blended(const QImage &original, const QImage &adjusted, LayerBlendMode mode)
|
||||
{
|
||||
const int width = original.width(), height = original.height();
|
||||
QImage base = original.copy(), top = adjusted.copy(), alpha(original.size(), QImage::Format_Grayscale8);
|
||||
if (base.isNull() || top.isNull() || alpha.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
layer_extract_alpha(base.constBits(), size_t(base.bytesPerLine()), alpha.bits(), size_t(alpha.bytesPerLine()), size_t(width), size_t(height));
|
||||
layer_unpremultiply_opaque(base.bits(), size_t(base.bytesPerLine()), size_t(width), size_t(height));
|
||||
layer_unpremultiply_opaque(top.bits(), size_t(top.bytesPerLine()), size_t(width), size_t(height));
|
||||
{
|
||||
QPainter painter(&base);
|
||||
LayerRenderer::composite(painter, QTransform(), QRectF(base.rect()), LayerSampling::nearest, InterpolationQuality::none,
|
||||
{.opacity = 1, .blendMode = mode}, QRectF(), [&](QPainter &aside) { aside.drawImage(QRectF(top.rect()), top); });
|
||||
}
|
||||
layer_restore_alpha(base.bits(), size_t(base.bytesPerLine()), alpha.constBits(), size_t(alpha.bytesPerLine()), size_t(width), size_t(height));
|
||||
return base;
|
||||
}
|
||||
|
||||
// Adjusted over original by opacity, coverage and clip.
|
||||
QImage mixed(const QImage &adjusted, const QImage &original, const QImage &coverage, const QImage &clip, double opacity)
|
||||
{
|
||||
QImage result = original.copy();
|
||||
if (result.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
for (int y = 0; y < result.height(); ++y) {
|
||||
const uchar *top = adjusted.constScanLine(y), *weight = coverage.constScanLine(y);
|
||||
const uchar *outer = clip.isNull() ? nullptr : clip.constScanLine(y);
|
||||
uchar *target = result.scanLine(y);
|
||||
for (int x = 0; x < result.width(); ++x) {
|
||||
const double share = opacity * weight[x] / 255 * (outer ? outer[x] / 255.0 : 1);
|
||||
for (int channel = 0; channel < 4; ++channel) {
|
||||
const int index = x * 4 + channel;
|
||||
target[index] = uchar(std::lround(target[index] + (top[index] - target[index]) * share));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
void LiveMaskRenderer::adjust(QUuid id, QPainter &context, const QImage &clip)
|
||||
{
|
||||
auto *device = dynamic_cast<QImage *>(context.device());
|
||||
if (!device)
|
||||
throw std::logic_error("an adjustment reads a painter on an image");
|
||||
if (!fits(context)) {
|
||||
qCWarning(lcRendering) << "an adjustment passes its pixel budget:" << device->size();
|
||||
return;
|
||||
}
|
||||
// The document the device shows, where Grain's pattern sits.
|
||||
const QRectF region = context.deviceTransform().inverted().mapRect(QRectF(device->rect()));
|
||||
try {
|
||||
// The kernels' byte order, one image pixel a device pixel.
|
||||
QImage original = device->convertToFormat(QImage::Format_RGBA8888_Premultiplied).copy();
|
||||
if (original.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
original.setDevicePixelRatio(1);
|
||||
QImage adjusted = adjustment(id).value().apply(original, region);
|
||||
const LayerBlendMode mode = m_modes.value(id, LayerBlendMode::normal);
|
||||
if (mode != LayerBlendMode::normal)
|
||||
adjusted = blended(original, adjusted, mode);
|
||||
QImage coverage(device->size(), QImage::Format_Alpha8);
|
||||
if (coverage.isNull())
|
||||
throw ExportError(ExportError::Kind::render);
|
||||
coverage.fill(255);
|
||||
adjustmentClip(id, context, coverage);
|
||||
const QImage result = mixed(adjusted, original, coverage, clip, adjustmentOpacity(id));
|
||||
// Back in device pixels, through the painter's own clip.
|
||||
context.save();
|
||||
context.setTransform(context.deviceTransform().inverted(), true);
|
||||
context.setCompositionMode(QPainter::CompositionMode_Source);
|
||||
context.drawImage(QRectF(result.rect()), result);
|
||||
context.restore();
|
||||
} catch (const ExportError &error) {
|
||||
qCWarning(lcRendering) << "an adjustment could not be drawn:" << error.what();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include "Document/LayerAdjustment.h"
|
||||
#include "Document/LayerAppearance.h"
|
||||
#include <QHash>
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <QSet>
|
||||
#include <QUuid>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
// Per-render dependency cache: a layer shows through its source's alpha.
|
||||
class LiveMaskRenderer {
|
||||
public:
|
||||
static constexpr qint64 pixelBudget = 100'000'000;
|
||||
using Source = std::function<std::optional<QUuid>(QUuid)>;
|
||||
// Draws a layer through `clip`: device-sized coverage, null for none.
|
||||
using DrawOwn = std::function<void(QUuid, QPainter &, const QImage &clip)>;
|
||||
|
||||
LiveMaskRenderer(Source source, DrawOwn drawOwn, qint64 pixelBudget = LiveMaskRenderer::pixelBudget);
|
||||
// Clipping stacks share the base's alpha instead of repainting it.
|
||||
void prepareStacks(const std::vector<QUuid> &ids, const std::function<std::optional<QUuid>(QUuid)> &parent,
|
||||
const std::function<LayerBlendMode(QUuid)> &blend);
|
||||
void drawComposite(QUuid id, QPainter &context, const QImage &clip = QImage());
|
||||
void draw(QUuid id, QPainter &context, const QImage &clip = QImage());
|
||||
// An adjustment layer's settings, opacity and own mask as coverage.
|
||||
std::function<std::optional<LayerAdjustment>(QUuid)> adjustment = [](QUuid) { return std::optional<LayerAdjustment>(); };
|
||||
std::function<double(QUuid)> adjustmentOpacity = [](QUuid) { return 1.0; };
|
||||
std::function<void(QUuid, const QPainter &, QImage &coverage)> adjustmentClip = [](QUuid, const QPainter &, QImage &) {};
|
||||
|
||||
private:
|
||||
// The pixels beneath, adjusted and mixed back through coverage.
|
||||
void adjust(QUuid id, QPainter &context, const QImage &clip);
|
||||
// A layer's alpha through its own source; nil on failure.
|
||||
std::optional<QImage> coverage(QUuid id, const QPainter &context);
|
||||
bool fits(const QPainter &context) const;
|
||||
|
||||
const Source m_source;
|
||||
const DrawOwn m_drawOwn;
|
||||
const qint64 m_pixelBudget;
|
||||
QHash<QUuid, QImage> m_cache;
|
||||
QSet<QUuid> m_visiting;
|
||||
QHash<QUuid, std::vector<QUuid>> m_stacks;
|
||||
QSet<QUuid> m_stacked;
|
||||
QHash<QUuid, LayerBlendMode> m_stackModes;
|
||||
// Every prepared layer's mode, as Swift's `blendMode`.
|
||||
QHash<QUuid, LayerBlendMode> m_modes;
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include <QThread>
|
||||
#include <QThreadPool>
|
||||
#include <QtConcurrent>
|
||||
#include <utility>
|
||||
|
||||
// QtConcurrent's blockingMap, which deadlocks a full pool from inside.
|
||||
namespace PoolMap {
|
||||
// A pool thread waiting on the pool lends its place.
|
||||
template <typename Sequence, typename Function>
|
||||
void blocking(Sequence &sequence, Function &&function)
|
||||
{
|
||||
struct Lent {
|
||||
QThreadPool *const pool;
|
||||
const bool lent;
|
||||
~Lent()
|
||||
{
|
||||
if (lent)
|
||||
pool->reserveThread();
|
||||
}
|
||||
} guard{QThreadPool::globalInstance(), QThreadPool::globalInstance()->contains(QThread::currentThread())};
|
||||
if (guard.lent)
|
||||
guard.pool->releaseThread();
|
||||
QtConcurrent::blockingMap(sequence, std::forward<Function>(function));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace {
|
||||
using Cell = std::pair<int, int>;
|
||||
|
||||
std::vector<Cell> cells(const QRectF &rect)
|
||||
{
|
||||
std::vector<Cell> result;
|
||||
if (rect.isEmpty())
|
||||
return result;
|
||||
for (int y = int(std::floor(rect.top() / 256)); y <= int(std::ceil(rect.bottom() / 256)) - 1; ++y) {
|
||||
for (int x = int(std::floor(rect.left() / 256)); x <= int(std::ceil(rect.right() / 256)) - 1; ++x)
|
||||
result.push_back({x, y});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Borrowed pixels, as CGImage.cropping; valid while image lives.
|
||||
QImage view(const QImage &image, const QRect &rect)
|
||||
{
|
||||
return QImage(image.constScanLine(rect.top()) + rect.left() * image.depth() / 8, rect.width(), rect.height(),
|
||||
image.bytesPerLine(), image.format());
|
||||
}
|
||||
|
||||
BrushPatch cropped(const BrushPatch &patch, const QRectF &rect)
|
||||
{
|
||||
return {rect, patch.image.copy(rect.translated(-patch.rect.topLeft()).toAlignedRect())};
|
||||
}
|
||||
|
||||
std::vector<BrushPatch> without(const BrushPatch &piece, const QRectF &overlap)
|
||||
{
|
||||
const QRectF r = piece.rect;
|
||||
const QRectF rects[] = {QRectF(r.left(), r.top(), r.width(), overlap.top() - r.top()),
|
||||
QRectF(r.left(), overlap.bottom(), r.width(), r.bottom() - overlap.bottom()),
|
||||
QRectF(r.left(), overlap.top(), overlap.left() - r.left(), overlap.height()),
|
||||
QRectF(overlap.right(), overlap.top(), r.right() - overlap.right(), overlap.height())};
|
||||
std::vector<BrushPatch> result;
|
||||
for (const QRectF &rect : rects) {
|
||||
if (rect.width() > 0 && rect.height() > 0)
|
||||
result.push_back(cropped(piece, rect));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
RasterSnapshot::RasterSnapshot(int width, int height, QImage base, QRectF baseRect, std::vector<BrushPatch> patches,
|
||||
bool isMask, std::optional<QPointF> alignment)
|
||||
: width(width), height(height), base(std::move(base)), baseRect(baseRect), patches(std::move(patches)),
|
||||
isMask(isMask), alignment(alignment.value_or(baseRect.topLeft()))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<const RasterSnapshot> RasterSnapshot::replacing(const std::optional<ImportedImage> &source,
|
||||
const QRectF &sourceRect,
|
||||
const std::vector<BrushPatch> &added,
|
||||
const QRectF &crop, bool isMask)
|
||||
{
|
||||
const std::shared_ptr<const RasterSnapshot> old = source ? source->raster : nullptr;
|
||||
const QPointF shift = sourceRect.topLeft() - crop.topLeft();
|
||||
std::vector<BrushPatch> additions;
|
||||
for (const BrushPatch &patch : added)
|
||||
additions.push_back({patch.rect.translated(-crop.topLeft()), patch.image});
|
||||
// Indexed by tile, so the handoff follows touched tiles.
|
||||
std::map<Cell, std::vector<int>> buckets;
|
||||
for (int index = 0; index < int(additions.size()); ++index) {
|
||||
for (const Cell &cell : cells(additions[index].rect))
|
||||
buckets[cell].push_back(index);
|
||||
}
|
||||
std::vector<BrushPatch> kept;
|
||||
for (const BrushPatch &oldPatch : old ? old->patches : std::vector<BrushPatch>()) {
|
||||
const BrushPatch patch{oldPatch.rect.translated(shift), oldPatch.image};
|
||||
std::set<int> candidates;
|
||||
for (const Cell &cell : cells(patch.rect)) {
|
||||
if (const auto found = buckets.find(cell); found != buckets.end())
|
||||
candidates.insert(found->second.begin(), found->second.end());
|
||||
}
|
||||
std::vector<BrushPatch> pieces{patch};
|
||||
for (int index : candidates) {
|
||||
std::vector<BrushPatch> split;
|
||||
for (const BrushPatch &piece : pieces) {
|
||||
const QRectF overlap = piece.rect.intersected(additions[index].rect);
|
||||
if (overlap.isEmpty()) {
|
||||
split.push_back(piece);
|
||||
continue;
|
||||
}
|
||||
const std::vector<BrushPatch> rest = without(piece, overlap);
|
||||
split.insert(split.end(), rest.begin(), rest.end());
|
||||
}
|
||||
pieces = std::move(split);
|
||||
}
|
||||
kept.insert(kept.end(), pieces.begin(), pieces.end());
|
||||
}
|
||||
kept.insert(kept.end(), additions.begin(), additions.end());
|
||||
const QRectF bounds(0, 0, crop.width(), crop.height());
|
||||
std::vector<BrushPatch> inside;
|
||||
for (const BrushPatch &patch : kept) {
|
||||
const QRectF rect = patch.rect.intersected(bounds);
|
||||
if (rect.isEmpty())
|
||||
continue;
|
||||
inside.push_back(rect == patch.rect ? patch : cropped(patch, rect));
|
||||
}
|
||||
const QImage base = old ? old->base : source ? source->image() : QImage();
|
||||
const QRectF baseRect = old ? old->baseRect.translated(shift) : sourceRect.translated(-crop.topLeft());
|
||||
const QPointF alignment = sourceRect.topLeft() + (old ? old->alignment : QPointF(0, 0)) - crop.topLeft();
|
||||
return std::make_shared<const RasterSnapshot>(int(crop.width()), int(crop.height()), base, baseRect,
|
||||
std::move(inside), isMask, alignment);
|
||||
}
|
||||
|
||||
void RasterSnapshot::draw(const QRectF &rect, QPainter &context) const
|
||||
{
|
||||
context.save();
|
||||
context.setClipRect(rect, Qt::IntersectClip);
|
||||
context.setRenderHint(QPainter::Antialiasing, false);
|
||||
// A grown mask reveals the pixels outside it.
|
||||
if (isMask)
|
||||
context.fillRect(rect, Qt::white);
|
||||
const double sx = rect.width() / width, sy = rect.height() / height;
|
||||
const auto mapped = [&](const QRectF &r) {
|
||||
return QRectF(rect.left() + r.left() * sx, rect.top() + r.top() * sy, r.width() * sx, r.height() * sy);
|
||||
};
|
||||
const QRectF visible = BrushRaster::visibleRect(context);
|
||||
if (!base.isNull()) {
|
||||
const QRectF target = mapped(baseRect);
|
||||
const QRectF overlap = target.intersected(visible);
|
||||
if (!overlap.isEmpty()) {
|
||||
const QRect crop = QRectF((overlap.left() - target.left()) / target.width() * base.width(),
|
||||
(overlap.top() - target.top()) / target.height() * base.height(),
|
||||
overlap.width() / target.width() * base.width(),
|
||||
overlap.height() / target.height() * base.height())
|
||||
.toAlignedRect().intersected(base.rect());
|
||||
if (!crop.isEmpty()) {
|
||||
const QRectF destination(target.left() + double(crop.left()) / base.width() * target.width(),
|
||||
target.top() + double(crop.top()) / base.height() * target.height(),
|
||||
double(crop.width()) / base.width() * target.width(),
|
||||
double(crop.height()) / base.height() * target.height());
|
||||
BrushRaster::draw(view(base, crop), destination, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const BrushPatch &patch : patches) {
|
||||
if (mapped(patch.rect).intersects(visible))
|
||||
BrushRaster::draw(patch.image, mapped(patch.rect), context);
|
||||
}
|
||||
context.restore();
|
||||
}
|
||||
|
||||
QImage RasterSnapshot::makeImage() const
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
if (m_materialized.isNull()) {
|
||||
QImage surface = BrushRaster::context(width, height, isMask);
|
||||
QPainter painter(&surface);
|
||||
draw(QRectF(0, 0, width, height), painter);
|
||||
painter.end();
|
||||
m_materialized = surface;
|
||||
}
|
||||
return m_materialized;
|
||||
}
|
||||
|
||||
bool RasterSnapshot::hasMaterializedPixels() const
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
return !m_materialized.isNull();
|
||||
}
|
||||
|
||||
QImage RasterSnapshot::thumbnail() const
|
||||
{
|
||||
const double factor = std::min(1.0, 96.0 / std::max(width, height));
|
||||
QImage surface = BrushRaster::context(std::max(1, int(width * factor)), std::max(1, int(height * factor)), isMask);
|
||||
QPainter painter(&surface);
|
||||
draw(QRectF(0, 0, surface.width(), surface.height()), painter);
|
||||
return surface;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include "Document/BrushStroke.h"
|
||||
#include "IO/ImageImporter.h"
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
// Immutable sparse raster; paint commits share untouched tiles.
|
||||
class RasterSnapshot {
|
||||
public:
|
||||
const int width;
|
||||
const int height;
|
||||
const QImage base;
|
||||
const QRectF baseRect;
|
||||
const std::vector<BrushPatch> patches;
|
||||
const bool isMask;
|
||||
// Origin of the halving grids, kept across commits.
|
||||
const QPointF alignment;
|
||||
|
||||
RasterSnapshot(int width, int height, QImage base, QRectF baseRect, std::vector<BrushPatch> patches,
|
||||
bool isMask = false, std::optional<QPointF> alignment = std::nullopt);
|
||||
|
||||
static std::shared_ptr<const RasterSnapshot> replacing(const std::optional<ImportedImage> &source,
|
||||
const QRectF &sourceRect,
|
||||
const std::vector<BrushPatch> &patches,
|
||||
const QRectF &crop, bool isMask = false);
|
||||
|
||||
void draw(const QRectF &rect, QPainter &context) const;
|
||||
QImage makeImage() const;
|
||||
bool hasMaterializedPixels() const;
|
||||
QImage thumbnail() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex m_lock;
|
||||
mutable QImage m_materialized;
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
#include "Rendering/SampleRingOverlay.h"
|
||||
|
||||
QRegion SampleRingOverlay::update(std::optional<QPointF> point, const PaletteColor &original, const PaletteColor &sampled)
|
||||
{
|
||||
QRegion dirty;
|
||||
if (m_frame)
|
||||
dirty += m_frame->toAlignedRect();
|
||||
m_frame = point ? std::optional(QRectF(point->x() - 58, point->y() - 58, 116, 116)) : std::nullopt;
|
||||
m_original = original;
|
||||
m_sampled = sampled;
|
||||
if (m_frame)
|
||||
dirty += m_frame->toAlignedRect();
|
||||
return dirty;
|
||||
}
|
||||
|
||||
void SampleRingOverlay::draw(QPainter &painter) const
|
||||
{
|
||||
if (!m_frame)
|
||||
return;
|
||||
painter.save();
|
||||
painter.setRenderHint(QPainter::Antialiasing, true);
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
const QRectF ring = m_frame->adjusted(15, 15, -15, -15);
|
||||
painter.setPen(QPen(QColor::fromRgbF(0.45f, 0.45f, 0.45f), 24));
|
||||
painter.drawEllipse(ring);
|
||||
// The sampled colour on top, the original below; restore unclips.
|
||||
for (const auto &[colour, top] : {std::pair(m_sampled, m_frame->top()), std::pair(m_original, m_frame->center().y())}) {
|
||||
painter.setClipRect(QRectF(m_frame->left(), top, m_frame->width(), m_frame->height() / 2));
|
||||
painter.setPen(QPen(colour.color(), 16));
|
||||
painter.drawEllipse(ring);
|
||||
}
|
||||
painter.restore();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include "Document/ColorPalette.h"
|
||||
#include <QPainter>
|
||||
#include <QRegion>
|
||||
#include <optional>
|
||||
|
||||
// Swift's sample ring: the sampled colour over the original.
|
||||
class SampleRingOverlay {
|
||||
public:
|
||||
// Rings a view point or hides; returns the areas touched.
|
||||
QRegion update(std::optional<QPointF> point, const PaletteColor &original, const PaletteColor &sampled);
|
||||
void draw(QPainter &painter) const;
|
||||
std::optional<QRectF> frame() const { return m_frame; }
|
||||
PaletteColor original() const { return m_original; }
|
||||
PaletteColor sampled() const { return m_sampled; }
|
||||
|
||||
private:
|
||||
std::optional<QRectF> m_frame;
|
||||
PaletteColor m_original = PaletteColor::black();
|
||||
PaletteColor m_sampled = PaletteColor::black();
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "Rendering/SelectionIcons.h"
|
||||
#include <QPainterPath>
|
||||
|
||||
namespace {
|
||||
void dashed(QPainter &painter)
|
||||
{
|
||||
QPen pen = painter.pen();
|
||||
pen.setDashPattern({2.2, 1.8});
|
||||
pen.setCapStyle(Qt::FlatCap);
|
||||
painter.setPen(pen);
|
||||
}
|
||||
}
|
||||
|
||||
void SelectionIcons::paint(QPainter &painter, SelectionIcon icon)
|
||||
{
|
||||
switch (icon) {
|
||||
case SelectionIcon::rectangleMarquee:
|
||||
dashed(painter);
|
||||
painter.drawRoundedRect(QRectF(2.5, 3.5, 13, 11), 2, 2);
|
||||
return;
|
||||
// Swift's circle.dashed: the Marquee in Ellipse mode.
|
||||
case SelectionIcon::ellipseMarquee:
|
||||
dashed(painter);
|
||||
painter.drawEllipse(QRectF(2.5, 2.5, 13, 13));
|
||||
return;
|
||||
case SelectionIcon::freehandLasso: {
|
||||
painter.drawEllipse(QRectF(2, 2.5, 14, 8.5));
|
||||
QPainterPath tail(QPointF(5.2, 10.2));
|
||||
tail.cubicTo(QPointF(3.2, 12), QPointF(4.6, 14.2), QPointF(6.6, 13.2));
|
||||
tail.cubicTo(QPointF(8, 12.4), QPointF(6.4, 10.8), QPointF(5.2, 12.2));
|
||||
tail.cubicTo(QPointF(4.4, 13.4), QPointF(5, 15.6), QPointF(7.4, 16));
|
||||
painter.drawPath(tail);
|
||||
return;
|
||||
}
|
||||
// Swift's PolygonalLassoToolIcon: loop, knot and rope as segments.
|
||||
case SelectionIcon::polygonalLasso:
|
||||
painter.drawPolygon(QPolygonF{QPointF(1.2, 7.0), QPointF(4.0, 2.4), QPointF(11.8, 1.8), QPointF(16.8, 5.2), QPointF(15.6, 10.4), QPointF(7.0, 11.6)});
|
||||
painter.drawPolygon(QPolygonF{QPointF(8.9, 10.9), QPointF(13.3, 10.5), QPointF(11.6, 14.5)});
|
||||
painter.drawLine(QPointF(11.6, 14.5), QPointF(12.9, 17.3));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <QPainter>
|
||||
|
||||
// Which selection tool an icon names, by its kind.
|
||||
enum class SelectionIcon { freehandLasso, polygonalLasso, rectangleMarquee, ellipseMarquee };
|
||||
|
||||
// Icons the rail and the cursors share, 18-unit grid.
|
||||
namespace SelectionIcons {
|
||||
// Draws with the painter's pen; the Marquee's take a dash.
|
||||
void paint(QPainter &painter, SelectionIcon icon);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
#include "Rendering/TextLayout.h"
|
||||
#include "Logging.h"
|
||||
#include <QPainter>
|
||||
#include <QRegularExpression>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <fontconfig/fontconfig.h>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
QString text(FcPattern *pattern, const char *object)
|
||||
{
|
||||
FcChar8 *value = nullptr;
|
||||
if (FcPatternGetString(pattern, object, 0, &value) != FcResultMatch)
|
||||
return QString();
|
||||
return QString::fromUtf8(reinterpret_cast<const char *>(value));
|
||||
}
|
||||
|
||||
// Each installed face by PostScript name: its family and style.
|
||||
const std::map<QString, std::pair<QString, QString>> &faces()
|
||||
{
|
||||
static const std::map<QString, std::pair<QString, QString>> listed = [] {
|
||||
std::map<QString, std::pair<QString, QString>> found;
|
||||
FcPattern *pattern = FcPatternCreate();
|
||||
FcObjectSet *objects = FcObjectSetBuild(FC_POSTSCRIPT_NAME, FC_FAMILY, FC_STYLE, nullptr);
|
||||
FcFontSet *set = FcFontList(nullptr, pattern, objects);
|
||||
for (int index = 0; set && index < set->nfont; ++index) {
|
||||
const QString name = text(set->fonts[index], FC_POSTSCRIPT_NAME);
|
||||
if (!name.isEmpty())
|
||||
found.emplace(name, std::pair(text(set->fonts[index], FC_FAMILY), text(set->fonts[index], FC_STYLE)));
|
||||
}
|
||||
if (set)
|
||||
FcFontSetDestroy(set);
|
||||
FcObjectSetDestroy(objects);
|
||||
FcPatternDestroy(pattern);
|
||||
qCInfo(lcRendering) << "fontconfig lists" << int(found.size()) << "faces";
|
||||
return found;
|
||||
}();
|
||||
return listed;
|
||||
}
|
||||
}
|
||||
|
||||
QFont TextLayout::font(const LayerTextStyle &style)
|
||||
{
|
||||
QFont font;
|
||||
if (faces().contains(style.fontName)) {
|
||||
font.setFamily(faces().at(style.fontName).first);
|
||||
font.setStyleName(faces().at(style.fontName).second);
|
||||
} else {
|
||||
// Not installed: Qt's match, where macOS takes its own.
|
||||
font.setFamily(style.fontName);
|
||||
}
|
||||
// A point is a pixel here; Qt's faces come whole.
|
||||
font.setPixelSize(qRound(style.fontSize));
|
||||
// Swift's kern: no pairs; spacing after every letter.
|
||||
font.setKerning(false);
|
||||
font.setLetterSpacing(QFont::AbsoluteSpacing, style.tracking);
|
||||
font.setHintingPreference(QFont::PreferNoHinting);
|
||||
return font;
|
||||
}
|
||||
|
||||
QStringList TextLayout::availableFonts()
|
||||
{
|
||||
QStringList names;
|
||||
for (const auto &[name, face] : faces())
|
||||
names << name;
|
||||
return names;
|
||||
}
|
||||
|
||||
TextLines::TextLines(const LayerTextStyle &style, QSizeF container)
|
||||
: m_lineHeight(style.lineHeight()), m_width(container.width()), m_laidEnd(int(style.content.size()))
|
||||
{
|
||||
const QFont font = TextLayout::font(style);
|
||||
QTextOption option(style.alignment == TextAlignment::left ? Qt::AlignLeft : style.alignment == TextAlignment::center ? Qt::AlignHCenter : Qt::AlignRight);
|
||||
option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
|
||||
// NSParagraphStyle's twelve stops, 28 points apart, and on.
|
||||
option.setTabStopDistance(28);
|
||||
// Cocoa's paragraph separators: LF, CR, CRLF and U+2029.
|
||||
static const QRegularExpression separator(QStringLiteral("\\r\\n|[\\r\\n\\x{2029}]"));
|
||||
std::vector<TextRange> paragraphs;
|
||||
int from = 0;
|
||||
for (QRegularExpressionMatchIterator match = separator.globalMatch(style.content); match.hasNext();) {
|
||||
const QRegularExpressionMatch next = match.next();
|
||||
paragraphs.push_back({from, int(next.capturedStart())});
|
||||
from = int(next.capturedEnd());
|
||||
}
|
||||
paragraphs.push_back({from, int(style.content.size())});
|
||||
// TextKit's extra line after a final break holds the caret.
|
||||
const QChar last = style.content.isEmpty() ? QChar() : style.content.back();
|
||||
const bool caretLine = last == u'\n' || last == u'\r' || last == QChar::LineSeparator || last == QChar::ParagraphSeparator;
|
||||
for (const TextRange &range : paragraphs) {
|
||||
const QString paragraph = style.content.mid(range.start, range.end - range.start);
|
||||
auto layout = std::make_unique<QTextLayout>(paragraph, font);
|
||||
layout->setTextOption(option);
|
||||
layout->beginLayout();
|
||||
const auto laid = [&] {
|
||||
const int count = layout->lineCount();
|
||||
return count == 0 ? 0 : layout->lineAt(count - 1).textStart() + layout->lineAt(count - 1).textLength();
|
||||
};
|
||||
// Empty paragraphs take a line, as do final U+2028s.
|
||||
const auto pending = [&] {
|
||||
return layout->lineCount() == 0 || laid() < paragraph.length()
|
||||
|| (layout->lineAt(layout->lineCount() - 1).textLength() > 0 && paragraph.endsWith(QChar::LineSeparator));
|
||||
};
|
||||
while (pending()) {
|
||||
// Past the bottom no line is laid, but the caret's.
|
||||
const bool caret = caretLine && &range == ¶graphs.back() && laid() == paragraph.length();
|
||||
if ((lineCount() + 1) * m_lineHeight > container.height() && !caret) {
|
||||
// TextKit's overflow: some character left unlaid.
|
||||
m_laidEnd = range.start + laid();
|
||||
m_overflows = m_laidEnd < style.content.size();
|
||||
break;
|
||||
}
|
||||
QTextLine line = layout->createLine();
|
||||
if (!line.isValid())
|
||||
throw std::logic_error("Qt laid out no line for pending text");
|
||||
line.setLineWidth(container.width());
|
||||
// The fixed height's extra space sits above the text.
|
||||
line.setPosition(QPointF(0, (lineCount() + 1) * m_lineHeight - line.descent() - line.ascent()));
|
||||
m_lineList.push_back({m_paragraphs.size(), line.lineNumber()});
|
||||
}
|
||||
layout->endLayout();
|
||||
m_paragraphs.push_back(std::move(layout));
|
||||
m_starts.push_back(range.start);
|
||||
if (m_overflows)
|
||||
break;
|
||||
}
|
||||
m_caretLine = caretLine && !m_overflows;
|
||||
}
|
||||
|
||||
QSizeF TextLines::usedSize() const
|
||||
{
|
||||
double width = 0;
|
||||
for (const std::unique_ptr<QTextLayout> ¶graph : m_paragraphs) {
|
||||
for (int index = 0; index < paragraph->lineCount(); ++index)
|
||||
width = std::max(width, paragraph->lineAt(index).naturalTextWidth());
|
||||
}
|
||||
// Measures leave the caret's line out, as TextKit's do.
|
||||
return QSizeF(width, (lineCount() - (m_caretLine ? 1 : 0)) * m_lineHeight);
|
||||
}
|
||||
|
||||
void TextLines::draw(QPainter &painter, QPointF origin, TextRange selection, const QList<QTextLayout::FormatRange> &formats, const QColor &highlight) const
|
||||
{
|
||||
for (int line = 0; line < lineCount() && !selection.isEmpty(); ++line)
|
||||
drawSelection(painter, origin, line, selection, highlight);
|
||||
for (size_t index = 0; index < m_paragraphs.size(); ++index) {
|
||||
const int offset = m_starts[index], length = int(m_paragraphs[index]->text().size());
|
||||
QList<QTextLayout::FormatRange> local;
|
||||
for (const QTextLayout::FormatRange &format : formats) {
|
||||
const int start = std::max(format.start - offset, 0), end = std::min(format.start + format.length - offset, length);
|
||||
if (start < end)
|
||||
local << QTextLayout::FormatRange{start, end - start, format.format};
|
||||
}
|
||||
m_paragraphs[index]->draw(&painter, origin, local);
|
||||
}
|
||||
}
|
||||
|
||||
// TextKit's highlight: visual runs, the whole line, to its edge.
|
||||
void TextLines::drawSelection(QPainter &painter, QPointF origin, int line, TextRange selection, const QColor &highlight) const
|
||||
{
|
||||
const Line &laid = m_lineList[size_t(line)];
|
||||
const QTextLayout ¶graph = *m_paragraphs[laid.paragraph];
|
||||
const QTextLine text = paragraph.lineAt(laid.index);
|
||||
const int offset = m_starts[laid.paragraph], first = offset + text.textStart(), last = first + text.textLength();
|
||||
// The paragraph's separator ends its last line.
|
||||
const bool separated = laid.index == paragraph.lineCount() - 1;
|
||||
const bool before = selection.start < first && selection.end > first;
|
||||
const bool after = selection.end > last && (separated ? selection.start <= last : selection.start < last);
|
||||
const int start = std::max(selection.start, first), end = std::min(selection.end, last);
|
||||
const QRectF band(origin.x(), origin.y() + line * m_lineHeight, m_width, m_lineHeight);
|
||||
painter.save();
|
||||
painter.setClipRect(band, Qt::IntersectClip);
|
||||
if (start < end) {
|
||||
QTextCharFormat format;
|
||||
format.setBackground(highlight);
|
||||
painter.save();
|
||||
painter.setPen(Qt::NoPen);
|
||||
painter.translate(0, band.top());
|
||||
painter.scale(1, m_lineHeight / text.height());
|
||||
painter.translate(0, -(origin.y() + text.y()));
|
||||
const QRectF own(origin.x(), origin.y() + text.y(), m_width, text.height());
|
||||
paragraph.draw(&painter, origin, {QTextLayout::FormatRange{start - offset, end - start, format}}, own);
|
||||
painter.restore();
|
||||
}
|
||||
const bool rtl = paragraph.text().isRightToLeft();
|
||||
const double head = origin.x() + text.cursorToX(first - offset), tail = origin.x() + text.cursorToX(last - offset);
|
||||
if (before)
|
||||
painter.fillRect(rtl ? QRectF(QPointF(head, band.top()), band.bottomRight()) : QRectF(band.topLeft(), QPointF(head, band.bottom())), highlight);
|
||||
if (after)
|
||||
painter.fillRect(rtl ? QRectF(band.topLeft(), QPointF(tail, band.bottom())) : QRectF(QPointF(tail, band.top()), band.bottomRight()), highlight);
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
std::optional<int> TextLines::lineOf(int position) const
|
||||
{
|
||||
if (position > m_laidEnd)
|
||||
return std::nullopt;
|
||||
// The last laid paragraph starting at or before the position.
|
||||
const size_t paragraph = size_t(std::upper_bound(m_starts.begin(), m_starts.end(), position) - m_starts.begin() - 1);
|
||||
const int local = std::min(position - m_starts[paragraph], int(m_paragraphs[paragraph]->text().size()));
|
||||
const QTextLine line = m_paragraphs[paragraph]->lineForTextPosition(local);
|
||||
if (!line.isValid())
|
||||
return std::nullopt;
|
||||
for (size_t index = 0; index < m_lineList.size(); ++index) {
|
||||
if (m_lineList[index].paragraph == paragraph && m_lineList[index].index == line.lineNumber())
|
||||
return int(index);
|
||||
}
|
||||
throw std::logic_error("a laid line is missing from the list");
|
||||
}
|
||||
|
||||
std::optional<QRectF> TextLines::caret(int position) const
|
||||
{
|
||||
const std::optional<int> line = lineOf(position);
|
||||
if (!line)
|
||||
return std::nullopt;
|
||||
const Line &laid = m_lineList[size_t(*line)];
|
||||
const int local = std::min(position - m_starts[laid.paragraph], int(m_paragraphs[laid.paragraph]->text().size()));
|
||||
const double x = m_paragraphs[laid.paragraph]->lineAt(laid.index).cursorToX(local);
|
||||
return QRectF(x, *line * m_lineHeight, 1, m_lineHeight);
|
||||
}
|
||||
|
||||
int TextLines::lineStart(int line) const
|
||||
{
|
||||
const Line &laid = m_lineList[size_t(line)];
|
||||
return m_starts[laid.paragraph] + m_paragraphs[laid.paragraph]->lineAt(laid.index).textStart();
|
||||
}
|
||||
|
||||
int TextLines::lineEnd(int line) const
|
||||
{
|
||||
const Line &laid = m_lineList[size_t(line)];
|
||||
const QTextLayout ¶graph = *m_paragraphs[laid.paragraph];
|
||||
const QTextLine text = paragraph.lineAt(laid.index);
|
||||
const int end = text.textStart() + text.textLength();
|
||||
// A line ends before the space or separator breaking it.
|
||||
const bool wraps = (end < paragraph.text().size() || laid.index < paragraph.lineCount() - 1) && paragraph.text().at(end - 1).isSpace();
|
||||
return m_starts[laid.paragraph] + end - (wraps ? 1 : 0);
|
||||
}
|
||||
|
||||
int TextLines::position(int line, double x) const
|
||||
{
|
||||
const Line &laid = m_lineList[size_t(line)];
|
||||
return m_starts[laid.paragraph] + m_paragraphs[laid.paragraph]->lineAt(laid.index).xToCursor(x);
|
||||
}
|
||||
|
||||
int TextLines::character(int line, double x) const
|
||||
{
|
||||
const Line &laid = m_lineList[size_t(line)];
|
||||
return m_starts[laid.paragraph] + m_paragraphs[laid.paragraph]->lineAt(laid.index).xToCursor(x, QTextLine::CursorOnCharacter);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
#include "Document/TypeTool.h"
|
||||
#include <QFont>
|
||||
#include <QStringList>
|
||||
#include <QTextLayout>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
class QPainter;
|
||||
|
||||
// Where Swift has TextKit: a style's font and lines.
|
||||
namespace TextLayout {
|
||||
// The face a PostScript name names, or Qt's match.
|
||||
QFont font(const LayerTextStyle &style);
|
||||
// Every installed face's PostScript name, sorted.
|
||||
QStringList availableFonts();
|
||||
}
|
||||
|
||||
// Content positions from `start` up to `end`, as NSRange.
|
||||
struct TextRange {
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
bool isEmpty() const { return start == end; }
|
||||
friend bool operator==(const TextRange &, const TextRange &) = default;
|
||||
};
|
||||
|
||||
// A style's paragraphs in a container, as TextKit lays them.
|
||||
class TextLines {
|
||||
public:
|
||||
TextLines(const LayerTextStyle &style, QSizeF container);
|
||||
TextLines(const TextLines &) = delete;
|
||||
TextLines &operator=(const TextLines &) = delete;
|
||||
// The lines' widest width and their heights together.
|
||||
QSizeF usedSize() const;
|
||||
// Whether text fell past the container's bottom.
|
||||
bool overflows() const { return m_overflows; }
|
||||
// A selection shows behind the text; formats in content positions.
|
||||
void draw(QPainter &painter, QPointF origin, TextRange selection = {}, const QList<QTextLayout::FormatRange> &formats = {},
|
||||
const QColor &highlight = QColor()) const;
|
||||
int lineCount() const { return int(m_lineList.size()); }
|
||||
// The laid line holding a content position, if any.
|
||||
std::optional<int> lineOf(int position) const;
|
||||
// The caret before a position: a unit wide.
|
||||
std::optional<QRectF> caret(int position) const;
|
||||
// A line's first position; its last before any wrap.
|
||||
int lineStart(int line) const;
|
||||
int lineEnd(int line) const;
|
||||
// The position nearest `x` on a laid line.
|
||||
int position(int line, double x) const;
|
||||
// The character under `x` on a laid line.
|
||||
int character(int line, double x) const;
|
||||
|
||||
private:
|
||||
struct Line {
|
||||
size_t paragraph;
|
||||
int index;
|
||||
};
|
||||
std::vector<std::unique_ptr<QTextLayout>> m_paragraphs;
|
||||
// Each laid paragraph's first content position.
|
||||
std::vector<int> m_starts;
|
||||
void drawSelection(QPainter &painter, QPointF origin, int line, TextRange selection, const QColor &highlight) const;
|
||||
std::vector<Line> m_lineList;
|
||||
double m_lineHeight;
|
||||
double m_width;
|
||||
// Where the laid text ends: past it, no line.
|
||||
int m_laidEnd;
|
||||
bool m_overflows = false;
|
||||
// TextKit's line after a final newline, the caret's alone.
|
||||
bool m_caretLine = false;
|
||||
};
|
||||
@@ -0,0 +1,428 @@
|
||||
#include "Rendering/TiledLayerRenderer.h"
|
||||
#include "Rendering/PoolMap.h"
|
||||
#include "Logging.h"
|
||||
#include "Rendering/DownsampleCache.h"
|
||||
#include <QRegion>
|
||||
#include <QtConcurrent>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <numeric>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
// Pieces compose and halve side by side, kept in order.
|
||||
std::vector<TiledLayerRenderer::Piece> sideBySide(const std::vector<QRectF> &squares,
|
||||
const std::function<std::optional<TiledLayerRenderer::Piece>(const QRectF &)> &build)
|
||||
{
|
||||
std::vector<std::optional<TiledLayerRenderer::Piece>> built(squares.size());
|
||||
std::vector<size_t> order(squares.size());
|
||||
std::iota(order.begin(), order.end(), size_t(0));
|
||||
PoolMap::blocking(order, [&](size_t index) { built[index] = build(squares[index]); });
|
||||
std::vector<TiledLayerRenderer::Piece> pieces;
|
||||
for (std::optional<TiledLayerRenderer::Piece> &one : built) {
|
||||
if (one)
|
||||
pieces.push_back(std::move(*one));
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
|
||||
using TiledLayerRenderer::Frame;
|
||||
using TiledLayerRenderer::Piece;
|
||||
|
||||
// Columns whose centres satisfy low <= a*x+b < high.
|
||||
std::pair<int, int> columns(double a, double b, double low, double high, int first, int last)
|
||||
{
|
||||
if (a == 0)
|
||||
return low <= b && b < high ? std::pair(first, last) : std::pair(first, first);
|
||||
const double from = (low - b) / a, to = (high - b) / a;
|
||||
// A negative slope turns the half-open interval around.
|
||||
const double begin = a > 0 ? std::ceil(from - 0.5) : std::floor(to - 0.5) + 1;
|
||||
const double end = a > 0 ? std::ceil(to - 0.5) : std::floor(from - 0.5) + 1;
|
||||
// Near a right angle the slope is tiny: clamp first.
|
||||
return {int(std::clamp(begin, double(first), double(last))), int(std::clamp(end, double(first), double(last)))};
|
||||
}
|
||||
|
||||
// Device pixels to grid pixels.
|
||||
QTransform toGrid(const Frame &frame, const QPainter &context)
|
||||
{
|
||||
return context.deviceTransform().inverted()
|
||||
* QTransform::fromTranslate(-frame.bounds.left(), -frame.bounds.top())
|
||||
* QTransform::fromScale(frame.pixelWidth / frame.bounds.width(), frame.pixelHeight / frame.bounds.height());
|
||||
}
|
||||
|
||||
// Device pixels whose centres lie inside `area`, half-open.
|
||||
QRegion pixelsInside(const QRectF &area, const Frame &frame, const QPainter &context)
|
||||
{
|
||||
const QTransform grid = toGrid(frame, context);
|
||||
const QRect device(0, 0, context.device()->width(), context.device()->height());
|
||||
const QRect rows = context.deviceTransform().mapRect(frame.mapped(area)).toAlignedRect().intersected(device);
|
||||
QRegion region;
|
||||
for (int y = rows.top(); y <= rows.bottom(); ++y) {
|
||||
const double row = y + 0.5;
|
||||
const auto [left, right] = columns(grid.m11(), grid.m21() * row + grid.dx(), area.left(), area.right(),
|
||||
device.left(), device.right() + 1);
|
||||
const auto [begin, end] = columns(grid.m12(), grid.m22() * row + grid.dy(), area.top(), area.bottom(), left, right);
|
||||
if (end > begin)
|
||||
region += QRect(begin, y, end - begin, 1);
|
||||
}
|
||||
return region;
|
||||
}
|
||||
|
||||
// The unchanged image, reduced by the frame's halvings.
|
||||
void drawBase(const QImage &image, const QRectF &rect, const Frame &frame, QPainter &context)
|
||||
{
|
||||
const DownsampleCache::Reduced reduced = DownsampleCache::shared().imageAtLevel(image, frame.level);
|
||||
const double step = 1 << reduced.level;
|
||||
const QRectF covered(rect.left(), rect.top(), reduced.image.width() * step * rect.width() / std::max(1, image.width()),
|
||||
reduced.image.height() * step * rect.height() / std::max(1, image.height()));
|
||||
context.drawImage(frame.mapped(covered), reduced.image);
|
||||
}
|
||||
|
||||
// An interior ending with its image opens one device pixel.
|
||||
QRectF opened(const Piece &piece, const Frame &frame, const QPainter &context)
|
||||
{
|
||||
// How far one device pixel reaches across each grid axis.
|
||||
const QTransform grid = toGrid(frame, context);
|
||||
const double dx = std::hypot(grid.m11(), grid.m21()), dy = std::hypot(grid.m12(), grid.m22());
|
||||
const QRectF &inside = piece.interior, &image = piece.region;
|
||||
return inside.adjusted(inside.left() <= image.left() ? -dx : 0, inside.top() <= image.top() ? -dy : 0,
|
||||
inside.right() >= image.right() ? dx : 0, inside.bottom() >= image.bottom() ? dy : 0);
|
||||
}
|
||||
|
||||
// A piece replaces its interior: cleared, then drawn.
|
||||
void draw(const Piece &piece, const Frame &frame, QPainter &context)
|
||||
{
|
||||
const QRegion pixels = pixelsInside(opened(piece, frame, context), frame, context);
|
||||
if (pixels.isEmpty())
|
||||
return;
|
||||
context.save();
|
||||
// A region in device pixels stays hard under antialiasing.
|
||||
context.setWorldMatrixEnabled(false);
|
||||
context.setClipRegion(pixels, Qt::IntersectClip);
|
||||
context.setCompositionMode(QPainter::CompositionMode_Clear);
|
||||
context.fillRect(pixels.boundingRect(), Qt::transparent);
|
||||
context.setCompositionMode(QPainter::CompositionMode_SourceOver);
|
||||
context.setWorldMatrixEnabled(true);
|
||||
context.drawImage(frame.mapped(piece.region), piece.image);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// A committed raster placed at `offset` in the frame's grid.
|
||||
void drawCommitted(const std::shared_ptr<const RasterSnapshot> &raster, QPointF offset, const Frame &frame, QPainter &context)
|
||||
{
|
||||
if (!raster->base.isNull())
|
||||
drawBase(raster->base, raster->baseRect.translated(offset), frame, context);
|
||||
for (const Piece &cached : TiledPieceCache::shared().pieces(raster, frame.level)) {
|
||||
const Piece piece = cached.offsetBy(offset);
|
||||
if (opened(piece, frame, context).intersects(frame.visible))
|
||||
draw(piece, frame, context);
|
||||
}
|
||||
}
|
||||
|
||||
// A mask piece replaces its interior of the mask coverage.
|
||||
void drawCoverage(const Piece &piece, const Frame &frame, QPainter &veil)
|
||||
{
|
||||
draw(Piece{piece.interior, piece.region, BrushRaster::alphaView(piece.image)}, frame, veil);
|
||||
}
|
||||
|
||||
// The part of `image`, placed at `rect`, inside `region`.
|
||||
void drawCropped(const QImage &image, const QRectF &rect, const QRectF ®ion, QPainter &context)
|
||||
{
|
||||
if (image.width() != rect.width() || image.height() != rect.height()) {
|
||||
// A solid 1 x 1 mask, say, stretches over `rect`.
|
||||
BrushRaster::draw(image, rect, context);
|
||||
return;
|
||||
}
|
||||
const QRectF local = QRectF(region.translated(-rect.topLeft()).intersected(QRectF(image.rect())).toAlignedRect());
|
||||
if (!local.isEmpty())
|
||||
BrushRaster::draw(image, local.translated(rect.topLeft()), context, local);
|
||||
}
|
||||
|
||||
using Body = std::function<void(const Frame &, QPainter &)>;
|
||||
|
||||
// Composes a grid holding `painted` aside; `maskRect` places the mask.
|
||||
void withFrame(int pixelWidth, int pixelHeight, const QRectF &painted, const QRectF &maskRect, const LayerTransform &transform,
|
||||
QPointF center, QPainter &context, const LayerRenderer::Options &options, const Body &body, const Body &veil)
|
||||
{
|
||||
const double width = transform.size.width() * options.scale, height = transform.size.height() * options.scale;
|
||||
if (width <= 0 || height <= 0 || pixelWidth <= 0 || pixelHeight <= 0)
|
||||
return;
|
||||
const double device = LayerRenderer::deviceScale(context);
|
||||
const int level = transform.sampling == LayerSampling::nearest ? 0 : DownsampleCache::level(width * device / pixelWidth);
|
||||
const InterpolationQuality quality = LayerRenderer::interpolation(transform.sampling, width * device / pixelWidth * (1 << level));
|
||||
QTransform placement;
|
||||
placement.translate(center.x(), center.y());
|
||||
placement.rotateRadians(transform.radians());
|
||||
placement.scale(transform.flipX ? -1 : 1, transform.flipY ? -1 : 1);
|
||||
const QRectF bounds(-width / 2, -height / 2, width, height);
|
||||
const QRectF shown = placement.inverted().mapRect(BrushRaster::visibleRect(context));
|
||||
const double sx = pixelWidth / width, sy = pixelHeight / height;
|
||||
const Frame frame{bounds, double(pixelWidth), double(pixelHeight), level, device, transform.sampling,
|
||||
QRectF((shown.left() - bounds.left()) * sx, (shown.top() - bounds.top()) * sy, shown.width() * sx, shown.height() * sy)};
|
||||
// Halvings and aligned pieces overhang by less than a step.
|
||||
const double step = 1 << level;
|
||||
const QRectF extent = frame.mapped(painted.adjusted(-step, -step, step, step));
|
||||
const auto framed = [&](const Body &paint) {
|
||||
return paint ? std::function<void(QPainter &)>([&, paint](QPainter &aside) { paint(frame, aside); }) : std::function<void(QPainter &)>();
|
||||
};
|
||||
LayerRenderer::composite(context, placement, extent, transform.sampling, quality, options, frame.mapped(maskRect), framed(body), framed(veil));
|
||||
}
|
||||
}
|
||||
|
||||
TiledLayerRenderer::Piece TiledLayerRenderer::Piece::offsetBy(QPointF offset) const
|
||||
{
|
||||
return {interior.translated(offset), region.translated(offset), image};
|
||||
}
|
||||
|
||||
QRectF TiledLayerRenderer::Frame::mapped(const QRectF &rect) const
|
||||
{
|
||||
return {bounds.left() + rect.left() / pixelWidth * bounds.width(), bounds.top() + rect.top() / pixelHeight * bounds.height(),
|
||||
rect.width() / pixelWidth * bounds.width(), rect.height() / pixelHeight * bounds.height()};
|
||||
}
|
||||
|
||||
double TiledLayerRenderer::support(int level)
|
||||
{
|
||||
return level == 0 ? 8 : 16 << level;
|
||||
}
|
||||
|
||||
void TiledLayerRenderer::drawRaster(const std::shared_ptr<const RasterSnapshot> &raster, const LayerTransform &transform,
|
||||
QPointF center, QPainter &context, const LayerRenderer::Options &options)
|
||||
{
|
||||
const QRectF full(0, 0, raster->width, raster->height);
|
||||
withFrame(raster->width, raster->height, full, full, transform, center, context, options,
|
||||
[&](const Frame &frame, QPainter &aside) { drawCommitted(raster, QPointF(0, 0), frame, aside); }, {});
|
||||
}
|
||||
|
||||
void TiledLayerRenderer::drawStroke(int width, int height, const QRectF &sourceRect, const std::vector<BrushPatch> &patches,
|
||||
const QImage &image, const std::shared_ptr<const RasterSnapshot> &raster,
|
||||
const LayerTransform &transform, QPointF center, QPainter &context,
|
||||
const LayerRenderer::Options &options)
|
||||
{
|
||||
QRectF painted(0, 0, width, height);
|
||||
std::vector<QRectF> changed;
|
||||
for (const BrushPatch &patch : patches) {
|
||||
painted = painted.united(patch.rect);
|
||||
changed.push_back(patch.rect);
|
||||
}
|
||||
std::vector<Piece> pieces;
|
||||
const QPointF origin = sourceRect.topLeft() + (raster ? raster->alignment : QPointF(0, 0));
|
||||
const Body body = [&](const Frame &frame, QPainter &aside) {
|
||||
const std::vector<QRectF> squares = interiors(changed, support(frame.level), strokeCell, 1 << frame.level, origin, frame.visible);
|
||||
const std::vector<Piece> built = sideBySide(squares, [&](const QRectF &square) {
|
||||
return piece(square, frame.level, origin, painted, false, [&](QPainter &painter, const QRectF ®ion) {
|
||||
if (raster)
|
||||
raster->draw(QRectF(sourceRect.topLeft(), QSizeF(raster->width, raster->height)), painter);
|
||||
else if (!image.isNull())
|
||||
drawCropped(image, sourceRect, region, painter);
|
||||
for (const BrushPatch &patch : patches) {
|
||||
if (patch.rect.intersects(region))
|
||||
BrushRaster::draw(patch.image, patch.rect, painter);
|
||||
}
|
||||
});
|
||||
});
|
||||
pieces.insert(pieces.end(), built.begin(), built.end());
|
||||
if (raster)
|
||||
drawCommitted(raster, sourceRect.topLeft(), frame, aside);
|
||||
else if (!image.isNull())
|
||||
drawBase(image, sourceRect, frame, aside);
|
||||
for (const Piece &piece : pieces)
|
||||
draw(piece, frame, aside);
|
||||
};
|
||||
const Body veil = [&](const Frame &frame, QPainter &masking) {
|
||||
// Paint past the old bounds is revealed, not masked.
|
||||
std::vector<QRectF> past;
|
||||
for (const Piece &built : pieces) {
|
||||
if (!sourceRect.contains(built.interior))
|
||||
past.push_back(built.interior);
|
||||
}
|
||||
const std::vector<Piece> shown = sideBySide(past, [&](const QRectF &interior) {
|
||||
return piece(interior, frame.level, origin, painted, true, [&](QPainter &painter, const QRectF ®ion) {
|
||||
painter.fillRect(region, Qt::white);
|
||||
drawCropped(options.mask, sourceRect, region, painter);
|
||||
});
|
||||
});
|
||||
for (const Piece &one : shown)
|
||||
drawCoverage(one, frame, masking);
|
||||
};
|
||||
withFrame(width, height, painted, sourceRect, transform, center, context, options, body, options.mask.isNull() ? Body() : veil);
|
||||
}
|
||||
|
||||
void TiledLayerRenderer::drawMaskStroke(int width, int height, const QRectF &sourceRect, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<ImportedImage> &oldMask, const QImage &image,
|
||||
const std::shared_ptr<const RasterSnapshot> &raster, const LayerTransform &transform,
|
||||
QPointF center, QPainter &context, const LayerRenderer::Options &options)
|
||||
{
|
||||
if (!options.mask.isNull())
|
||||
throw std::logic_error("a mask stroke draws through the mask it paints");
|
||||
LayerRenderer::Options masked = options;
|
||||
if (oldMask)
|
||||
masked.mask = oldMask->image();
|
||||
std::vector<QRectF> changed;
|
||||
for (const BrushPatch &patch : patches)
|
||||
changed.push_back(patch.rect);
|
||||
const Body body = [&](const Frame &frame, QPainter &aside) {
|
||||
if (raster)
|
||||
drawCommitted(raster, sourceRect.topLeft(), frame, aside);
|
||||
else if (!image.isNull())
|
||||
drawBase(image, sourceRect, frame, aside);
|
||||
};
|
||||
const Body veil = [&](const Frame &frame, QPainter &masking) {
|
||||
// Pieces halve on the mask's own grid and levels.
|
||||
const int level = frame.sampling == LayerSampling::nearest
|
||||
? 0 : DownsampleCache::level(frame.mapped(sourceRect).width() * frame.device / std::max(1.0, sourceRect.width()));
|
||||
const QPointF origin = sourceRect.topLeft();
|
||||
const std::vector<Piece> built = sideBySide(interiors(changed, support(level), strokeCell, 1 << level, origin, frame.visible), [&](const QRectF &interior) {
|
||||
return piece(interior, level, origin, sourceRect, true, [&](QPainter &painter, const QRectF ®ion) {
|
||||
// Beyond the old mask an edit reveals.
|
||||
painter.fillRect(region, Qt::white);
|
||||
if (oldMask)
|
||||
drawCropped(masked.mask, sourceRect, region, painter);
|
||||
for (const BrushPatch &patch : patches) {
|
||||
if (patch.rect.intersects(region))
|
||||
BrushRaster::draw(patch.image, patch.rect, painter);
|
||||
}
|
||||
});
|
||||
});
|
||||
for (const Piece &one : built)
|
||||
drawCoverage(one, frame, masking);
|
||||
};
|
||||
withFrame(width, height, QRectF(0, 0, width, height), sourceRect, transform, center, context, masked, body, veil);
|
||||
}
|
||||
|
||||
std::optional<TiledLayerRenderer::Piece> TiledLayerRenderer::piece(const QRectF &interior, int level, QPointF origin, const std::optional<QRectF> &bounds,
|
||||
bool mask, const std::function<void(QPainter &, const QRectF &)> &compose)
|
||||
{
|
||||
const double margin = support(level), step = 1 << level;
|
||||
QRectF region = aligned(interior.adjusted(-margin, -margin, margin, margin), step, origin);
|
||||
if (bounds) {
|
||||
// Past the pixels' edge there is nothing to compose.
|
||||
region = region.intersected(aligned(*bounds, step, origin));
|
||||
if (region.isEmpty())
|
||||
return std::nullopt;
|
||||
}
|
||||
const int width = int(region.width()), height = int(region.height());
|
||||
if (width <= 0 || height <= 0 || qint64(width) * height > 64'000'000)
|
||||
return std::nullopt;
|
||||
QImage image(width, height, mask ? QImage::Format_Grayscale8 : QImage::Format_RGBA8888_Premultiplied);
|
||||
if (image.isNull()) {
|
||||
qCWarning(lcRendering) << "a tile piece could not be allocated:" << width << "x" << height;
|
||||
return std::nullopt;
|
||||
}
|
||||
image.fill(0);
|
||||
{
|
||||
QPainter painter(&image);
|
||||
painter.translate(-region.topLeft());
|
||||
compose(painter, region);
|
||||
}
|
||||
for (int halving = 0; halving < level; ++halving) {
|
||||
const std::optional<QImage> half = DownsampleCache::halve(image, false);
|
||||
if (!half) {
|
||||
qCWarning(lcRendering) << "a tile piece could not be halved";
|
||||
return std::nullopt;
|
||||
}
|
||||
image = *half;
|
||||
}
|
||||
const QRectF kept = bounds ? interior.intersected(region) : interior;
|
||||
if (kept.isEmpty())
|
||||
return std::nullopt;
|
||||
return Piece{kept, region, image};
|
||||
}
|
||||
|
||||
std::vector<QRectF> TiledLayerRenderer::interiors(const std::vector<QRectF> &rects, double margin, double size, double step,
|
||||
QPointF origin, const std::optional<QRectF> &visible)
|
||||
{
|
||||
std::map<std::pair<int, int>, QRectF> parts;
|
||||
for (const QRectF &rect : rects) {
|
||||
const QRectF grown = rect.adjusted(-margin, -margin, margin, margin);
|
||||
if (visible && !grown.intersects(*visible))
|
||||
continue;
|
||||
const int x0 = int(std::floor((grown.left() - origin.x()) / size)), x1 = int(std::ceil((grown.right() - origin.x()) / size));
|
||||
const int y0 = int(std::floor((grown.top() - origin.y()) / size)), y1 = int(std::ceil((grown.bottom() - origin.y()) / size));
|
||||
for (int y = y0; y < y1; ++y) {
|
||||
for (int x = x0; x < x1; ++x) {
|
||||
const QRectF part = grown.intersected(QRectF(origin.x() + x * size, origin.y() + y * size, size, size));
|
||||
if (part.isEmpty())
|
||||
continue;
|
||||
const auto found = parts.find({y, x});
|
||||
if (found == parts.end())
|
||||
parts.insert({{y, x}, part});
|
||||
else
|
||||
found->second = found->second.united(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Squares sit on the step grid: grown parts stay inside.
|
||||
std::vector<QRectF> result;
|
||||
for (const auto &[cell, part] : parts) {
|
||||
const QRectF interior = aligned(part, step, origin);
|
||||
if (!visible || interior.intersects(*visible))
|
||||
result.push_back(interior);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QRectF TiledLayerRenderer::aligned(const QRectF &rect, double step, QPointF origin)
|
||||
{
|
||||
const double left = origin.x() + std::floor((rect.left() - origin.x()) / step) * step;
|
||||
const double top = origin.y() + std::floor((rect.top() - origin.y()) / step) * step;
|
||||
const double right = origin.x() + std::ceil((rect.right() - origin.x()) / step) * step;
|
||||
const double bottom = origin.y() + std::ceil((rect.bottom() - origin.y()) / step) * step;
|
||||
return {left, top, right - left, bottom - top};
|
||||
}
|
||||
|
||||
TiledPieceCache::TiledPieceCache(qint64 pixelBudget) : m_pixelBudget(pixelBudget) {}
|
||||
|
||||
TiledPieceCache &TiledPieceCache::shared()
|
||||
{
|
||||
static TiledPieceCache cache;
|
||||
return cache;
|
||||
}
|
||||
|
||||
std::size_t TiledPieceCache::KeyHash::operator()(const Key &key) const
|
||||
{
|
||||
return std::hash<const RasterSnapshot *>()(key.raster) ^ (std::hash<int>()(key.level) << 1);
|
||||
}
|
||||
|
||||
std::vector<TiledLayerRenderer::Piece> TiledPieceCache::pieces(const std::shared_ptr<const RasterSnapshot> &raster, int level)
|
||||
{
|
||||
const Key key{raster.get(), level};
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
m_clock += 1;
|
||||
if (const auto found = m_entries.find(key); found != m_entries.end()) {
|
||||
found->second.lastUse = m_clock;
|
||||
return found->second.pieces;
|
||||
}
|
||||
}
|
||||
const QPointF origin = raster->alignment;
|
||||
const QRectF full(0, 0, raster->width, raster->height);
|
||||
std::vector<QRectF> changed;
|
||||
for (const BrushPatch &patch : raster->patches)
|
||||
changed.push_back(patch.rect);
|
||||
const std::vector<TiledLayerRenderer::Piece> pieces = sideBySide(
|
||||
TiledLayerRenderer::interiors(changed, TiledLayerRenderer::support(level), TiledLayerRenderer::committedCell, 1 << level, origin, std::nullopt),
|
||||
[&](const QRectF &square) {
|
||||
return TiledLayerRenderer::piece(square, level, origin, full, raster->isMask, [&](QPainter &painter, const QRectF &) { raster->draw(full, painter); });
|
||||
});
|
||||
qint64 pixels = 0;
|
||||
for (const TiledLayerRenderer::Piece &piece : pieces)
|
||||
pixels += qint64(piece.image.width()) * piece.image.height();
|
||||
const std::lock_guard<std::mutex> guard(m_lock);
|
||||
m_entries.insert_or_assign(key, Entry{raster, pieces, m_clock, pixels});
|
||||
qint64 total = 0;
|
||||
for (const auto &[entryKey, entry] : m_entries)
|
||||
total += entry.pixels;
|
||||
while (total > m_pixelBudget) {
|
||||
auto oldest = m_entries.end();
|
||||
for (auto entry = m_entries.begin(); entry != m_entries.end(); ++entry) {
|
||||
if (!(entry->first == key) && (oldest == m_entries.end() || entry->second.lastUse < oldest->second.lastUse))
|
||||
oldest = entry;
|
||||
}
|
||||
if (oldest == m_entries.end())
|
||||
break;
|
||||
total -= oldest->second.pixels;
|
||||
m_entries.erase(oldest);
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#pragma once
|
||||
#include "Rendering/LayerRenderer.h"
|
||||
#include "Rendering/RasterSnapshot.h"
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
// Draws an image plus replacement tiles as one image would.
|
||||
namespace TiledLayerRenderer {
|
||||
struct Piece {
|
||||
// Grid pixels this piece draws.
|
||||
QRectF interior;
|
||||
// Grid pixels its image holds: the interior and a margin.
|
||||
QRectF region;
|
||||
QImage image;
|
||||
Piece offsetBy(QPointF offset) const;
|
||||
};
|
||||
|
||||
// How one layer's grid maps into its local drawing space.
|
||||
struct Frame {
|
||||
QRectF bounds;
|
||||
double pixelWidth;
|
||||
double pixelHeight;
|
||||
int level;
|
||||
double device;
|
||||
LayerSampling sampling;
|
||||
// Grid pixels the painter's clip can show.
|
||||
QRectF visible;
|
||||
QRectF mapped(const QRectF &rect) const;
|
||||
};
|
||||
|
||||
// Piece squares: large for committed snapshots, small for live strokes.
|
||||
inline constexpr double committedCell = 1024;
|
||||
inline constexpr double strokeCell = 256;
|
||||
|
||||
// Grid pixels a change's reduced, resampled pixels can reach.
|
||||
double support(int level);
|
||||
void drawRaster(const std::shared_ptr<const RasterSnapshot> &raster, const LayerTransform &transform, QPointF center,
|
||||
QPainter &context, const LayerRenderer::Options &options = {});
|
||||
// A tiled edit in progress over the pixels at `sourceRect`.
|
||||
void drawStroke(int width, int height, const QRectF &sourceRect, const std::vector<BrushPatch> &patches, const QImage &image,
|
||||
const std::shared_ptr<const RasterSnapshot> &raster, const LayerTransform &transform, QPointF center,
|
||||
QPainter &context, const LayerRenderer::Options &options = {});
|
||||
// The layer through its mask as the stroke leaves it.
|
||||
void drawMaskStroke(int width, int height, const QRectF &sourceRect, const std::vector<BrushPatch> &patches,
|
||||
const std::optional<ImportedImage> &oldMask, const QImage &image,
|
||||
const std::shared_ptr<const RasterSnapshot> &raster, const LayerTransform &transform, QPointF center,
|
||||
QPainter &context, const LayerRenderer::Options &options = {});
|
||||
std::optional<Piece> piece(const QRectF &interior, int level, QPointF origin, const std::optional<QRectF> &bounds, bool mask,
|
||||
const std::function<void(QPainter &, const QRectF ®ion)> &compose);
|
||||
std::vector<QRectF> interiors(const std::vector<QRectF> &rects, double margin, double size, double step, QPointF origin,
|
||||
const std::optional<QRectF> &visible);
|
||||
QRectF aligned(const QRectF &rect, double step, QPointF origin);
|
||||
}
|
||||
|
||||
// Committed rasters' pieces, built once per snapshot and level.
|
||||
class TiledPieceCache {
|
||||
public:
|
||||
static constexpr qint64 pixelBudget = 150'000'000;
|
||||
explicit TiledPieceCache(qint64 pixelBudget = TiledPieceCache::pixelBudget);
|
||||
static TiledPieceCache &shared();
|
||||
std::vector<TiledLayerRenderer::Piece> pieces(const std::shared_ptr<const RasterSnapshot> &raster, int level);
|
||||
|
||||
private:
|
||||
struct Key {
|
||||
const RasterSnapshot *raster;
|
||||
int level;
|
||||
bool operator==(const Key &) const = default;
|
||||
};
|
||||
struct KeyHash {
|
||||
std::size_t operator()(const Key &key) const;
|
||||
};
|
||||
struct Entry {
|
||||
std::shared_ptr<const RasterSnapshot> raster;
|
||||
std::vector<TiledLayerRenderer::Piece> pieces;
|
||||
quint64 lastUse;
|
||||
qint64 pixels;
|
||||
};
|
||||
const qint64 m_pixelBudget;
|
||||
std::unordered_map<Key, Entry, KeyHash> m_entries;
|
||||
quint64 m_clock = 0;
|
||||
std::mutex m_lock;
|
||||
};
|
||||
@@ -0,0 +1,379 @@
|
||||
#include "Rendering/TransformOverlay.h"
|
||||
#include <QPainterPath>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
|
||||
TransformOverlayGeometry::TransformOverlayGeometry(const LayerTransform &transform, const CanvasViewport &viewport, QSizeF documentSize)
|
||||
{
|
||||
for (size_t index = 0; index < handles.size(); ++index)
|
||||
handles[index] = viewport.viewPoint(transform.point(LayerTransform::handles[index]), documentSize);
|
||||
rotationHandle = handles[1] + QPointF(std::sin(transform.radians()) * 28, -std::cos(transform.radians()) * 28);
|
||||
showsRotation = true;
|
||||
}
|
||||
|
||||
TransformOverlayGeometry::TransformOverlayGeometry(const Corners &corners, const CanvasViewport &viewport, QSizeF documentSize)
|
||||
{
|
||||
std::array<QPointF, 4> view;
|
||||
for (size_t index = 0; index < 4; ++index)
|
||||
view[index] = viewport.viewPoint(corners[index], documentSize);
|
||||
const auto middle = [](QPointF a, QPointF b) { return QPointF((a.x() + b.x()) / 2, (a.y() + b.y()) / 2); };
|
||||
handles = {view[0], middle(view[0], view[1]), view[1], middle(view[1], view[2]), view[2], middle(view[2], view[3]), view[3], middle(view[3], view[0])};
|
||||
rotationHandle = handles[1];
|
||||
showsRotation = false;
|
||||
}
|
||||
|
||||
std::optional<TransformDrag::Mode> TransformOverlayGeometry::hit(QPointF point) const
|
||||
{
|
||||
const auto near = [&](QPointF other) { return std::hypot(point.x() - other.x(), point.y() - other.y()) <= 10; };
|
||||
if (showsRotation && near(rotationHandle))
|
||||
return TransformDrag::Mode{TransformDrag::Kind::rotate};
|
||||
for (size_t index = 0; index < handles.size(); ++index) {
|
||||
if (near(handles[index]))
|
||||
return TransformDrag::Mode{TransformDrag::Kind::resize, int(index)};
|
||||
}
|
||||
// Along an edge, its middle handle: the whole edge resizes.
|
||||
for (const auto &[start, end, handle] : {std::tuple(0, 2, 1), std::tuple(2, 4, 3), std::tuple(4, 6, 5), std::tuple(6, 0, 7)}) {
|
||||
const QPointF a = handles[start], b = handles[end];
|
||||
const double dx = b.x() - a.x(), dy = b.y() - a.y();
|
||||
const double lengthSquared = dx * dx + dy * dy;
|
||||
if (lengthSquared <= 0)
|
||||
continue;
|
||||
const double t = ((point.x() - a.x()) * dx + (point.y() - a.y()) * dy) / lengthSquared;
|
||||
if (t >= 0 && t <= 1 && std::hypot(point.x() - a.x() - t * dx, point.y() - a.y() - t * dy) <= 10)
|
||||
return TransformDrag::Mode{TransformDrag::Kind::resize, handle};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Qt::CursorShape TransformOverlayGeometry::resizeCursor(int index) const
|
||||
{
|
||||
constexpr double quarter = std::numbers::pi / 4;
|
||||
const double angle = std::atan2(handles[2].y() - handles[0].y(), handles[2].x() - handles[0].x());
|
||||
const std::array<double, 8> offsets = {quarter, 2 * quarter, 3 * quarter, 0, quarter, 2 * quarter, 3 * quarter, 0};
|
||||
const int direction = (int(std::round((angle + offsets[size_t(index)]) / quarter)) % 4 + 4) % 4;
|
||||
// Swift's frame positions: right, bottom right, bottom, top right.
|
||||
const std::array<Qt::CursorShape, 4> shapes = {Qt::SizeHorCursor, Qt::SizeFDiagCursor, Qt::SizeVerCursor, Qt::SizeBDiagCursor};
|
||||
return shapes[size_t(direction)];
|
||||
}
|
||||
|
||||
std::optional<TransformOverlayGeometry> TransformOverlay::geometry() const
|
||||
{
|
||||
const std::optional<TransformEdit> &edit = m_session.transformEdit();
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (m_session.tool() != NavigationTool::move || !(m_session.showsTransformControls() || (edit && edit->persistent)) || !document)
|
||||
return std::nullopt;
|
||||
// Several layers or a folder: one box around them all.
|
||||
if ((edit && edit->group) || (!edit && m_session.transformsAsGroup())) {
|
||||
if (edit && edit->corners)
|
||||
return TransformOverlayGeometry(*edit->corners, m_session.viewport, document->size());
|
||||
const std::optional<LayerTransform> box = edit ? std::optional(edit->draft) : m_session.groupTransformBox();
|
||||
if (!box)
|
||||
return std::nullopt;
|
||||
return TransformOverlayGeometry(*box, m_session.viewport, document->size());
|
||||
}
|
||||
const std::optional<ImageLayer> layer = m_session.activeLayer();
|
||||
if (!layer || !layer->asset || layer->isGroup || !document->effectiveVisibleIDs().contains(layer->id))
|
||||
return std::nullopt;
|
||||
if (edit && edit->layerID == layer->id && edit->corners)
|
||||
return TransformOverlayGeometry(*edit->corners, m_session.viewport, document->size());
|
||||
return TransformOverlayGeometry(m_session.editedTransform(*layer), m_session.viewport, document->size());
|
||||
}
|
||||
|
||||
QRect TransformOverlay::drawnRect(const QRect &canvas) const
|
||||
{
|
||||
const SnapGuides &guides = m_session.snapGuides;
|
||||
if (!guides.xs.empty() || !guides.ys.empty())
|
||||
return canvas;
|
||||
QRect drawn;
|
||||
if (const std::optional<TransformOverlayGeometry> geometry = this->geometry()) {
|
||||
QPointF low = geometry->rotationHandle, high = low;
|
||||
for (const QPointF handle : geometry->handles) {
|
||||
low = {std::min(low.x(), handle.x()), std::min(low.y(), handle.y())};
|
||||
high = {std::max(high.x(), handle.x()), std::max(high.y(), handle.y())};
|
||||
}
|
||||
// The strokes reach five points past a handle's middle.
|
||||
drawn = QRectF(low, high).adjusted(-5, -5, 5, 5).toAlignedRect();
|
||||
}
|
||||
// Outside both frames the dimming stays: only the frames change.
|
||||
if (const std::optional<QRectF> crop = cropViewRect())
|
||||
drawn |= crop->adjusted(-5, -5, 5, 5).toAlignedRect();
|
||||
drawn |= selectionRect(canvas);
|
||||
if (const std::optional<LassoDraft> &draft = m_session.lassoDraft()) {
|
||||
QPointF low = draft->points.front(), high = low;
|
||||
for (const QPointF point : draft->points) {
|
||||
low = {std::min(low.x(), point.x()), std::min(low.y(), point.y())};
|
||||
high = {std::max(high.x(), point.x()), std::max(high.y(), point.y())};
|
||||
}
|
||||
if (draft->cursor) {
|
||||
low = {std::min(low.x(), draft->cursor->x()), std::min(low.y(), draft->cursor->y())};
|
||||
high = {std::max(high.x(), draft->cursor->x()), std::max(high.y(), draft->cursor->y())};
|
||||
}
|
||||
// The first corner's handle reaches five points out.
|
||||
drawn |= documentToView().mapRect(QRectF(low, high)).adjusted(-5, -5, 5, 5).toAlignedRect();
|
||||
}
|
||||
return drawn.intersected(canvas);
|
||||
}
|
||||
|
||||
QRect TransformOverlay::selectionRect(const QRect &canvas) const
|
||||
{
|
||||
const std::optional<DocumentSelection> selection = m_session.displayedSelection();
|
||||
if (!selection || selection->isEmpty())
|
||||
return QRect();
|
||||
return documentToView().map(selection->path).boundingRect().adjusted(-2, -2, 2, 2).toAlignedRect().intersected(canvas);
|
||||
}
|
||||
|
||||
QTransform TransformOverlay::documentToView() const
|
||||
{
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!document)
|
||||
return QTransform();
|
||||
const QPointF origin = m_session.viewport.documentRect(document->size()).topLeft();
|
||||
const double scale = m_session.viewport.pointsPerPixel();
|
||||
return QTransform::fromTranslate(origin.x(), origin.y()).scale(scale, scale);
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::array<QPointF, 8> cropHandles(const QRectF &rect)
|
||||
{
|
||||
std::array<QPointF, 8> handles;
|
||||
for (size_t index = 0; index < handles.size(); ++index)
|
||||
handles[index] = QPointF(rect.left() + LayerTransform::handles[index].x() * rect.width(), rect.top() + LayerTransform::handles[index].y() * rect.height());
|
||||
return handles;
|
||||
}
|
||||
}
|
||||
|
||||
// Swift's document guard is dead: visibleCropRect reads it.
|
||||
std::optional<QRectF> TransformOverlay::cropViewRect() const
|
||||
{
|
||||
const std::optional<QRectF> rect = m_session.visibleCropRect();
|
||||
if (!rect)
|
||||
return std::nullopt;
|
||||
const double scale = m_session.viewport.pointsPerPixel();
|
||||
return QRectF(m_session.viewport.viewPoint(rect->topLeft(), m_session.document().value().size()), rect->size() * scale);
|
||||
}
|
||||
|
||||
std::vector<TransformOverlay::CropRegion> TransformOverlay::cropResizeRegions() const
|
||||
{
|
||||
const std::optional<QRectF> rect = cropViewRect();
|
||||
if (!rect)
|
||||
return {};
|
||||
const std::array<QPointF, 8> handles = cropHandles(*rect);
|
||||
constexpr double radius = 10;
|
||||
std::vector<CropRegion> regions;
|
||||
for (const size_t index : {0, 2, 4, 6})
|
||||
regions.push_back({int(index), QRectF(handles[index] - QPointF(radius, radius), QSizeF(radius * 2, radius * 2))});
|
||||
// Whole edges resize; Swift's max(0) is dead under the corners.
|
||||
for (const size_t index : {1, 5})
|
||||
regions.push_back({int(index), QRectF(rect->left() + radius, handles[index].y() - radius, rect->width() - radius * 2, radius * 2)});
|
||||
for (const size_t index : {3, 7})
|
||||
regions.push_back({int(index), QRectF(handles[index].x() - radius, rect->top() + radius, radius * 2, rect->height() - radius * 2)});
|
||||
return regions;
|
||||
}
|
||||
|
||||
std::optional<std::pair<QPointF, QPointF>> TransformOverlay::gradientLine() const
|
||||
{
|
||||
const std::optional<GradientEdit> &edit = m_session.gradientEdit();
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if (!edit || !edit->hasLine() || !document)
|
||||
return std::nullopt;
|
||||
return std::pair(m_session.viewport.viewPoint(edit->start, document->size()), m_session.viewport.viewPoint(edit->end, document->size()));
|
||||
}
|
||||
|
||||
void TransformOverlay::draw(QPainter &context, const QPalette &palette) const
|
||||
{
|
||||
if (m_session.tool() == NavigationTool::crop)
|
||||
drawCrop(context);
|
||||
else if (const std::optional<std::pair<QPointF, QPointF>> line = gradientLine())
|
||||
drawGradientLine(context, line->first, line->second);
|
||||
else
|
||||
drawTransformHandles(context, palette);
|
||||
drawSelection(context);
|
||||
drawLassoDraft(context);
|
||||
drawSnapGuides(context, palette);
|
||||
}
|
||||
|
||||
// The line, its ends in their colours, a radial's rim.
|
||||
void TransformOverlay::drawGradientLine(QPainter &context, QPointF start, QPointF end) const
|
||||
{
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.setBrush(Qt::NoBrush);
|
||||
if (m_session.gradientSettings().shape == GradientShape::radial) {
|
||||
// A faint rim where the radial reaches its end colour.
|
||||
const double radius = std::hypot(end.x() - start.x(), end.y() - start.y());
|
||||
const QRectF rim(start.x() - radius, start.y() - radius, radius * 2, radius * 2);
|
||||
for (const auto &[colour, width] : {std::pair(QColor(0, 0, 0, 128), 2.0), std::pair(QColor(255, 255, 255, 204), 1.0)}) {
|
||||
QPen pen(colour, width, Qt::SolidLine, Qt::FlatCap);
|
||||
// Four on, four off, in points: Qt counts widths.
|
||||
pen.setDashPattern({4 / width, 4 / width});
|
||||
context.setPen(pen);
|
||||
context.drawEllipse(rim);
|
||||
}
|
||||
}
|
||||
context.setPen(QPen(QColor(0, 0, 0, 179), 3));
|
||||
context.drawLine(start, end);
|
||||
context.setPen(QPen(Qt::white, 1));
|
||||
context.drawLine(start, end);
|
||||
const std::array<QColor, 2> colors = m_session.gradientColors(false);
|
||||
for (const auto &[point, colour] : {std::pair(start, colors[0]), std::pair(end, colors[1])}) {
|
||||
const QRectF rect(point.x() - 6, point.y() - 6, 12, 12);
|
||||
context.setPen(QPen(Qt::black, 1));
|
||||
context.setBrush(Qt::white);
|
||||
context.drawEllipse(rect);
|
||||
// A gray under the colour shows a clear end.
|
||||
const QRectF inner = rect.adjusted(2.5, 2.5, -2.5, -2.5);
|
||||
context.setPen(Qt::NoPen);
|
||||
context.setBrush(QColor::fromRgbF(0.75, 0.75, 0.75));
|
||||
context.drawEllipse(inner);
|
||||
context.setBrush(colour);
|
||||
context.drawEllipse(inner);
|
||||
}
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// The outside dimmed, the frame, its thirds and its grips.
|
||||
void TransformOverlay::drawCrop(QPainter &context) const
|
||||
{
|
||||
const std::optional<QRectF> rect = cropViewRect();
|
||||
if (!rect)
|
||||
return;
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
// Odd-even, a path's own rule: the frame stays clear.
|
||||
QPainterPath outside;
|
||||
outside.addRect(context.window());
|
||||
outside.addRect(*rect);
|
||||
context.fillPath(outside, QColor::fromRgbF(0, 0, 0, 0.6));
|
||||
context.setBrush(Qt::NoBrush);
|
||||
// CoreGraphics' butt caps and miter joins.
|
||||
context.setPen(QPen(Qt::white, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
|
||||
context.drawRect(*rect);
|
||||
QPainterPath thirds;
|
||||
for (const int index : {1, 2}) {
|
||||
const double fraction = index / 3.0;
|
||||
thirds.moveTo(rect->left() + rect->width() * fraction, rect->top());
|
||||
thirds.lineTo(rect->left() + rect->width() * fraction, rect->bottom());
|
||||
thirds.moveTo(rect->left(), rect->top() + rect->height() * fraction);
|
||||
thirds.lineTo(rect->right(), rect->top() + rect->height() * fraction);
|
||||
}
|
||||
context.setPen(QPen(QColor::fromRgbF(1, 1, 1, 0.4), 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
|
||||
context.drawPath(thirds);
|
||||
context.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
|
||||
context.setBrush(Qt::white);
|
||||
for (const QPointF point : cropHandles(*rect))
|
||||
context.drawRect(QRectF(point.x() - 4, point.y() - 4, 8, 8));
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// Marching ants: a white line under an animated black dash.
|
||||
void TransformOverlay::drawSelection(QPainter &context) const
|
||||
{
|
||||
const std::optional<DocumentSelection> selection = m_session.displayedSelection();
|
||||
if (!selection || selection->isEmpty() || !m_session.document())
|
||||
return;
|
||||
const QPainterPath path = documentToView().map(selection->path);
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.setBrush(Qt::NoBrush);
|
||||
context.setPen(QPen(Qt::white, 1));
|
||||
context.drawPath(path);
|
||||
// Butt caps, as CoreGraphics dashes: four on, four off.
|
||||
QPen ants(Qt::black, 1);
|
||||
ants.setCapStyle(Qt::FlatCap);
|
||||
ants.setDashPattern({4, 4});
|
||||
ants.setDashOffset(antsPhase);
|
||||
context.setPen(ants);
|
||||
context.drawPath(path);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
void TransformOverlay::drawLassoDraft(QPainter &context) const
|
||||
{
|
||||
const std::optional<LassoDraft> &draft = m_session.lassoDraft();
|
||||
if (!draft || !m_session.document())
|
||||
return;
|
||||
const QTransform transform = documentToView();
|
||||
std::vector<QPointF> points;
|
||||
for (const QPointF point : draft->points)
|
||||
points.push_back(transform.map(point));
|
||||
if (draft->kind == LassoKind::polygonal && draft->cursor)
|
||||
points.push_back(transform.map(*draft->cursor));
|
||||
QPainterPath path;
|
||||
if (draft->kind == LassoKind::ellipse && points.size() == 4) {
|
||||
QPointF low = points[0], high = low;
|
||||
for (const QPointF point : points) {
|
||||
low = {std::min(low.x(), point.x()), std::min(low.y(), point.y())};
|
||||
high = {std::max(high.x(), point.x()), std::max(high.y(), point.y())};
|
||||
}
|
||||
path.addEllipse(QRectF(low, high));
|
||||
} else {
|
||||
path.moveTo(points.front());
|
||||
for (std::size_t index = 1; index < points.size(); ++index)
|
||||
path.lineTo(points[index]);
|
||||
if (draft->kind == LassoKind::rectangle)
|
||||
path.closeSubpath();
|
||||
}
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.setBrush(Qt::NoBrush);
|
||||
// Butt caps: an open outline ends at its last point.
|
||||
context.setPen(QPen(QColor(0, 0, 0, 204), 2, Qt::SolidLine, Qt::FlatCap));
|
||||
context.drawPath(path);
|
||||
context.setPen(QPen(Qt::white, 1, Qt::SolidLine, Qt::FlatCap));
|
||||
context.drawPath(path);
|
||||
if (draft->kind == LassoKind::polygonal) {
|
||||
// The first corner: click it to close the outline.
|
||||
const QRectF handle(points.front().x() - 4, points.front().y() - 4, 8, 8);
|
||||
context.fillRect(handle, Qt::white);
|
||||
context.setPen(QPen(Qt::black, 1));
|
||||
context.drawRect(handle);
|
||||
}
|
||||
context.restore();
|
||||
}
|
||||
|
||||
void TransformOverlay::drawTransformHandles(QPainter &context, const QPalette &palette) const
|
||||
{
|
||||
const std::optional<TransformOverlayGeometry> geometry = this->geometry();
|
||||
if (!geometry)
|
||||
return;
|
||||
const QColor accent = palette.color(QPalette::Highlight);
|
||||
QPainterPath path(geometry->handles[0]);
|
||||
for (const int index : {2, 4, 6})
|
||||
path.lineTo(geometry->handles[size_t(index)]);
|
||||
path.closeSubpath();
|
||||
if (geometry->showsRotation) {
|
||||
path.moveTo(geometry->handles[1]);
|
||||
path.lineTo(geometry->rotationHandle);
|
||||
}
|
||||
context.save();
|
||||
context.setRenderHint(QPainter::Antialiasing, true);
|
||||
context.setBrush(Qt::NoBrush);
|
||||
context.setPen(QPen(QColor(0, 0, 0, 179), 3));
|
||||
context.drawPath(path);
|
||||
context.setPen(QPen(accent, 1));
|
||||
context.drawPath(path);
|
||||
context.setBrush(Qt::white);
|
||||
for (const QPointF point : geometry->handles)
|
||||
context.drawRect(QRectF(point.x() - 3.5, point.y() - 3.5, 7, 7));
|
||||
if (geometry->showsRotation)
|
||||
context.drawEllipse(QRectF(geometry->rotationHandle.x() - 4, geometry->rotationHandle.y() - 4, 8, 8));
|
||||
context.restore();
|
||||
}
|
||||
|
||||
// While a move snaps, a line along what it met.
|
||||
void TransformOverlay::drawSnapGuides(QPainter &context, const QPalette &palette) const
|
||||
{
|
||||
const SnapGuides &guides = m_session.snapGuides;
|
||||
const std::optional<CanvasDocument> &document = m_session.document();
|
||||
if ((guides.xs.empty() && guides.ys.empty()) || !document)
|
||||
return;
|
||||
const QSizeF size = document->size();
|
||||
const CanvasViewport &viewport = m_session.viewport;
|
||||
context.save();
|
||||
context.setPen(QPen(palette.color(QPalette::Highlight), 1));
|
||||
for (const double x : guides.xs)
|
||||
context.drawLine(viewport.viewPoint(QPointF(x, 0), size), viewport.viewPoint(QPointF(x, size.height()), size));
|
||||
for (const double y : guides.ys)
|
||||
context.drawLine(viewport.viewPoint(QPointF(0, y), size), viewport.viewPoint(QPointF(size.width(), y), size));
|
||||
context.restore();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
#include "Document/EditorSession.h"
|
||||
#include <QPainter>
|
||||
#include <QPalette>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
// The Move tool's box on screen: handles and a grip.
|
||||
struct TransformOverlayGeometry {
|
||||
std::array<QPointF, 8> handles;
|
||||
QPointF rotationHandle;
|
||||
// A distortion has no single rotation: its grip is hidden.
|
||||
bool showsRotation;
|
||||
|
||||
TransformOverlayGeometry(const LayerTransform &transform, const CanvasViewport &viewport, QSizeF documentSize);
|
||||
// A distortion: its corners and the middles of its edges.
|
||||
TransformOverlayGeometry(const Corners &corners, const CanvasViewport &viewport, QSizeF documentSize);
|
||||
|
||||
// What a press takes hold of, within ten points.
|
||||
std::optional<TransformDrag::Mode> hit(QPointF point) const;
|
||||
// The resize cursor along the handle's edge, turned with it.
|
||||
Qt::CursorShape resizeCursor(int index) const;
|
||||
friend bool operator==(const TransformOverlayGeometry &, const TransformOverlayGeometry &) = default;
|
||||
};
|
||||
|
||||
// Drawn by the canvas over its pixels: Swift's overlay view.
|
||||
class TransformOverlay {
|
||||
public:
|
||||
explicit TransformOverlay(const EditorSession &session) : m_session(session) {}
|
||||
|
||||
// The marching ants' dash offset, stepped by the canvas.
|
||||
double antsPhase = 0;
|
||||
|
||||
std::optional<TransformOverlayGeometry> geometry() const;
|
||||
// Swift's gradientLine: the pending gradient's ends in view points.
|
||||
std::optional<std::pair<QPointF, QPointF>> gradientLine() const;
|
||||
// Where it draws, so the canvas repaints only that.
|
||||
QRect drawnRect(const QRect &canvas) const;
|
||||
// Where the ants draw: a tick repaints that alone.
|
||||
QRect selectionRect(const QRect &canvas) const;
|
||||
// Swift's crop frame in view points; none off the tool.
|
||||
std::optional<QRectF> cropViewRect() const;
|
||||
// A grip and the view points it takes, corners first.
|
||||
struct CropRegion {
|
||||
int index;
|
||||
QRectF rect;
|
||||
};
|
||||
std::vector<CropRegion> cropResizeRegions() const;
|
||||
void draw(QPainter &context, const QPalette &palette) const;
|
||||
|
||||
private:
|
||||
QTransform documentToView() const;
|
||||
void drawTransformHandles(QPainter &context, const QPalette &palette) const;
|
||||
void drawGradientLine(QPainter &context, QPointF start, QPointF end) const;
|
||||
void drawCrop(QPainter &context) const;
|
||||
void drawSelection(QPainter &context) const;
|
||||
void drawLassoDraft(QPainter &context) const;
|
||||
void drawSnapGuides(QPainter &context, const QPalette &palette) const;
|
||||
|
||||
const EditorSession &m_session;
|
||||
};
|
||||
Reference in new issue
Block a user