Merge inbound to mozilla-central. a=merge

This commit is contained in:
Bogdan Tara 2019-03-31 12:00:08 +03:00
Родитель e1236ec692 a00853db4b
Коммит 2738efcf98
1562 изменённых файлов: 223319 добавлений и 219050 удалений

Просмотреть файл

@ -182,9 +182,6 @@ pref("extensions.update.interval", 86400); // Check for updates to Extensions a
pref("extensions.webextensions.themes.icons.buttons", "back,forward,reload,stop,bookmark_star,bookmark_menu,downloads,home,app_menu,cut,copy,paste,new_window,new_private_window,save_page,print,history,full_screen,find,options,addons,developer,synced_tabs,open_file,sidebars,share_page,subscribe,text_encoding,email_link,forget,pocket");
pref("lightweightThemes.update.enabled", true);
pref("lightweightThemes.getMoreURL", "https://addons.mozilla.org/%LOCALE%/firefox/themes");
#if defined(MOZ_WIDEVINE_EME)
pref("browser.eme.ui.enabled", true);
#else
@ -1211,8 +1208,6 @@ pref("services.sync.prefs.sync.extensions.personas.current", true);
pref("services.sync.prefs.sync.extensions.update.enabled", true);
pref("services.sync.prefs.sync.intl.accept_languages", true);
pref("services.sync.prefs.sync.layout.spellcheckDefault", true);
pref("services.sync.prefs.sync.lightweightThemes.selectedThemeID", true);
pref("services.sync.prefs.sync.lightweightThemes.usedThemes", true);
pref("services.sync.prefs.sync.media.autoplay.default", true);
pref("services.sync.prefs.sync.media.eme.enabled", true);
pref("services.sync.prefs.sync.network.cookie.cookieBehavior", true);
@ -1261,14 +1256,6 @@ pref("services.sync.prefs.sync.xpinstall.whitelist.required", true);
// user's tabs and bookmarks. Note this pref is also synced.
pref("services.sync.syncedTabs.showRemoteIcons", true);
// Developer edition preferences
#ifdef MOZ_DEV_EDITION
pref("lightweightThemes.selectedThemeID", "firefox-compact-dark@mozilla.org",
sticky);
#else
pref("lightweightThemes.selectedThemeID", "default-theme@mozilla.org", sticky);
#endif
// Whether the character encoding menu is under the main Firefox button. This
// preference is a string so that localizers can alter it.
pref("browser.menu.showCharacterEncoding", "chrome://browser/locale/browser.properties");

Просмотреть файл

@ -25,11 +25,13 @@ var CompactTheme = {
return this.styleSheet && !this.styleSheet.disabled;
},
isCompactTheme(theme) {
return theme && (theme.id == "firefox-compact-dark@mozilla.org" ||
theme.id == "firefox-compact-light@mozilla.org");
},
get isThemeCurrentlyApplied() {
let theme = LightweightThemeManager.currentThemeWithPersistedData;
return theme && (
theme.id == "firefox-compact-dark@mozilla.org" ||
theme.id == "firefox-compact-light@mozilla.org");
return this.isCompactTheme(LightweightThemeManager.currentThemeWithFallback);
},
init() {
@ -42,10 +44,7 @@ var CompactTheme = {
observe(subject, topic, data) {
if (topic == "lightweight-theme-styling-update") {
let { theme } = JSON.parse(data) || {};
if (theme && (
theme.id == "firefox-compact-light@mozilla.org" ||
theme.id == "firefox-compact-dark@mozilla.org")) {
if (this.isCompactTheme(subject.wrappedJSObject.theme)) {
// We are using the theme ID on this object instead of always referencing
// LightweightThemeManager.currentTheme in case this is a preview
this._toggleStyleSheet(true);

Просмотреть файл

@ -116,12 +116,6 @@ const startupPhases = {
}},
};
if (Services.prefs.getBoolPref("browser.startup.blankWindow") &&
Services.prefs.getCharPref("lightweightThemes.selectedThemeID") ==
"default-theme@mozilla.org") {
startupPhases["before profile selection"].whitelist.components.add("XULStore.js");
}
if (!gBrowser.selectedBrowser.isRemoteBrowser) {
// With e10s disabled, Places and BrowserWindowTracker.jsm (from a
// SessionSaver.jsm timer) intermittently get loaded earlier. Likely

Просмотреть файл

@ -309,6 +309,8 @@ function parseManifest(manifestUri) {
// for any embedded APIs. Returns the passed in URI if the manifest
// is not a webextension manifest, null otherwise.
async function parseJsonManifest(uri) {
uri = Services.io.newURI(convertToCodeURI(uri.spec));
let raw = await fetchFile(uri.spec);
let data;
try {
@ -322,6 +324,12 @@ async function parseJsonManifest(uri) {
return uri;
}
if (data.icons) {
for (let icon of Object.values(data.icons)) {
gReferencesFromCode.set(uri.resolve(icon), null);
}
}
if (data.experiment_apis) {
for (let api of Object.values(data.experiment_apis)) {
if (api.parent && api.parent.script) {

Просмотреть файл

@ -75,8 +75,6 @@ browser.jar:
content/browser/defaultthemes/5.header.png (content/defaultthemes/5.header.png)
content/browser/defaultthemes/5.icon.jpg (content/defaultthemes/5.icon.jpg)
content/browser/defaultthemes/5.preview.jpg (content/defaultthemes/5.preview.jpg)
content/browser/defaultthemes/dark.icon.svg (content/defaultthemes/dark.icon.svg)
content/browser/defaultthemes/light.icon.svg (content/defaultthemes/light.icon.svg)
content/browser/history-swipe-arrow.svg (content/history-swipe-arrow.svg)
* content/browser/pageinfo/pageInfo.xul (content/pageinfo/pageInfo.xul)
content/browser/pageinfo/pageInfo.js (content/pageinfo/pageInfo.js)
@ -128,3 +126,4 @@ browser.jar:
% override chrome://global/locale/appstrings.properties chrome://browser/locale/appstrings.properties
% override chrome://global/locale/netError.dtd chrome://browser/locale/netError.dtd
% override chrome://mozapps/locale/downloads/settingsChange.dtd chrome://browser/locale/downloads/settingsChange.dtd
% override chrome://global/locale/app-extension-fields.properties chrome://browser/locale/app-extension-fields.properties

Просмотреть файл

@ -399,7 +399,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
HybridContentTelemetry: "resource://gre/modules/HybridContentTelemetry.jsm",
Integration: "resource://gre/modules/Integration.jsm",
L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
LightweightThemeManager: "resource://gre/modules/LightweightThemeManager.jsm",
LiveBookmarkMigrator: "resource:///modules/LiveBookmarkMigrator.jsm",
NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
Normandy: "resource://normandy/Normandy.jsm",
@ -1037,53 +1036,12 @@ BrowserGlue.prototype = {
SessionStore.init();
let vendorShortName = gBrandBundle.GetStringFromName("vendorShortName");
LightweightThemeManager.addBuiltInTheme({
id: "firefox-compact-light@mozilla.org",
name: gBrowserBundle.GetStringFromName("lightTheme.name"),
description: gBrowserBundle.GetStringFromName("lightTheme.description"),
iconURL: "resource:///chrome/browser/content/browser/defaultthemes/light.icon.svg",
textcolor: "rgb(24, 25, 26)",
icon_color: "rgb(24, 25, 26, 0.7)",
accentcolor: "#E3E4E6",
popup: "#fff",
popup_text: "#0c0c0d",
popup_border: "#ccc",
tab_line: "#0a84ff",
toolbarColor: "#f5f6f7",
toolbar_bottom_separator: "#ccc",
toolbar_field: "#fff",
toolbar_field_border: "#ccc",
author: vendorShortName,
});
LightweightThemeManager.addBuiltInTheme({
id: "firefox-compact-dark@mozilla.org",
name: gBrowserBundle.GetStringFromName("darkTheme.name"),
description: gBrowserBundle.GetStringFromName("darkTheme.description"),
iconURL: "resource:///chrome/browser/content/browser/defaultthemes/dark.icon.svg",
textcolor: "rgb(249, 249, 250)",
icon_color: "rgb(249, 249, 250, 0.7)",
accentcolor: "hsl(240, 5%, 5%)",
popup: "#4a4a4f",
popup_text: "rgb(249, 249, 250)",
popup_border: "#27272b",
tab_line: "#0a84ff",
toolbarColor: "hsl(240, 1%, 20%)",
toolbar_bottom_separator: "hsl(240, 5%, 5%)",
toolbar_field: "rgb(71, 71, 73)",
toolbar_field_border: "rgba(249, 249, 250, 0.2)",
toolbar_field_separator: "#5F6670",
toolbar_field_text: "rgb(249, 249, 250)",
ntp_background: "#2A2A2E",
ntp_text: "rgb(249, 249, 250)",
sidebar: "#38383D",
sidebar_text: "rgb(249, 249, 250)",
sidebar_border: "rgba(255, 255, 255, 0.1)",
author: vendorShortName,
}, {
useInDarkMode: true,
});
AddonManager.maybeInstallBuiltinAddon(
"firefox-compact-light@mozilla.org", "1.0",
"resource:///modules/themes/light/");
AddonManager.maybeInstallBuiltinAddon(
"firefox-compact-dark@mozilla.org", "1.0",
"resource:///modules/themes/dark/");
Normandy.init();

Просмотреть файл

@ -184,10 +184,13 @@ var CustomizableUIInternal = {
initialize() {
log.debug("Initializing");
Services.obs.addObserver(this, "xpi-database-loaded");
if (AddonManagerPrivate.isDBLoaded()) {
this.observe(null, "xpi-database-loaded");
}
AddonManagerPrivate.databaseReady.then(async () => {
AddonManager.addAddonListener(this);
let addons = await AddonManager.getAddonsByTypes(["theme"]);
gDefaultTheme = addons.find(addon => addon.id == kDefaultThemeID);
gSelectedTheme = addons.find(addon => addon.isActive) || gDefaultTheme;
});
this.addListener(this);
this._defineBuiltInWidgets();
@ -256,16 +259,6 @@ var CustomizableUIInternal = {
SearchWidgetTracker.init();
},
async observe(subject, topic, data) {
if (topic == "xpi-database-loaded") {
AddonManager.addAddonListener(this);
let addons = await AddonManager.getAddonsByTypes(["theme"]);
gDefaultTheme = addons.find(addon => addon.id == kDefaultThemeID);
gSelectedTheme = addons.find(addon => addon.isActive) || gDefaultTheme;
}
},
onEnabled(addon) {
if (addon.type == "theme") {
gSelectedTheme = addon;

Просмотреть файл

@ -60,7 +60,7 @@ add_task(async function() {
is(header.nextElementSibling.nextElementSibling.nextElementSibling.theme.id, DARK_THEME_ID,
"The third theme should be the dark theme");
let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
let themeChangedPromise = promiseObserverNotified("lightweight-theme-styling-update");
header.nextElementSibling.nextElementSibling.doCommand(); // Select light theme
info("Clicked on light theme");
await themeChangedPromise;
@ -87,7 +87,7 @@ add_task(async function() {
let firstLWTheme = footer.previousElementSibling;
let firstLWThemeId = firstLWTheme.theme.id;
themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
themeChangedPromise = promiseObserverNotified("lightweight-theme-styling-update");
firstLWTheme.doCommand();
info("Clicked on first theme");
await themeChangedPromise;
@ -118,8 +118,6 @@ add_task(async function() {
let defaultTheme = header.nextElementSibling;
defaultTheme.doCommand();
await new Promise(SimpleTest.executeSoon);
is(Services.prefs.getCharPref("lightweightThemes.selectedThemeID"),
DEFAULT_THEME_ID, "Default theme should be selected");
// ensure current theme isn't set to "Default"
popupShownPromise = popupShown(popup);

Просмотреть файл

@ -26,7 +26,7 @@ add_task(async function() {
let header = document.getElementById("customization-lwtheme-menu-header");
let firstLWTheme = header.nextElementSibling.nextElementSibling;
let firstLWThemeId = firstLWTheme.theme.id;
let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
let themeChangedPromise = promiseObserverNotified("lightweight-theme-styling-update");
firstLWTheme.doCommand();
info("Clicked on first theme");
await themeChangedPromise;

Просмотреть файл

@ -0,0 +1,12 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# LOCALIZATION NOTE (extension.firefox-compact-light@mozilla.org.name): This is displayed in about:addons -> Appearance
extension.firefox-compact-light@mozilla.org.name=Light
extension.firefox-compact-light@mozilla.org.description=A theme with a light color scheme.
# LOCALIZATION NOTE (extension.firefox-compact-dark@mozilla.org.name): This is displayed in about:addons -> Appearance
extension.firefox-compact-dark@mozilla.org.name=Dark
extension.firefox-compact-dark@mozilla.org.description=A theme with a dark color scheme.

Просмотреть файл

@ -235,14 +235,6 @@ unsignedAddonsDisabled.message=One or more installed add-ons cannot be verified
unsignedAddonsDisabled.learnMore.label=Learn More
unsignedAddonsDisabled.learnMore.accesskey=L
# LOCALIZATION NOTE (lightTheme.name): This is displayed in about:addons -> Appearance
lightTheme.name=Light
lightTheme.description=A theme with a light color scheme.
# LOCALIZATION NOTE (darkTheme.name): This is displayed in about:addons -> Appearance
darkTheme.name=Dark
darkTheme.description=A theme with a dark color scheme.
# LOCALIZATION NOTE (lwthemeInstallRequest.message2): %S will be replaced with
# the host name of the site.
lwthemeInstallRequest.message2=This site (%S) attempted to install a theme.

Просмотреть файл

@ -16,6 +16,7 @@
locale/browser/bookmarks.html (bookmarks.html)
locale/browser/accounts.properties (%chrome/browser/accounts.properties)
locale/browser/app-extension-fields.properties (%chrome/browser/app-extension-fields.properties)
locale/browser/browser.dtd (%chrome/browser/browser.dtd)
locale/browser/baseMenuOverlay.dtd (%chrome/browser/baseMenuOverlay.dtd)
locale/browser/browser.properties (%chrome/browser/browser.properties)

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 1.0 KiB

После

Ширина:  |  Высота:  |  Размер: 1.0 KiB

Просмотреть файл

@ -0,0 +1,39 @@
{
"manifest_version": 2,
"applications": {
"gecko": {
"id": "firefox-compact-dark@mozilla.org"
}
},
"name": "Dark",
"description": "A theme with a dark color scheme.",
"author": "Mozilla",
"version": "1.0",
"icons": {"32": "icon.svg"},
"theme": {
"colors": {
"tab_background_text": "rgb(249, 249, 250)",
"icons": "rgb(249, 249, 250, 0.7)",
"frame": "hsl(240, 5%, 5%)",
"popup": "#4a4a4f",
"popup_text": "rgb(249, 249, 250)",
"popup_border": "#27272b",
"tab_line": "#0a84ff",
"toolbar": "hsl(240, 1%, 20%)",
"toolbar_bottom_separator": "hsl(240, 5%, 5%)",
"toolbar_field": "rgb(71, 71, 73)",
"toolbar_field_border": "rgba(249, 249, 250, 0.2)",
"toolbar_field_separator": "#5F6670",
"toolbar_field_text": "rgb(249, 249, 250)",
"ntp_background": "#2A2A2E",
"ntp_text": "rgb(249, 249, 250)",
"sidebar": "#38383D",
"sidebar_text": "rgb(249, 249, 250)",
"sidebar_border": "rgba(255, 255, 255, 0.1)"
}
}
}

Просмотреть файл

@ -0,0 +1,10 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
EXTRA_JS_MODULES.themes['dark'] += [
'icon.svg',
'manifest.json',
]

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 1.1 KiB

После

Ширина:  |  Высота:  |  Размер: 1.1 KiB

Просмотреть файл

@ -0,0 +1,32 @@
{
"manifest_version": 2,
"applications": {
"gecko": {
"id": "firefox-compact-light@mozilla.org"
}
},
"name": "Light",
"description": "A theme with a light color scheme.",
"author": "Mozilla",
"version": "1.0",
"icons": {"32": "icon.svg"},
"theme": {
"colors": {
"tab_background_text": "rgb(24, 25, 26)",
"icons": "rgb(24, 25, 26, 0.7)",
"frame": "#E3E4E6",
"popup": "#fff",
"popup_text": "#0c0c0d",
"popup_border": "#ccc",
"tab_line": "#0a84ff",
"toolbar": "#f5f6f7",
"toolbar_bottom_separator": "#ccc",
"toolbar_field": "#fff",
"toolbar_field_border": "#ccc"
}
}
}

Просмотреть файл

@ -0,0 +1,10 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
EXTRA_JS_MODULES.themes['light'] += [
'icon.svg',
'manifest.json',
]

Просмотреть файл

@ -16,6 +16,11 @@ elif toolkit == 'gtk3':
else:
DIRS += ['windows']
DIRS += [
'addons/dark',
'addons/light',
]
with Files('osx/**'):
SCHEDULES.exclusive = ['macosx']

Просмотреть файл

@ -158,7 +158,7 @@
}
#customization-lwtheme-button > .box-inherit > .box-inherit > .button-icon {
background-image: url("chrome://mozapps/content/extensions/default-theme-icon.svg");
background-image: url("resource://gre/modules/themes/default/icon.svg");
}
#customization-uidensity-button > .box-inherit > .box-inherit > .button-icon {

Просмотреть файл

@ -6,81 +6,34 @@
var EXPORTED_SYMBOLS = ["LightweightThemes"];
const {LightweightThemeManager} = ChromeUtils.import("resource://gre/modules/LightweightThemeManager.jsm");
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm");
const {AddonManager} = ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
var LightweightThemes = {
init(libDir) {
// convert -size 3000x200 canvas:#333 black_theme.png
let blackImage = libDir.clone();
blackImage.append("black_theme.png");
this._blackImageURL = Services.io.newFileURI(blackImage).spec;
// convert -size 3000x200 canvas:#eee white_theme.png
let whiteImage = libDir.clone();
whiteImage.append("white_theme.png");
this._whiteImageURL = Services.io.newFileURI(whiteImage).spec;
},
configurations: {
noLWT: {
selectors: [],
async applyConfig() {
LightweightThemeManager.currentTheme = null;
},
},
darkLWT: {
selectors: [],
applyConfig() {
LightweightThemeManager.setLocalTheme({
id: "black",
name: "black",
headerURL: LightweightThemes._blackImageURL,
textcolor: "#eeeeee",
accentcolor: "#111111",
});
// Wait for LWT listener
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, 500);
});
},
},
lightLWT: {
selectors: [],
applyConfig() {
LightweightThemeManager.setLocalTheme({
id: "white",
name: "white",
headerURL: LightweightThemes._whiteImageURL,
textcolor: "#111111",
accentcolor: "#eeeeee",
});
// Wait for LWT listener
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, 500);
});
let addon = await AddonManager.getAddonByID("default-theme@mozilla.org");
await addon.enable();
},
},
compactLight: {
selectors: [],
applyConfig() {
LightweightThemeManager.currentTheme = LightweightThemeManager.getUsedTheme("firefox-compact-light@mozilla.org");
async applyConfig() {
let addon = await AddonManager.getAddonByID("firefox-compact-light@mozilla.org");
await addon.enable();
},
},
compactDark: {
selectors: [],
applyConfig() {
LightweightThemeManager.currentTheme = LightweightThemeManager.getUsedTheme("firefox-compact-dark@mozilla.org");
async applyConfig() {
let addon = await AddonManager.getAddonByID("firefox-compact-dark@mozilla.org");
await addon.enable();
},
},
},

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 183 B

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 183 B

Просмотреть файл

@ -36,7 +36,6 @@ FINAL_TARGET_FILES.resources.configurations += [
]
FINAL_TARGET_FILES.resources.lib += [
'lib/black_theme.png',
'lib/borderify.xpi',
'lib/mozscreenshots-script.js',
'lib/mozscreenshots-style.css',
@ -48,7 +47,6 @@ FINAL_TARGET_FILES.resources.lib += [
'lib/robot_diagonal.png',
'lib/robot_uncropped.png',
'lib/robot_upperleft.png',
'lib/white_theme.png',
]
FINAL_TARGET_FILES.resources.lib.controlCenter += [

Просмотреть файл

@ -5879,7 +5879,7 @@ g.addColorStop(1, '#f00');
ctx.fillStyle = g;
ctx.fillRect(0, 0, 100, 50);
todo_isPixel(ctx, 40,20, 0,255,0,255, 2);
isPixel(ctx, 40,20, 0,255,0,255, 2);
}
</script>

Просмотреть файл

@ -1940,11 +1940,7 @@ already_AddRefed<ID2D1Brush> DrawTargetD2D1::CreateBrushForPattern(
}
if (pat->mBegin == pat->mEnd) {
uint32_t stopCount = stops->mStopCollection->GetGradientStopCount();
vector<D2D1_GRADIENT_STOP> d2dStops(stopCount);
stops->mStopCollection->GetGradientStops(&d2dStops.front(), stopCount);
d2dStops.back().color.a *= aAlpha;
return GetSolidColorBrush(d2dStops.back().color);
return CreateTransparentBlackBrush();
}
mDC->CreateLinearGradientBrush(
@ -1973,6 +1969,10 @@ already_AddRefed<ID2D1Brush> DrawTargetD2D1::CreateBrushForPattern(
return CreateTransparentBlackBrush();
}
if (pat->mCenter1 == pat->mCenter2 && pat->mRadius1 == pat->mRadius2) {
return CreateTransparentBlackBrush();
}
// This will not be a complex radial gradient brush.
mDC->CreateRadialGradientBrush(
D2D1::RadialGradientBrushProperties(

Просмотреть файл

@ -14,6 +14,8 @@
#include "mozilla/CheckedInt.h"
#include "mozilla/Vector.h"
#include "skia/include/core/SkFont.h"
#include "skia/include/core/SkTextBlob.h"
#include "skia/include/core/SkSurface.h"
#include "skia/include/core/SkTypeface.h"
#include "skia/include/effects/SkGradientShader.h"
@ -432,8 +434,9 @@ static void SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern,
static_cast<const LinearGradientPattern&>(aPattern);
GradientStopsSkia* stops =
static_cast<GradientStopsSkia*>(pat.mStops.get());
if (!stops || stops->mCount < 2 || !pat.mBegin.IsFinite() ||
!pat.mEnd.IsFinite()) {
if (!stops || stops->mCount < 2 ||
!pat.mBegin.IsFinite() || !pat.mEnd.IsFinite() ||
pat.mBegin == pat.mEnd) {
aPaint.setColor(SK_ColorTRANSPARENT);
} else {
SkShader::TileMode mode =
@ -465,9 +468,10 @@ static void SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern,
static_cast<const RadialGradientPattern&>(aPattern);
GradientStopsSkia* stops =
static_cast<GradientStopsSkia*>(pat.mStops.get());
if (!stops || stops->mCount < 2 || !pat.mCenter1.IsFinite() ||
!IsFinite(pat.mRadius1) || !pat.mCenter2.IsFinite() ||
!IsFinite(pat.mRadius2)) {
if (!stops || stops->mCount < 2 ||
!pat.mCenter1.IsFinite() || !IsFinite(pat.mRadius1) ||
!pat.mCenter2.IsFinite() || !IsFinite(pat.mRadius2) ||
(pat.mCenter1 == pat.mCenter2 && pat.mRadius1 == pat.mRadius2)) {
aPaint.setColor(SK_ColorTRANSPARENT);
} else {
SkShader::TileMode mode =
@ -595,7 +599,8 @@ struct AutoPaintSetup {
temp.setBlendMode(GfxOpToSkiaOp(aOptions.mCompositionOp));
temp.setAlpha(ColorFloatToByte(aOptions.mAlpha));
// TODO: Get a rect here
mCanvas->saveLayerPreserveLCDTextRequests(nullptr, &temp);
SkCanvas::SaveLayerRec rec(nullptr, &temp, SkCanvas::kPreserveLCDText_SaveLayerFlag);
mCanvas->saveLayer(rec);
mNeedsRestore = true;
} else {
mPaint.setAlpha(ColorFloatToByte(aOptions.mAlpha));
@ -1314,17 +1319,16 @@ void DrawTargetSkia::DrawGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,
aaMode = aOptions.mAntialiasMode;
}
bool aaEnabled = aaMode != AntialiasMode::NONE;
paint.mPaint.setAntiAlias(aaEnabled);
paint.mPaint.setTypeface(sk_ref_sp(typeface));
paint.mPaint.setTextSize(SkFloatToScalar(skiaFont->mSize));
paint.mPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
bool shouldLCDRenderText = ShouldLCDRenderText(aFont->GetType(), aaMode);
paint.mPaint.setLCDRenderText(shouldLCDRenderText);
SkFont font(sk_ref_sp(typeface), SkFloatToScalar(skiaFont->mSize));
bool useSubpixelAA = ShouldLCDRenderText(aFont->GetType(), aaMode);
font.setEdging(useSubpixelAA ?
SkFont::Edging::kSubpixelAntiAlias :
(aaEnabled ? SkFont::Edging::kAntiAlias : SkFont::Edging::kAlias));
bool useSubpixelText = true;
switch (aFont->GetType()) {
case FontType::FREETYPE:
case FontType::FONTCONFIG:
@ -1349,17 +1353,17 @@ void DrawTargetSkia::DrawGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,
// disabling the LCD font smoothing behaviour.
// To accomplish this we have to explicitly disable hinting,
// and disable LCDRenderText.
paint.mPaint.setHinting(SkPaint::kNo_Hinting);
font.setHinting(kNo_SkFontHinting);
}
break;
#ifdef XP_WIN
case FontType::DWRITE: {
ScaledFontDWrite* dwriteFont = static_cast<ScaledFontDWrite*>(aFont);
paint.mPaint.setEmbeddedBitmapText(dwriteFont->UseEmbeddedBitmaps());
if (dwriteFont->ForceGDIMode()) {
paint.mPaint.setEmbeddedBitmapText(true);
font.setEmbeddedBitmaps(true);
useSubpixelText = false;
} else {
font.setEmbeddedBitmaps(dwriteFont->UseEmbeddedBitmaps());
}
break;
}
@ -1368,23 +1372,16 @@ void DrawTargetSkia::DrawGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,
break;
}
paint.mPaint.setSubpixelText(useSubpixelText);
Vector<uint16_t, 64> indices;
Vector<SkPoint, 64> offsets;
if (!indices.resizeUninitialized(aBuffer.mNumGlyphs) ||
!offsets.resizeUninitialized(aBuffer.mNumGlyphs)) {
gfxDebug() << "Failed allocating Skia text buffers for GlyphBuffer";
return;
}
font.setSubpixel(useSubpixelText);
SkTextBlobBuilder builder;
auto runBuffer = builder.allocRunPos(font, aBuffer.mNumGlyphs);
for (uint32_t i = 0; i < aBuffer.mNumGlyphs; i++) {
indices[i] = aBuffer.mGlyphs[i].mIndex;
offsets[i] = PointToSkPoint(aBuffer.mGlyphs[i].mPosition);
runBuffer.glyphs[i] = aBuffer.mGlyphs[i].mIndex;
runBuffer.points()[i] = PointToSkPoint(aBuffer.mGlyphs[i].mPosition);
}
mCanvas->drawPosText(indices.begin(), indices.length() * sizeof(uint16_t),
offsets.begin(), paint.mPaint);
sk_sp<SkTextBlob> text = builder.make();
mCanvas->drawTextBlob(text, 0, 0, paint.mPaint);
}
void DrawTargetSkia::FillGlyphs(ScaledFont* aFont, const GlyphBuffer& aBuffer,

Просмотреть файл

@ -280,18 +280,18 @@ static inline SkShader::TileMode ExtendModeToTileMode(ExtendMode aMode,
return SkShader::kClamp_TileMode;
}
static inline SkPaint::Hinting GfxHintingToSkiaHinting(FontHinting aHinting) {
static inline SkFontHinting GfxHintingToSkiaHinting(FontHinting aHinting) {
switch (aHinting) {
case FontHinting::NONE:
return SkPaint::kNo_Hinting;
return kNo_SkFontHinting;
case FontHinting::LIGHT:
return SkPaint::kSlight_Hinting;
return kSlight_SkFontHinting;
case FontHinting::NORMAL:
return SkPaint::kNormal_Hinting;
return kNormal_SkFontHinting;
case FontHinting::FULL:
return SkPaint::kFull_Hinting;
return kFull_SkFontHinting;
}
return SkPaint::kNormal_Hinting;
return kNormal_SkFontHinting;
}
static inline FillRule GetFillRule(SkPath::FillType aFillType) {

Просмотреть файл

@ -10,7 +10,7 @@
#ifdef USE_SKIA
# include "PathSkia.h"
# include "skia/include/core/SkPaint.h"
# include "skia/include/core/SkFont.h"
#endif
#ifdef USE_CAIRO
@ -109,26 +109,32 @@ SkPath ScaledFontBase::GetSkiaPathForGlyphs(const GlyphBuffer &aBuffer) {
SkTypeface *typeFace = GetSkTypeface();
MOZ_ASSERT(typeFace);
SkPaint paint;
paint.setTypeface(sk_ref_sp(typeFace));
paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
paint.setTextSize(SkFloatToScalar(mSize));
SkFont font(sk_ref_sp(typeFace), SkFloatToScalar(mSize));
std::vector<uint16_t> indices;
std::vector<SkPoint> offsets;
indices.resize(aBuffer.mNumGlyphs);
offsets.resize(aBuffer.mNumGlyphs);
for (unsigned int i = 0; i < aBuffer.mNumGlyphs; i++) {
indices[i] = aBuffer.mGlyphs[i].mIndex;
offsets[i].fX = SkFloatToScalar(aBuffer.mGlyphs[i].mPosition.x);
offsets[i].fY = SkFloatToScalar(aBuffer.mGlyphs[i].mPosition.y);
}
SkPath path;
paint.getPosTextPath(&indices.front(), aBuffer.mNumGlyphs * 2,
&offsets.front(), &path);
return path;
struct Context {
const Glyph* mGlyph;
SkPath mPath;
} ctx = { aBuffer.mGlyphs };
font.getPaths(indices.data(), indices.size(),
[](const SkPath* glyphPath, const SkMatrix& scaleMatrix, void* ctxPtr) {
Context& ctx = *reinterpret_cast<Context*>(ctxPtr);
if (glyphPath) {
SkMatrix transMatrix(scaleMatrix);
transMatrix.postTranslate(SkFloatToScalar(ctx.mGlyph->mPosition.x),
SkFloatToScalar(ctx.mGlyph->mPosition.y));
ctx.mPath.addPath(*glyphPath, transMatrix);
}
++ctx.mGlyph;
}, &ctx);
return ctx.mPath;
}
#endif

Просмотреть файл

@ -14,6 +14,7 @@
#include "mozilla/Sprintf.h"
#include "mozilla/gfx/HelpersSkia.h"
#include "skia/include/core/SkFont.h"
#include "PaintCounter.h"
namespace mozilla {
@ -48,12 +49,14 @@ void PaintCounter::Draw(Compositor* aCompositor, TimeDuration aPaintTime,
aCompositeTime.ToMilliseconds());
SkPaint paint;
paint.setTextSize(32);
paint.setColor(SkColorSetRGB(0, 255, 0));
paint.setAntiAlias(true);
SkFont font(SkTypeface::MakeDefault(), 32);
mCanvas->clear(SK_ColorTRANSPARENT);
mCanvas->drawText(buffer, strlen(buffer), 10, 30, paint);
mCanvas->drawSimpleText(buffer, strlen(buffer), kUTF8_SkTextEncoding,
10, 30, font, paint);
mCanvas->flush();
if (!mTextureSource) {

Просмотреть файл

@ -76,9 +76,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
# We should autogenerate these SSE related flags.
if CONFIG['INTEL_ARCHITECTURE']:
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-mssse3']
SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
SOURCES['skia/src/opts/SkOpts_sse42.cpp'].flags += ['-msse4.2']
@ -148,9 +145,13 @@ def generate_opt_sources():
subprocess.check_output('cd skia && bin/gn gen out/{0} --args=\'target_cpu="{1}"\''.format(key, cpu), shell=True)
opt_sources[key] = set()
for dep in deps:
output = subprocess.check_output('cd skia && bin/gn desc out/{0} {1} sources'.format(key, dep), shell=True)
if output:
opt_sources[key].update(parse_sources(output))
try:
output = subprocess.check_output('cd skia && bin/gn desc out/{0} {1} sources'.format(key, dep), shell=True)
if output:
opt_sources[key].update(parse_sources(output))
except subprocess.CalledProcessError as e:
if e.output.find('source_set') < 0:
raise
return opt_sources
@ -165,7 +166,13 @@ def generate_platform_sources():
if output:
sources[plat] = parse_sources(output)
deps = {':effects' : 'common', ':pdf' : 'pdf'}
plat_deps = {':fontmgr_win' : 'win', ':fontmgr_win_gdi' : 'win'}
for dep, key in plat_deps.items():
output = subprocess.check_output('cd skia && bin/gn desc out/{1} {0} sources'.format(dep, key), shell=True)
if output:
sources[key].update(parse_sources(output))
deps = {':pdf' : 'pdf'}
for dep, key in deps.items():
output = subprocess.check_output('cd skia && bin/gn desc out/linux {} sources'.format(dep), shell=True)
if output:
@ -188,6 +195,7 @@ def generate_separated_sources(platform_sources):
'SkLight',
'SkNormal',
'codec',
'SkWGL',
'SkMemory_malloc',
'third_party',
'Sk3D',
@ -204,7 +212,6 @@ def generate_separated_sources(platform_sources):
'SkOverdrawCanvas',
'SkPaintFilterCanvas',
'SkParseColor',
'SkTextBox',
'SkWhitelistTypefaces',
'SkXPS',
'SkCreateCGImageRef',
@ -225,7 +232,6 @@ def generate_separated_sources(platform_sources):
'skia/src/effects/SkDashPathEffect.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkGlobalInitialization_default.cpp',
'skia/src/ports/SkGlobalInitialization_default_imagefilters.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
'skia/src/ports/SkImageGenerator_none.cpp',
'skia/third_party/skcms/skcms.cc',
@ -298,13 +304,11 @@ def write_cflags(f, values, subsearch, cflag, indent):
f.write("SOURCES[\'" + val + "\'].flags += " + cflag + "\n")
opt_whitelist = [
'skia/src/opts/Sk',
'SkOpts',
'SkBitmapProcState',
'SkBlitMask',
'SkBitmapScaler',
'SkBlitRow',
'SkBlitter',
'SkJumper',
'SkSpriteBlitter',
'SkMatrix.cpp',
'skcms',
@ -314,7 +318,6 @@ opt_whitelist = [
# non-unifiable. Keep track of this and fix it.
unified_blacklist = [
'FontHost',
'SkAdvancedTypefaceMetrics',
'SkBitmapProcState_matrixProcs.cpp',
'SkBlitter_A8.cpp',
'SkBlitter_ARGB32.cpp',
@ -327,7 +330,6 @@ unified_blacklist = [
'SkPDFFont.cpp',
'SkPictureData.cpp',
'SkColorSpace',
'SkImage_Gpu.cpp',
'SkPathOpsDebug.cpp',
'SkParsePath.cpp',
'SkRecorder.cpp',
@ -336,10 +338,8 @@ unified_blacklist = [
'SkMatrix44.cpp',
'SkRTree.cpp',
'SkVertices.cpp',
'SkJumper',
'SkSLHCodeGenerator.cpp',
'SkSLLexer.cpp',
'SkSLLayoutLexer.cpp',
] + opt_whitelist
def write_sources(f, values, indent):
@ -410,16 +410,19 @@ def write_mozbuild(sources):
write_sources(f, sources['intel'], 4)
write_cflags(f, sources['intel'], opt_whitelist, 'skia_opt_flags', 4)
f.write("elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['CC_TYPE'] in ('clang', 'gcc'):\n")
write_sources(f, sources['arm'], 4)
write_cflags(f, sources['arm'], opt_whitelist, 'skia_opt_flags', 4)
if sources['arm']:
f.write("elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['CC_TYPE'] in ('clang', 'gcc'):\n")
write_sources(f, sources['arm'], 4)
write_cflags(f, sources['arm'], opt_whitelist, 'skia_opt_flags', 4)
f.write("elif CONFIG['CPU_ARCH'] == 'aarch64':\n")
write_sources(f, sources['arm64'], 4)
write_cflags(f, sources['arm64'], opt_whitelist, 'skia_opt_flags', 4)
if sources['arm64']:
f.write("elif CONFIG['CPU_ARCH'] == 'aarch64':\n")
write_sources(f, sources['arm64'], 4)
write_cflags(f, sources['arm64'], opt_whitelist, 'skia_opt_flags', 4)
f.write("else:\n")
write_sources(f, sources['none'], 4)
if sources['none']:
f.write("else:\n")
write_sources(f, sources['none'], 4)
f.write(footer)

Просмотреть файл

@ -38,7 +38,6 @@ UNIFIED_SOURCES += [
'skia/src/core/SkBitmapController.cpp',
'skia/src/core/SkBitmapDevice.cpp',
'skia/src/core/SkBitmapProvider.cpp',
'skia/src/core/SkBitmapScaler.cpp',
'skia/src/core/SkBlendMode.cpp',
'skia/src/core/SkBlurMask.cpp',
'skia/src/core/SkBlurMF.cpp',
@ -51,6 +50,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkColor.cpp',
'skia/src/core/SkColorFilter.cpp',
'skia/src/core/SkColorMatrixFilterRowMajor255.cpp',
'skia/src/core/SkContourMeasure.cpp',
'skia/src/core/SkConvertPixels.cpp',
'skia/src/core/SkConvolver.cpp',
'skia/src/core/SkCoverageDelta.cpp',
@ -63,6 +63,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkDeferredDisplayList.cpp',
'skia/src/core/SkDeferredDisplayListRecorder.cpp',
'skia/src/core/SkDeque.cpp',
'skia/src/core/SkDescriptor.cpp',
'skia/src/core/SkDevice.cpp',
'skia/src/core/SkDistanceFieldGen.cpp',
'skia/src/core/SkDocument.cpp',
@ -76,18 +77,17 @@ UNIFIED_SOURCES += [
'skia/src/core/SkEdgeBuilder.cpp',
'skia/src/core/SkEdgeClipper.cpp',
'skia/src/core/SkExecutor.cpp',
'skia/src/core/SkFDot6Constants.cpp',
'skia/src/core/SkFlattenable.cpp',
'skia/src/core/SkFont.cpp',
'skia/src/core/SkFontDescriptor.cpp',
'skia/src/core/SkFontLCDConfig.cpp',
'skia/src/core/SkFontMgr.cpp',
'skia/src/core/SkFontPriv.cpp',
'skia/src/core/SkFontStream.cpp',
'skia/src/core/SkGaussFilter.cpp',
'skia/src/core/SkGeometry.cpp',
'skia/src/core/SkGlobalInitialization_core.cpp',
'skia/src/core/SkGlyph.cpp',
'skia/src/core/SkGlyphCache.cpp',
'skia/src/core/SkGlyphRun.cpp',
'skia/src/core/SkGlyphRunPainter.cpp',
'skia/src/core/SkGpuBlurUtils.cpp',
@ -110,12 +110,10 @@ UNIFIED_SOURCES += [
'skia/src/core/SkMath.cpp',
'skia/src/core/SkMatrixImageFilter.cpp',
'skia/src/core/SkMD5.cpp',
'skia/src/core/SkMetaData.cpp',
'skia/src/core/SkMipMap.cpp',
'skia/src/core/SkModeColorFilter.cpp',
'skia/src/core/SkMultiPictureDraw.cpp',
'skia/src/core/SkPaint.cpp',
'skia/src/core/SkPaint_text.cpp',
'skia/src/core/SkPaintPriv.cpp',
'skia/src/core/SkPath.cpp',
'skia/src/core/SkPath_serial.cpp',
@ -132,6 +130,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkPixmap.cpp',
'skia/src/core/SkPoint.cpp',
'skia/src/core/SkPoint3.cpp',
'skia/src/core/SkPromiseImageTexture.cpp',
'skia/src/core/SkPtrRecorder.cpp',
'skia/src/core/SkQuadClipper.cpp',
'skia/src/core/SkRasterClip.cpp',
@ -162,6 +161,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkSpecialSurface.cpp',
'skia/src/core/SkSpinlock.cpp',
'skia/src/core/SkStream.cpp',
'skia/src/core/SkStrike.cpp',
'skia/src/core/SkStrikeCache.cpp',
'skia/src/core/SkString.cpp',
'skia/src/core/SkStringUtils.cpp',
@ -184,6 +184,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkVertState.cpp',
'skia/src/core/SkWriteBuffer.cpp',
'skia/src/core/SkWriter32.cpp',
'skia/src/core/SkYUVASizeInfo.cpp',
'skia/src/core/SkYUVPlanesCache.cpp',
'skia/src/effects/imagefilters/SkBlurImageFilter.cpp',
'skia/src/effects/SkDashPathEffect.cpp',
@ -216,7 +217,6 @@ UNIFIED_SOURCES += [
'skia/src/pathops/SkPathOpsCurve.cpp',
'skia/src/pathops/SkPathOpsLine.cpp',
'skia/src/pathops/SkPathOpsOp.cpp',
'skia/src/pathops/SkPathOpsPoint.cpp',
'skia/src/pathops/SkPathOpsQuad.cpp',
'skia/src/pathops/SkPathOpsRect.cpp',
'skia/src/pathops/SkPathOpsSimplify.cpp',
@ -228,7 +228,6 @@ UNIFIED_SOURCES += [
'skia/src/pathops/SkReduceOrder.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkGlobalInitialization_default.cpp',
'skia/src/ports/SkGlobalInitialization_default_imagefilters.cpp',
'skia/src/ports/SkImageGenerator_none.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
'skia/src/ports/SkOSFile_stdio.cpp',
@ -256,11 +255,13 @@ UNIFIED_SOURCES += [
'skia/src/utils/SkEventTracer.cpp',
'skia/src/utils/SkFloatToDecimal.cpp',
'skia/src/utils/SkMatrix22.cpp',
'skia/src/utils/SkMetaData.cpp',
'skia/src/utils/SkOSPath.cpp',
'skia/src/utils/SkPatchUtils.cpp',
'skia/src/utils/SkPolyUtils.cpp',
'skia/src/utils/SkShadowTessellator.cpp',
'skia/src/utils/SkShadowUtils.cpp',
'skia/src/utils/SkTextUtils.cpp',
'skia/src/utils/SkThreadUtils_pthread.cpp',
'skia/src/utils/SkThreadUtils_win.cpp',
'skia/src/utils/SkUTF.cpp',
@ -274,7 +275,7 @@ UNIFIED_SOURCES += [
SOURCES += [
'skia/src/core/SkBitmapProcState.cpp',
'skia/src/core/SkBitmapProcState_matrixProcs.cpp',
'skia/src/core/SkBlitMask_D32.cpp',
'skia/src/core/SkBitmapScaler.cpp',
'skia/src/core/SkBlitRow_D32.cpp',
'skia/src/core/SkBlitter.cpp',
'skia/src/core/SkBlitter_A8.cpp',
@ -300,7 +301,6 @@ SOURCES += [
'skia/src/core/SkVertices.cpp',
'skia/src/core/SkXfermode.cpp',
'skia/src/core/SkXfermodeInterpretation.cpp',
'skia/src/jumper/SkJumper.cpp',
'skia/src/pathops/SkPathOpsDebug.cpp',
'skia/src/utils/SkParse.cpp',
'skia/src/utils/SkParsePath.cpp',
@ -308,7 +308,7 @@ SOURCES += [
]
SOURCES['skia/src/core/SkBitmapProcState.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBitmapProcState_matrixProcs.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBlitMask_D32.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBitmapScaler.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBlitRow_D32.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBlitter.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBlitter_A8.cpp'].flags += skia_opt_flags
@ -319,7 +319,6 @@ SOURCES['skia/src/core/SkMatrix.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkOpts.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkSpriteBlitter_ARGB32.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkSpriteBlitter_RGB565.cpp'].flags += skia_opt_flags
SOURCES['skia/src/jumper/SkJumper.cpp'].flags += skia_opt_flags
SOURCES['skia/third_party/skcms/skcms.cc'].flags += skia_opt_flags
if CONFIG['MOZ_ENABLE_SKIA_PDF']:
UNIFIED_SOURCES += [
@ -328,7 +327,6 @@ if CONFIG['MOZ_ENABLE_SKIA_PDF']:
'skia/src/pdf/SkJpegInfo.cpp',
'skia/src/pdf/SkKeyedImage.cpp',
'skia/src/pdf/SkPDFBitmap.cpp',
'skia/src/pdf/SkPDFCanon.cpp',
'skia/src/pdf/SkPDFConvertType1FontStream.cpp',
'skia/src/pdf/SkPDFDevice.cpp',
'skia/src/pdf/SkPDFDocument.cpp',
@ -340,6 +338,7 @@ if CONFIG['MOZ_ENABLE_SKIA_PDF']:
'skia/src/pdf/SkPDFMetadata.cpp',
'skia/src/pdf/SkPDFResourceDict.cpp',
'skia/src/pdf/SkPDFShader.cpp',
'skia/src/pdf/SkPDFSubsetFont.cpp',
'skia/src/pdf/SkPDFTag.cpp',
'skia/src/pdf/SkPDFTypes.cpp',
'skia/src/pdf/SkPDFUtils.cpp',
@ -392,69 +391,23 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
'skia/src/ports/SkTypeface_win_dw.cpp',
]
if CONFIG['INTEL_ARCHITECTURE']:
UNIFIED_SOURCES += [
'skia/src/opts/opts_check_x86.cpp',
]
SOURCES += [
'skia/src/opts/SkBitmapProcState_opts_SSE2.cpp',
'skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp',
'skia/src/opts/SkBlitRow_opts_SSE2.cpp',
'skia/src/opts/SkOpts_avx.cpp',
'skia/src/opts/SkOpts_hsw.cpp',
'skia/src/opts/SkOpts_sse41.cpp',
'skia/src/opts/SkOpts_sse42.cpp',
'skia/src/opts/SkOpts_ssse3.cpp',
]
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_hsw.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_sse42.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += skia_opt_flags
elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['CC_TYPE'] in ('clang', 'gcc'):
SOURCES += [
'skia/src/opts/SkBitmapProcState_arm_neon.cpp',
'skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp',
'skia/src/opts/SkBitmapProcState_opts_none.cpp',
'skia/src/opts/SkBlitMask_opts_arm.cpp',
'skia/src/opts/SkBlitMask_opts_arm_neon.cpp',
'skia/src/opts/SkBlitRow_opts_arm.cpp',
'skia/src/opts/SkBlitRow_opts_arm_neon.cpp',
]
SOURCES['skia/src/opts/SkBitmapProcState_arm_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBitmapProcState_opts_none.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitMask_opts_arm.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitMask_opts_arm_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitRow_opts_arm_neon.cpp'].flags += skia_opt_flags
elif CONFIG['CPU_ARCH'] == 'aarch64':
SOURCES += [
'skia/src/opts/SkBitmapProcState_arm_neon.cpp',
'skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp',
'skia/src/opts/SkBitmapProcState_opts_none.cpp',
'skia/src/opts/SkBlitMask_opts_arm.cpp',
'skia/src/opts/SkBlitMask_opts_arm_neon.cpp',
'skia/src/opts/SkBlitRow_opts_arm.cpp',
'skia/src/opts/SkBlitRow_opts_arm_neon.cpp',
'skia/src/opts/SkOpts_crc32.cpp',
]
SOURCES['skia/src/opts/SkBitmapProcState_arm_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBitmapProcState_opts_none.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitMask_opts_arm.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitMask_opts_arm_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkBlitRow_opts_arm_neon.cpp'].flags += skia_opt_flags
SOURCES['skia/src/opts/SkOpts_crc32.cpp'].flags += skia_opt_flags
else:
SOURCES += [
'skia/src/opts/SkBitmapProcState_opts_none.cpp',
'skia/src/opts/SkBlitMask_opts_none.cpp',
'skia/src/opts/SkBlitRow_opts_none.cpp',
]
# We allow warnings for third-party code that can be updated from upstream.
@ -500,9 +453,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
# We should autogenerate these SSE related flags.
if CONFIG['INTEL_ARCHITECTURE']:
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-mssse3']
SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
SOURCES['skia/src/opts/SkOpts_sse42.cpp'].flags += ['-msse4.2']

Просмотреть файл

@ -9,10 +9,13 @@
#define SkAndroidFrameworkUtils_DEFINED
#include "SkTypes.h"
#include "SkRefCnt.h"
#ifdef SK_BUILD_FOR_ANDROID
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
class SkCanvas;
struct SkRect;
class SkSurface;
/**
* SkAndroidFrameworkUtils expose private APIs used only by Android framework.
@ -31,8 +34,14 @@ public:
*/
static bool clipWithStencil(SkCanvas* canvas);
#endif //SK_SUPPORT_GPU
static void SafetyNetLog(const char*);
static sk_sp<SkSurface> getSurfaceFromCanvas(SkCanvas* canvas);
static int SaveBehind(SkCanvas* canvas, const SkRect* subset);
};
#endif // SK_BUILD_FOR_ANDROID
#endif // SK_BUILD_FOR_ANDROID_ANDROID
#endif // SkAndroidFrameworkUtils_DEFINED

Просмотреть файл

@ -22,6 +22,19 @@ class SkPicture;
*/
class SK_API SkAnimatedImage : public SkDrawable {
public:
/**
* Create an SkAnimatedImage from the SkAndroidCodec.
*
* Returns null on failure to allocate pixels. On success, this will
* decode the first frame.
*
* @param info Width and height may require scaling.
* @param cropRect Rectangle to crop to after scaling.
* @param postProcess Picture to apply after scaling and cropping.
*/
static sk_sp<SkAnimatedImage> Make(std::unique_ptr<SkAndroidCodec>,
const SkImageInfo& info, SkIRect cropRect, sk_sp<SkPicture> postProcess);
/**
* Create an SkAnimatedImage from the SkAndroidCodec.
*

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkAtlasTextFont_DEFINED
#define SkAtlasTextFont_DEFINED
#include "SkFont.h"
#include "SkRefCnt.h"
#include "SkTypeface.h"
@ -24,6 +25,8 @@ public:
SkScalar size() const { return fSize; }
SkFont makeFont() const { return SkFont(fTypeface, fSize); }
private:
SkAtlasTextFont(sk_sp<SkTypeface> typeface, SkScalar size)
: fTypeface(std::move(typeface)), fSize(size) {}

Просмотреть файл

@ -20,7 +20,7 @@
#include "SkSize.h"
#include "SkStream.h"
#include "SkTypes.h"
#include "SkYUVSizeInfo.h"
#include "SkYUVASizeInfo.h"
#include <vector>
@ -351,16 +351,28 @@ public:
* returns false and does not modify any of the parameters.
*
* @param sizeInfo Output parameter indicating the sizes and required
* allocation widths of the Y, U, and V planes.
* allocation widths of the Y, U, V, and A planes. Given current codec
* limitations the size of the A plane will always be 0 and the Y, U, V
* channels will always be planar.
* @param colorSpace Output parameter. If non-NULL this is set to kJPEG,
* otherwise this is ignored.
*/
bool queryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
bool queryYUV8(SkYUVASizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
if (nullptr == sizeInfo) {
return false;
}
return this->onQueryYUV8(sizeInfo, colorSpace);
bool result = this->onQueryYUV8(sizeInfo, colorSpace);
if (result) {
for (int i = 0; i <= 2; ++i) {
SkASSERT(sizeInfo->fSizes[i].fWidth > 0 && sizeInfo->fSizes[i].fHeight > 0 &&
sizeInfo->fWidthBytes[i] > 0);
}
SkASSERT(!sizeInfo->fSizes[3].fWidth &&
!sizeInfo->fSizes[3].fHeight &&
!sizeInfo->fWidthBytes[3]);
}
return result;
}
/**
@ -373,11 +385,11 @@ public:
* recommendation (but not smaller).
* @param planes Memory for each of the Y, U, and V planes.
*/
Result getYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) {
if (nullptr == planes || nullptr == planes[0] || nullptr == planes[1] ||
nullptr == planes[2]) {
Result getYUV8Planes(const SkYUVASizeInfo& sizeInfo, void* planes[SkYUVASizeInfo::kMaxCount]) {
if (!planes || !planes[0] || !planes[1] || !planes[2]) {
return kInvalidInput;
}
SkASSERT(!planes[3]); // TODO: is this a fair assumption?
if (!this->rewindIfNeeded()) {
return kCouldNotRewind;
@ -391,6 +403,9 @@ public:
*
* This may require a rewind.
*
* If kIncompleteInput is returned, may be called again after more data has
* been provided to the source SkStream.
*
* @param dstInfo Info of the destination. If the dimensions do not match
* those of getInfo, this implies a scale.
* @param dst Memory to write to. Needs to be large enough to hold the subset,
@ -409,10 +424,11 @@ public:
/**
* Start/continue the incremental decode.
*
* Not valid to call before calling startIncrementalDecode().
* Not valid to call before a call to startIncrementalDecode() returns
* kSuccess.
*
* After the first call, should only be called again if more data has been
* provided to the source SkStream.
* If kIncompleteInput is returned, may be called again after more data has
* been provided to the source SkStream.
*
* Unlike getPixels and getScanlines, this does not do any filling. This is
* left up to the caller, since they may be skipping lines or continuing the
@ -708,11 +724,12 @@ protected:
void* pixels, size_t rowBytes, const Options&,
int* rowsDecoded) = 0;
virtual bool onQueryYUV8(SkYUVSizeInfo*, SkYUVColorSpace*) const {
virtual bool onQueryYUV8(SkYUVASizeInfo*, SkYUVColorSpace*) const {
return false;
}
virtual Result onGetYUV8Planes(const SkYUVSizeInfo&, void*[3] /*planes*/) {
virtual Result onGetYUV8Planes(const SkYUVASizeInfo&,
void*[SkYUVASizeInfo::kMaxCount] /*planes*/) {
return kUnimplemented;
}
@ -772,6 +789,14 @@ protected:
virtual int onOutputScanline(int inputScanline) const;
/**
* Return whether we can convert to dst.
*
* Will be called for the appropriate frame, prior to initializing the colorXform.
*/
virtual bool conversionSupported(const SkImageInfo& dst, bool srcIsOpaque,
bool needsColorXform);
// Some classes never need a colorXform e.g.
// - ICO uses its embedded codec's colorXform
// - WBMP is just Black/White
@ -818,14 +843,6 @@ private:
bool fStartedIncrementalDecode;
/**
* Return whether we can convert to dst.
*
* Will be called for the appropriate frame, prior to initializing the colorXform.
*/
virtual bool conversionSupported(const SkImageInfo& dst, bool srcIsOpaque,
bool needsColorXform);
bool initializeColorXform(const SkImageInfo& dstInfo, SkEncodedInfo::Alpha, bool srcIsOpaque);
/**

Просмотреть файл

@ -39,5 +39,5 @@ namespace SkCodecAnimation {
*/
kRestorePrevious = 3,
};
};
}
#endif // SkCodecAnimation_DEFINED

Просмотреть файл

@ -7,6 +7,9 @@
#ifndef SkEncodedOrigin_DEFINED
#define SkEncodedOrigin_DEFINED
#include "SkMatrix.h"
// These values match the orientation www.exif.org/Exif2-2.PDF.
enum SkEncodedOrigin {
kTopLeft_SkEncodedOrigin = 1, // Default
@ -20,4 +23,26 @@ enum SkEncodedOrigin {
kDefault_SkEncodedOrigin = kTopLeft_SkEncodedOrigin,
kLast_SkEncodedOrigin = kLeftBottom_SkEncodedOrigin,
};
/**
* Given an encoded origin and the width and height of the source data, returns a matrix
* that transforms the source rectangle [0, 0, w, h] to a correctly oriented destination
* rectangle, with the upper left corner still at [0, 0].
*/
static inline SkMatrix SkEncodedOriginToMatrix(SkEncodedOrigin origin, int w, int h) {
switch (origin) {
case kTopLeft_SkEncodedOrigin: return SkMatrix::I();
case kTopRight_SkEncodedOrigin: return SkMatrix::MakeAll(-1, 0, w, 0, 1, 0, 0, 0, 1);
case kBottomRight_SkEncodedOrigin: return SkMatrix::MakeAll(-1, 0, w, 0, -1, h, 0, 0, 1);
case kBottomLeft_SkEncodedOrigin: return SkMatrix::MakeAll( 1, 0, 0, 0, -1, h, 0, 0, 1);
case kLeftTop_SkEncodedOrigin: return SkMatrix::MakeAll( 0, 1, 0, 1, 0, 0, 0, 0, 1);
case kRightTop_SkEncodedOrigin: return SkMatrix::MakeAll( 0, -1, h, 1, 0, 0, 0, 0, 1);
case kRightBottom_SkEncodedOrigin: return SkMatrix::MakeAll( 0, -1, h, -1, 0, w, 0, 0, 1);
case kLeftBottom_SkEncodedOrigin: return SkMatrix::MakeAll( 0, 1, 0, -1, 0, w, 0, 0, 1);
}
SK_ABORT("Unexpected origin");
return SkMatrix::I();
}
#endif // SkEncodedOrigin_DEFINED

Просмотреть файл

@ -135,15 +135,14 @@
#define SK_ALLOW_STATIC_GLOBAL_INITIALIZERS 0
// Don't use __stdcall with SkiaGLGlue - bug 1320644
#define GR_GL_FUNCTION_TYPE
#define SK_RASTERIZE_EVEN_ROUNDING
#define SK_DISABLE_SLOW_DEBUG_VALIDATION 1
#define SK_SUPPORT_DEPRECATED_CLIPOPS
#define SK_SUPPORT_GPU 0
#ifndef MOZ_IMPLICIT
# ifdef MOZ_CLANG_PLUGIN
# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit")))
@ -154,6 +153,4 @@
#define MOZ_SKIA
#define SK_SUPPORT_GPU 0
#endif

Просмотреть файл

@ -420,7 +420,7 @@ public:
- rowBytes is positive and less than imageInfo.width() times imageInfo.bytesPerPixel()
@param imageInfo contains width, height, SkAlphaType, SkColorType, SkColorSpace
@param rowBytes imageInfo.minRowBytes or larger; or zero
@param rowBytes imageInfo.minRowBytes() or larger; or zero
@return true if SkImageInfo set successfully
*/
bool setInfo(const SkImageInfo& imageInfo, size_t rowBytes = 0);
@ -473,9 +473,7 @@ public:
@param info contains width, height, SkAlphaType, SkColorType, SkColorSpace
@param flags kZeroPixels_AllocFlag, or zero
*/
void allocPixelsFlags(const SkImageInfo& info, uint32_t flags) {
SkASSERT_RELEASE(this->tryAllocPixelsFlags(info, flags));
}
void allocPixelsFlags(const SkImageInfo& info, uint32_t flags);
/** Sets SkImageInfo to info following the rules in setInfo() and allocates pixel
memory. rowBytes must equal or exceed info.width() times info.bytesPerPixel(),
@ -511,9 +509,7 @@ public:
@param info contains width, height, SkAlphaType, SkColorType, SkColorSpace
@param rowBytes size of pixel row or larger; may be zero
*/
void allocPixels(const SkImageInfo& info, size_t rowBytes) {
SkASSERT_RELEASE(this->tryAllocPixels(info, rowBytes));
}
void allocPixels(const SkImageInfo& info, size_t rowBytes);
/** Sets SkImageInfo to info following the rules in setInfo() and allocates pixel
memory.
@ -547,9 +543,7 @@ public:
@param info contains width, height, SkAlphaType, SkColorType, SkColorSpace
*/
void allocPixels(const SkImageInfo& info) {
this->allocPixels(info, info.minRowBytes());
}
void allocPixels(const SkImageInfo& info);
/** Sets SkImageInfo to width, height, and native color type; and allocates
pixel memory. If isOpaque is true, sets SkImageInfo to kOpaque_SkAlphaType;
@ -568,11 +562,7 @@ public:
@param isOpaque true if pixels do not have transparency
@return true if pixel storage is allocated
*/
bool SK_WARN_UNUSED_RESULT tryAllocN32Pixels(int width, int height, bool isOpaque = false) {
SkImageInfo info = SkImageInfo::MakeN32(width, height,
isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
return this->tryAllocPixels(info);
}
bool SK_WARN_UNUSED_RESULT tryAllocN32Pixels(int width, int height, bool isOpaque = false);
/** Sets SkImageInfo to width, height, and the native color type; and allocates
pixel memory. If isOpaque is true, sets SkImageInfo to kPremul_SkAlphaType;
@ -589,11 +579,7 @@ public:
@param height pixel row count; must be zero or greater
@param isOpaque true if pixels do not have transparency
*/
void allocN32Pixels(int width, int height, bool isOpaque = false) {
SkImageInfo info = SkImageInfo::MakeN32(width, height,
isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
this->allocPixels(info);
}
void allocN32Pixels(int width, int height, bool isOpaque = false);
/** Sets SkImageInfo to info following the rules in setInfo(), and creates SkPixelRef
containing pixels and rowBytes. releaseProc, if not nullptr, is called
@ -643,7 +629,7 @@ public:
SkPixelRef containing pixmap.addr() and pixmap.rowBytes().
If SkImageInfo could not be set, or pixmap.rowBytes() is less than
SkImageInfo::minRowBytes: calls reset(), and returns false.
SkImageInfo::minRowBytes(): calls reset(), and returns false.
Otherwise, if pixmap.addr() equals nullptr: sets SkImageInfo, returns true.
@ -654,14 +640,14 @@ public:
*/
bool installPixels(const SkPixmap& pixmap);
/** To be deprecated soon.
/** Deprecated.
*/
bool installMaskPixels(const SkMask& mask);
/** Replaces SkPixelRef with pixels, preserving SkImageInfo and rowBytes().
Sets SkPixelRef origin to (0, 0).
If pixels is nullptr, or if info().colorType equals kUnknown_SkColorType;
If pixels is nullptr, or if info().colorType() equals kUnknown_SkColorType;
release reference to SkPixelRef, and set SkPixelRef to nullptr.
Caller is responsible for handling ownership pixel memory for the lifetime
@ -674,7 +660,7 @@ public:
/** Allocates pixel memory with HeapAllocator, and replaces existing SkPixelRef.
The allocation size is determined by SkImageInfo width, height, and SkColorType.
Returns false if info().colorType is kUnknown_SkColorType, or allocation fails.
Returns false if info().colorType() is kUnknown_SkColorType, or allocation fails.
@return true if the allocation succeeds
*/
@ -685,13 +671,11 @@ public:
/** Allocates pixel memory with HeapAllocator, and replaces existing SkPixelRef.
The allocation size is determined by SkImageInfo width, height, and SkColorType.
Aborts if info().colorType is kUnknown_SkColorType, or allocation fails.
Aborts if info().colorType() is kUnknown_SkColorType, or allocation fails.
Abort steps may be provided by the user at compile
time by defining SK_ABORT.
*/
void allocPixels() {
this->allocPixels((Allocator*)nullptr);
}
void allocPixels();
/** Allocates pixel memory with allocator, and replaces existing SkPixelRef.
The allocation size is determined by SkImageInfo width, height, and SkColorType.
@ -713,9 +697,7 @@ public:
@param allocator instance of SkBitmap::Allocator instantiation
*/
void allocPixels(Allocator* allocator) {
SkASSERT_RELEASE(this->tryAllocPixels(allocator));
}
void allocPixels(Allocator* allocator);
/** Returns SkPixelRef, which contains: pixel base address; its dimensions; and
rowBytes(), the interval from one row to the next. Does not change SkPixelRef
@ -778,7 +760,7 @@ public:
void notifyPixelsChanged() const;
/** Replaces pixel values with c. All pixels contained by bounds() are affected.
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then alpha
If the colorType() is kGray_8_SkColorType or kRGB_565_SkColorType, then alpha
is ignored; RGB is treated as opaque. If colorType() is kAlpha_8_SkColorType,
then RGB is ignored.
@ -788,7 +770,7 @@ public:
/** Replaces pixel values with unpremultiplied color built from a, r, g, and b.
All pixels contained by bounds() are affected.
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then a
If the colorType() is kGray_8_SkColorType or kRGB_565_SkColorType, then a
is ignored; r, g, and b are treated as opaque. If colorType() is kAlpha_8_SkColorType,
then r, g, and b are ignored.
@ -804,7 +786,7 @@ public:
/** Replaces pixel values inside area with c. If area does not intersect bounds(),
call has no effect.
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then alpha
If the colorType() is kGray_8_SkColorType or kRGB_565_SkColorType, then alpha
is ignored; RGB is treated as opaque. If colorType() is kAlpha_8_SkColorType,
then RGB is ignored.
@ -934,7 +916,7 @@ public:
dstInfo specifies width, height, SkColorType, SkAlphaType, and SkColorSpace of
destination. dstRowBytes specifics the gap from one destination row to the next.
Returns true if pixels are copied. Returns false if:
- dstInfo.addr() equals nullptr
- dstInfo has no address
- dstRowBytes is less than dstInfo.minRowBytes()
- SkPixelRef is nullptr
@ -966,7 +948,7 @@ public:
and row bytes of destination. dst.rowBytes() specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if:
- dst pixel storage equals nullptr
- dst.rowBytes is less than SkImageInfo::minRowBytes
- dst.rowBytes is less than SkImageInfo::minRowBytes()
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
@ -994,7 +976,7 @@ public:
and row bytes of destination. dst.rowBytes() specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if:
- dst pixel storage equals nullptr
- dst.rowBytes is less than SkImageInfo::minRowBytes
- dst.rowBytes is less than SkImageInfo::minRowBytes()
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
@ -1018,7 +1000,7 @@ public:
and row bytes of source. src.rowBytes() specifics the gap from one source
row to the next. Returns true if pixels are copied. Returns false if:
- src pixel storage equals nullptr
- src.rowBytes is less than SkImageInfo::minRowBytes
- src.rowBytes is less than SkImageInfo::minRowBytes()
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
@ -1046,7 +1028,7 @@ public:
and row bytes of source. src.rowBytes() specifics the gap from one source
row to the next. Returns true if pixels are copied. Returns false if:
- src pixel storage equals nullptr
- src.rowBytes is less than SkImageInfo::minRowBytes
- src.rowBytes is less than SkImageInfo::minRowBytes()
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
@ -1063,28 +1045,6 @@ public:
return this->writePixels(src, 0, 0);
}
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** For use by Android framework only.
@return true if setHasHardwareMipMap() has been called with true
*/
bool hasHardwareMipMap() const {
return (fFlags & kHasHardwareMipMap_Flag) != 0;
}
/** For use by Android framework only.
@param hasHardwareMipMap sets state
*/
void setHasHardwareMipMap(bool hasHardwareMipMap) {
if (hasHardwareMipMap) {
fFlags |= kHasHardwareMipMap_Flag;
} else {
fFlags &= ~kHasHardwareMipMap_Flag;
}
}
#endif
/** Sets dst to alpha described by pixels. Returns false if dst cannot be written to
or dst pixels cannot be allocated.
@ -1188,13 +1148,6 @@ public:
private:
enum Flags {
kImageIsVolatile_Flag = 0x02,
#ifdef SK_BUILD_FOR_ANDROID
/* A hint for the renderer responsible for drawing this bitmap
* indicating that it should attempt to use mipmaps when this bitmap
* is drawn scaled down.
*/
kHasHardwareMipMap_Flag = 0x08,
#endif
};
sk_sp<SkPixelRef> fPixelRef;

Просмотреть файл

@ -58,16 +58,16 @@ enum class SkBlendMode {
/** Returns name of blendMode as null-terminated C string.
@param blendMode one of:
SkBlendMode::kClear, SkBlendMode::kSrc, SkBlendMode::kDst, SkBlendMode::kSrcOver,
SkBlendMode::kDstOver, SkBlendMode::kSrcIn, SkBlendMode::kDstIn,
SkBlendMode::kSrcOut, SkBlendMode::kDstOut, SkBlendMode::kSrcATop,
SkBlendMode::kDstATop, SkBlendMode::kXor, SkBlendMode::kPlus,
SkBlendMode::kModulate, SkBlendMode::kScreen, SkBlendMode::kOverlay,
SkBlendMode::kDarken, SkBlendMode::kLighten, SkBlendMode::kColorDodge,
SkBlendMode::kColorBurn, SkBlendMode::kHardLight, SkBlendMode::kSoftLight,
SkBlendMode::kDifference, SkBlendMode::kExclusion, SkBlendMode::kMultiply,
SkBlendMode::kHue, SkBlendMode::kSaturation, SkBlendMode::kColor,
SkBlendMode::kLuminosity
SkBlendMode::kClear, SkBlendMode::kSrc, SkBlendMode::kDst,
SkBlendMode::kSrcOver, SkBlendMode::kDstOver, SkBlendMode::kSrcIn,
SkBlendMode::kDstIn, SkBlendMode::kSrcOut, SkBlendMode::kDstOut,
SkBlendMode::kSrcATop, SkBlendMode::kDstATop, SkBlendMode::kXor,
SkBlendMode::kPlus, SkBlendMode::kModulate, SkBlendMode::kScreen,
SkBlendMode::kOverlay, SkBlendMode::kDarken, SkBlendMode::kLighten,
SkBlendMode::kColorDodge, SkBlendMode::kColorBurn, SkBlendMode::kHardLight,
SkBlendMode::kSoftLight, SkBlendMode::kDifference, SkBlendMode::kExclusion,
SkBlendMode::kMultiply, SkBlendMode::kHue, SkBlendMode::kSaturation,
SkBlendMode::kColor, SkBlendMode::kLuminosity
@return C string
*/
SK_API const char* SkBlendMode_Name(SkBlendMode blendMode);

Просмотреть файл

@ -10,7 +10,7 @@
#include "SkTypes.h"
enum SkBlurStyle {
enum SkBlurStyle : int {
kNormal_SkBlurStyle, //!< fuzzy inside and outside
kSolid_SkBlurStyle, //!< solid inside, fuzzy outside
kOuter_SkBlurStyle, //!< nothing inside, fuzzy outside

Просмотреть файл

@ -22,6 +22,7 @@
#include "SkBlendMode.h"
#include "SkClipOp.h"
#include "SkDeque.h"
#include "SkFontTypes.h"
#include "SkPaint.h"
#include "SkRasterHandleAllocator.h"
#include "SkSurfaceProps.h"
@ -36,10 +37,10 @@ class SkData;
class SkDraw;
class SkDrawable;
struct SkDrawShadowRec;
class SkFont;
class SkGlyphRunBuilder;
class SkImage;
class SkImageFilter;
class SkMetaData;
class SkPath;
class SkPicture;
class SkPixmap;
@ -65,7 +66,7 @@ class SkTextBlob;
SkCanvas generated by raster surface draws to memory visible to the CPU.
SkCanvas generated by GPU surface uses Vulkan or OpenGL to draw to the GPU.
To draw to a document, obtain SkCanvas from svg canvas, document pdf, or SkPictureRecorder.
To draw to a document, obtain SkCanvas from SVG canvas, document PDF, or SkPictureRecorder.
SkDocument based SkCanvas and other SkCanvas subclasses reference SkBaseDevice describing the
destination.
@ -162,7 +163,7 @@ public:
*/
SkCanvas(int width, int height, const SkSurfaceProps* props = nullptr);
/** To be deprecated soon.
/** Private. For internal use only.
*/
explicit SkCanvas(sk_sp<SkBaseDevice> device);
@ -181,11 +182,13 @@ public:
explicit SkCanvas(const SkBitmap& bitmap);
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** Private.
*/
enum class ColorBehavior {
kLegacy, //!< placeholder
};
/** For use by Android framework only.
/** Private. For use by Android framework only.
@param bitmap specifies a bitmap for the canvas to draw into
@param behavior specializes this constructor; value is unused
@ -213,13 +216,6 @@ public:
*/
virtual ~SkCanvas();
/** Returns storage to associate additional data with the canvas.
The storage is freed when SkCanvas is deleted.
@return storage that can be read from and written to
*/
SkMetaData& getMetaData();
/** Returns SkImageInfo for SkCanvas. If SkCanvas is not associated with raster surface or
GPU surface, returned SkColorType is set to kUnknown_SkColorType.
@ -482,8 +478,8 @@ public:
- bitmap pixels are inaccessible; for instance, bitmap wraps a texture.
@param bitmap contains pixels copied to SkCanvas
@param x offset into SkCanvas writable pixels in x; may be negative
@param y offset into SkCanvas writable pixels in y; may be negative
@param x offset into SkCanvas writable pixels on x-axis; may be negative
@param y offset into SkCanvas writable pixels on y-axis; may be negative
@return true if pixels were written to SkCanvas
*/
bool writePixels(const SkBitmap& bitmap, int x, int y);
@ -548,33 +544,6 @@ public:
return this->saveLayer(&bounds, paint);
}
/** Saves SkMatrix and clip, and allocates a SkBitmap for subsequent drawing.
LCD text is preserved when the layer is drawn to the prior layer.
Calling restore() discards changes to SkMatrix and clip, and draws layer.
SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
clipPath(), clipRegion().
SkRect bounds suggests but does not define the layer size. To clip drawing to
a specific rectangle, use clipRect().
Optional SkPaint paint applies alpha, SkColorFilter, SkImageFilter, and
SkBlendMode when restore() is called.
Call restoreToCount() with returned value to restore this and subsequent saves.
Draw text on an opaque background so that LCD text blends correctly with the
prior layer. LCD text drawn on a background with transparency may result in
incorrect blending.
@param bounds hint to limit the size of layer; may be nullptr
@param paint graphics state for layer; may be nullptr
@return depth of saved stack
*/
int saveLayerPreserveLCDTextRequests(const SkRect* bounds, const SkPaint* paint);
/** Saves SkMatrix and clip, and allocates SkBitmap for subsequent drawing.
Calling restore() discards changes to SkMatrix and clip,
@ -603,14 +572,14 @@ public:
kPreserveLCDText_SaveLayerFlag, kInitWithPrevious_SaveLayerFlag, or both flags.
*/
enum SaveLayerFlagsSet {
kPreserveLCDText_SaveLayerFlag = 1 << 1, //!< creates layer for LCD text
kPreserveLCDText_SaveLayerFlag = 1 << 1,
kInitWithPrevious_SaveLayerFlag = 1 << 2, //!< initializes with previous contents
kMaskAgainstCoverage_EXPERIMENTAL_DONT_USE_SaveLayerFlag =
1 << 3, //!< experimental: do not use
#ifdef SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG
kDontClipToLayer_Legacy_SaveLayerFlag =
kDontClipToLayer_PrivateSaveLayerFlag, //!< to be deprecated soon
kDontClipToLayer_PrivateSaveLayerFlag, //!< deprecated
#endif
};
@ -632,7 +601,7 @@ public:
@param bounds layer dimensions; may be nullptr
@param paint applied to layer when overlaying prior layer; may be nullptr
@param saveLayerFlags SaveLayerRec options to modify layer
@return SaveLayerRec with empty backdrop
@return SaveLayerRec with empty fBackdrop
*/
SaveLayerRec(const SkRect* bounds, const SkPaint* paint, SaveLayerFlags saveLayerFlags = 0)
: fBounds(bounds)
@ -645,7 +614,10 @@ public:
@param bounds layer dimensions; may be nullptr
@param paint applied to layer when overlaying prior layer;
may be nullptr
@param backdrop prior layer copied with SkImageFilter; may be nullptr
@param backdrop If not null, this causes the current layer to be filtered by
backdrop, and then drawn into the new layer
(respecting the current clip).
If null, the new layer is initialized with transparent-black.
@param saveLayerFlags SaveLayerRec options to modify layer
@return SaveLayerRec fully specified
*/
@ -667,8 +639,10 @@ public:
@param bounds layer dimensions; may be nullptr
@param paint graphics state applied to layer when overlaying prior
layer; may be nullptr
@param backdrop prior layer copied with SkImageFilter;
may be nullptr
@param backdrop If not null, this causes the current layer to be filtered by
backdrop, and then drawn into the new layer
(respecting the current clip).
If null, the new layer is initialized with transparent-black.
@param clipMask clip applied to layer; may be nullptr
@param clipMatrix matrix applied to clipMask; may be nullptr to use
identity matrix
@ -692,7 +666,12 @@ public:
/** modifies overlay */
const SkPaint* fPaint = nullptr;
/** applies SkImageFilter to prior layer */
/**
* If not null, this triggers the same initialization behavior as setting
* kInitWithPrevious_SaveLayerFlag on fSaveLayerFlags: the current layer is copied into
* the new layer, rather than initializing the new layer with transparent-black.
* This is then filtered by fBackdrop (respecting the current clip).
*/
const SkImageFilter* fBackdrop = nullptr;
/** clips layer with mask alpha */
@ -719,7 +698,7 @@ public:
Call restoreToCount() with returned value to restore this and subsequent saves.
@param layerRec layer state
@return depth of save state stack
@return depth of save state stack before this call was made.
*/
int saveLayer(const SaveLayerRec& layerRec);
@ -756,8 +735,8 @@ public:
This has the effect of moving the drawing by (dx, dy) before transforming
the result with SkMatrix.
@param dx distance to translate in x
@param dy distance to translate in y
@param dx distance to translate on x-axis
@param dy distance to translate on y-axis
*/
void translate(SkScalar dx, SkScalar dy);
@ -769,8 +748,8 @@ public:
This has the effect of scaling the drawing by (sx, sy) before transforming
the result with SkMatrix.
@param sx amount to scale in x
@param sy amount to scale in y
@param sx amount to scale on x-axis
@param sy amount to scale on y-axis
*/
void scale(SkScalar sx, SkScalar sy);
@ -1328,12 +1307,8 @@ public:
/** Draws SkImage image, with its top-left corner at (left, top),
using clip, SkMatrix, and optional SkPaint paint.
If paint is supplied, apply SkColorFilter, alpha, SkImageFilter, SkBlendMode,
and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
If paint contains SkMaskFilter, generate mask from image bounds. If generated
mask extends beyond image bounds, replicate image edge colors, just as SkShader
made from SkImage::makeShader with SkShader::kClamp_TileMode set replicates the
image edge color when it samples outside of its bounds.
This is equivalent to drawImageRect() using a dst rect at (x,y) with the
same width and height of the image.
@param image uncompressed rectangular map of pixels
@param left left side of image
@ -1347,12 +1322,8 @@ public:
/** Draws SkImage image, with its top-left corner at (left, top),
using clip, SkMatrix, and optional SkPaint paint.
If SkPaint paint is supplied, apply SkColorFilter, alpha, SkImageFilter,
SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
If paint contains SkMaskFilter, generate mask from image bounds. If generated
mask extends beyond image bounds, replicate image edge colors, just as SkShader
made from SkImage::makeShader with SkShader::kClamp_TileMode set replicates the
image edge color when it samples outside of its bounds.
This is equivalent to drawImageRect() using a dst rect at (x,y) with the
same width and height of the image.
@param image uncompressed rectangular map of pixels
@param left left side of image
@ -1369,8 +1340,8 @@ public:
SrcRectConstraint controls the behavior at the edge of source SkRect,
provided to drawImageRect(), trading off speed for precision.
SkImageFilter in SkPaint may sample multiple pixels in the image. Source SkRect
restricts the bounds of pixels that may be read. SkImageFilter may slow down if
SkFilterQuality in SkPaint may sample multiple pixels in the image. Source SkRect
restricts the bounds of pixels that may be read. SkFilterQuality may slow down if
it cannot read outside the bounds, when sampling near the edge of source SkRect.
SrcRectConstraint specifies whether an SkImageFilter is allowed to read pixels
outside source SkRect.
@ -1391,6 +1362,10 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst). The src rect is only used to access the provided image.
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within src; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
@ -1419,6 +1394,10 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst). The src rect is only used to access the provided image.
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within isrc; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
@ -1445,18 +1424,16 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within image; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst).
@param image SkImage containing pixels, dimensions, and format
@param dst destination SkRect of image to draw to
@param paint SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
and so on; or nullptr
@param constraint filter strictly within image or draw faster
*/
void drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint,
SrcRectConstraint constraint = kStrict_SrcRectConstraint);
void drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint);
/** Draws SkRect src of SkImage image, scaled and translated to fill SkRect dst.
Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
@ -1469,9 +1446,9 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within src; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst). The src rect is only used to access the provided image.
@param image SkImage containing pixels, dimensions, and format
@param src source SkRect of image to draw from
@ -1498,6 +1475,10 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst). The src rect is only used to access the provided image.
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within image; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
@ -1526,6 +1507,10 @@ public:
as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
replicates the image edge color when it samples outside of its bounds.
When using a shader or shader mask filter, its coordinate system is based on the
current CTM, so will reflect the dst rect geometry and is equivalent to
drawRect(dst).
constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
sample within image; set to kFast_SrcRectConstraint allows sampling outside to
improve performance.
@ -1534,11 +1519,9 @@ public:
@param dst destination SkRect of image to draw to
@param paint SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
and so on; or nullptr
@param constraint filter strictly within image or draw faster
*/
void drawImageRect(const sk_sp<SkImage>& image, const SkRect& dst, const SkPaint* paint,
SrcRectConstraint constraint = kStrict_SrcRectConstraint) {
this->drawImageRect(image.get(), dst, paint, constraint);
void drawImageRect(const sk_sp<SkImage>& image, const SkRect& dst, const SkPaint* paint) {
this->drawImageRect(image.get(), dst, paint);
}
/** Draws SkImage image stretched proportionally to fit into SkRect dst.
@ -1820,151 +1803,140 @@ public:
void drawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
const SkPaint* paint = nullptr);
/** Draws text, with origin at (x, y), using clip, SkMatrix, and SkPaint paint.
/**
* Experimental. Controls anti-aliasing of each edge of images in an image-set.
*/
enum QuadAAFlags : unsigned {
kLeft_QuadAAFlag = 0b0001,
kTop_QuadAAFlag = 0b0010,
kRight_QuadAAFlag = 0b0100,
kBottom_QuadAAFlag = 0b1000,
text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
UTF-8.
kNone_QuadAAFlags = 0b0000,
kAll_QuadAAFlags = 0b1111,
};
x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
text draws left to right, positioning the first glyph left side bearing at x
and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
/** This is used by the experimental API below. */
struct ImageSetEntry {
sk_sp<const SkImage> fImage;
SkRect fSrcRect;
SkRect fDstRect;
float fAlpha;
unsigned fAAFlags; // QuadAAFlags
};
/**
* This is an experimental API for the SkiaRenderer Chromium project. The signature will
* surely evolve if this is not removed. It currently offers no performance advantage over
* drawing images independently, though may in the future. The antialiasing flags are intended
* to allow control over each edge's AA status, to allow perfect seaming for tile sets. The
* current implementation only antialiases if all edges are flagged, however.
* Results are undefined if an image's src rect is not within the image's bounds.
*/
void experimental_DrawImageSetV1(const ImageSetEntry imageSet[], int cnt,
SkFilterQuality quality, SkBlendMode mode);
/**
* This is an experimental API for the SkiaRenderer Chromium project. The signature will
* surely evolve if this is not removed. The antialiasing flags are intended to allow control
* over each edge's AA status, to allow perfect seaming for tile sets.
*
* When not fully supported, the implementation only antialiases if all edges are flagged.
*/
void experimental_DrawEdgeAARectV1(const SkRect& r, QuadAAFlags edgeAA, SkColor color,
SkBlendMode mode);
/** Draws text, with origin at (x, y), using clip, SkMatrix, SkFont font,
and SkPaint paint.
When encoding is SkTextEncoding::kUTF8, SkTextEncoding::kUTF16, or
SkTextEncoding::kUTF32, this function uses the default
character-to-glyph mapping from the SkTypeface in font. It does not
perform typeface fallback for characters not found in the SkTypeface.
It does not perform kerning or other complex shaping; glyphs are
positioned based on their default advances.
Text meaning depends on SkTextEncoding.
Text size is affected by SkMatrix and SkFont text size. Default text
size is 12 point.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By
default, draws filled black glyphs.
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param encoding text encoding used in the text array
@param x start of text on x-axis
@param y start of text on y-axis
@param paint text size, blend, color, and so on, used to draw
@param font typeface, text size and so, used to describe the text
@param paint blend, color, and so on, used to draw
*/
void drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
const SkPaint& paint);
void drawSimpleText(const void* text, size_t byteLength, SkTextEncoding encoding,
SkScalar x, SkScalar y, const SkFont& font, const SkPaint& paint);
/** Draws null terminated string, with origin at (x, y), using clip, SkMatrix, and
SkPaint paint.
/** Experimental.
string meaning depends on SkPaint::TextEncoding; by default, strings are encoded
as UTF-8. Other values of SkPaint::TextEncoding are unlikely to produce the desired
results, since zero bytes may be embedded in the string.
Draws null terminated string, with origin at (x, y), using clip, SkMatrix,
SkFont font, and SkPaint paint.
x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
string draws left to right, positioning the first glyph left side bearing at x
and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
This function uses the default character-to-glyph mapping from the
SkTypeface in font. It does not perform typeface fallback for
characters not found in the SkTypeface. It does not perform kerning;
glyphs are positioned based on their default advances.
String str is encoded as UTF-8.
Text size is affected by SkMatrix and font text size. Default text
size is 12 point.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By
default, draws filled black glyphs.
@param string character code points or glyphs drawn,
@param str character code points drawn,
ending with a char value of zero
@param x start of string on x-axis
@param y start of string on y-axis
@param paint text size, blend, color, and so on, used to draw
@param font typeface, text size and so, used to describe the text
@param paint blend, color, and so on, used to draw
*/
void drawString(const char* string, SkScalar x, SkScalar y, const SkPaint& paint) {
if (!string) {
return;
}
this->drawText(string, strlen(string), x, y, paint);
void drawString(const char str[], SkScalar x, SkScalar y, const SkFont& font,
const SkPaint& paint) {
this->drawSimpleText(str, strlen(str), kUTF8_SkTextEncoding, x, y, font, paint);
}
/** Draws null terminated string, with origin at (x, y), using clip, SkMatrix, and
SkPaint paint.
/** Experimental.
string meaning depends on SkPaint::TextEncoding; by default, strings are encoded
as UTF-8. Other values of SkPaint::TextEncoding are unlikely to produce the desired
results, since zero bytes may be embedded in the string.
Draws SkString, with origin at (x, y), using clip, SkMatrix, SkFont font,
and SkPaint paint.
x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
string draws left to right, positioning the first glyph left side bearing at x
and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
This function uses the default character-to-glyph mapping from the
SkTypeface in font. It does not perform typeface fallback for
characters not found in the SkTypeface. It does not perform kerning;
glyphs are positioned based on their default advances.
SkString str is encoded as UTF-8.
Text size is affected by SkMatrix and SkFont text size. Default text
size is 12 point.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By
default, draws filled black glyphs.
@param string character code points or glyphs drawn,
@param str character code points drawn,
ending with a char value of zero
@param x start of string on x-axis
@param y start of string on y-axis
@param paint text size, blend, color, and so on, used to draw
@param font typeface, text size and so, used to describe the text
@param paint blend, color, and so on, used to draw
*/
void drawString(const SkString& string, SkScalar x, SkScalar y, const SkPaint& paint);
/** Draws each glyph in text with the origin in pos array, using clip, SkMatrix, and
SkPaint paint. The number of entries in pos array must match the number of glyphs
described by byteLength of text.
text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
UTF-8. pos elements meaning depends on SkPaint vertical text; by default
glyph left side bearing and baseline are relative to SkPoint in pos array.
Text size is affected by SkMatrix and SkPaint text size.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
Layout engines such as Harfbuzz typically position each glyph
rather than using the font advance widths.
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param pos array of glyph origins
@param paint text size, blend, color, and so on, used to draw
*/
void drawPosText(const void* text, size_t byteLength, const SkPoint pos[],
const SkPaint& paint);
/** Draws each glyph in text with its (x, y) origin composed from xpos array and
constY, using clip, SkMatrix, and SkPaint paint. The number of entries in xpos array
must match the number of glyphs described by byteLength of text.
text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
UTF-8. xpos elements meaning depends on SkPaint vertical text;
by default each glyph left side bearing is positioned at an xpos element and
its baseline is positioned at constY. Text size is affected by SkMatrix and
SkPaint text size.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
Layout engines such as Harfbuzz typically position each glyph
rather than using the font advance widths if all glyphs share the same
baseline.
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param xpos array of x-axis positions, used to position each glyph
@param constY shared y-axis value for all of x-axis positions
@param paint text size, blend, color, and so on, used to draw
*/
void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY,
const SkPaint& paint);
/** Draws text, transforming each glyph by the corresponding SkRSXform,
using clip, SkMatrix, and SkPaint paint.
SkRSXform xform array specifies a separate square scale, rotation, and translation
for each glyph. xform does not affect paint SkShader.
Optional SkRect cullRect is a conservative bounds of text, taking into account
SkRSXform and paint. If cullRect is outside of clip, canvas can skip drawing.
All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
filled 12 point black glyphs.
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param xform SkRSXform rotates, scales, and translates each glyph individually
@param cullRect SkRect bounds of text for efficient clipping; or nullptr
@param paint text size, blend, color, and so on, used to draw
*/
void drawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
const SkRect* cullRect, const SkPaint& paint);
void drawString(const SkString& str, SkScalar x, SkScalar y, const SkFont& font,
const SkPaint& paint) {
this->drawSimpleText(str.c_str(), str.size(), kUTF8_SkTextEncoding, x, y, font, paint);
}
/** Draws SkTextBlob blob at (x, y), using clip, SkMatrix, and SkPaint paint.
@ -1974,7 +1946,7 @@ public:
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
SkPaint::TextEncoding must be set to SkPaint::kGlyphID_TextEncoding.
SkTextEncoding must be set to kGlyphID_SkTextEncoding.
Elements of paint: anti-alias, SkBlendMode, color including alpha,
SkColorFilter, SkPaint dither, SkDrawLooper, SkMaskFilter, SkPathEffect, SkShader, and
@ -1997,7 +1969,7 @@ public:
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
SkPaint::TextEncoding must be set to SkPaint::kGlyphID_TextEncoding.
SkTextEncoding must be set to kGlyphID_SkTextEncoding.
Elements of paint: SkPathEffect, SkMaskFilter, SkShader, SkColorFilter,
SkImageFilter, and SkDrawLooper; apply to blob.
@ -2296,10 +2268,10 @@ public:
void drawDrawable(SkDrawable* drawable, SkScalar x, SkScalar y);
/** Associates SkRect on SkCanvas with an annotation; a key-value pair, where the key is
a null-terminated utf8 string, and optional value is stored as SkData.
a null-terminated UTF-8 string, and optional value is stored as SkData.
Only some canvas implementations, such as recording to SkPicture, or drawing to
document pdf, use annotations.
document PDF, use annotations.
@param rect SkRect extent of canvas to annotate
@param key string used for lookup
@ -2308,10 +2280,10 @@ public:
void drawAnnotation(const SkRect& rect, const char key[], SkData* value);
/** Associates SkRect on SkCanvas when an annotation; a key-value pair, where the key is
a null-terminated utf8 string, and optional value is stored as SkData.
a null-terminated UTF-8 string, and optional value is stored as SkData.
Only some canvas implementations, such as recording to SkPicture, or drawing to
document pdf, use annotations.
document PDF, use annotations.
@param rect SkRect extent of canvas to annotate
@param key string used for lookup
@ -2392,6 +2364,8 @@ protected:
virtual SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& ) {
return kFullLayer_SaveLayerStrategy;
}
// returns true if we should actually perform the saveBehind, or false if we should just save.
virtual bool onDoSaveBehind(const SkRect*) { return true; }
virtual void willRestore() {}
virtual void didRestore() {}
virtual void didConcat(const SkMatrix& ) {}
@ -2405,6 +2379,8 @@ protected:
// that mechanism will be required to implement the new function.
virtual void onDrawPaint(const SkPaint& paint);
virtual void onDrawRect(const SkRect& rect, const SkPaint& paint);
virtual void onDrawEdgeAARect(const SkRect& rect, QuadAAFlags edgeAA, SkColor color,
SkBlendMode mode);
virtual void onDrawRRect(const SkRRect& rrect, const SkPaint& paint);
virtual void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint);
virtual void onDrawOval(const SkRect& rect, const SkPaint& paint);
@ -2413,15 +2389,6 @@ protected:
virtual void onDrawPath(const SkPath& path, const SkPaint& paint);
virtual void onDrawRegion(const SkRegion& region, const SkPaint& paint);
virtual void onDrawText(const void* text, size_t byteLength, SkScalar x,
SkScalar y, const SkPaint& paint);
virtual void onDrawPosText(const void* text, size_t byteLength,
const SkPoint pos[], const SkPaint& paint);
virtual void onDrawPosTextH(const void* text, size_t byteLength,
const SkScalar xpos[], SkScalar constY,
const SkPaint& paint);
virtual void onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
const SkRect* cullRect, const SkPaint& paint);
virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint);
@ -2446,6 +2413,9 @@ protected:
virtual void onDrawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
const SkPaint* paint);
virtual void onDrawImageSet(const ImageSetEntry imageSet[], int count, SkFilterQuality,
SkBlendMode);
virtual void onDrawBitmap(const SkBitmap& bitmap, SkScalar dx, SkScalar dy,
const SkPaint* paint);
virtual void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
@ -2567,7 +2537,6 @@ private:
int fSaveCount; // value returned by getSaveCount()
SkMetaData* fMetaData;
std::unique_ptr<SkRasterHandleAllocator> fAllocator;
SkSurface_Base* fSurfaceBase;
@ -2594,7 +2563,7 @@ private:
friend class SkPictureRecord; // predrawNotify (why does it need it? <reed>)
friend class SkOverdrawCanvas;
friend class SkRasterHandleAllocator;
friend class ClipTileRenderer; // GM needs getTopDevice() until API is in SkCanvas
protected:
// For use by SkNoDrawCanvas (via SkCanvasVirtualEnforcer, which can't be a friend)
SkCanvas(const SkIRect& bounds);
@ -2607,6 +2576,16 @@ private:
SkCanvas& operator=(SkCanvas&&) = delete;
SkCanvas& operator=(const SkCanvas&) = delete;
/** Experimental
* Saves the specified subset of the current pixels in the current layer,
* and then clears those pixels to transparent black.
* Restores the pixels on restore() by drawing them in SkBlendMode::kDstOver.
*
* @param subset conservative bounds of the area to be saved / restored.
* @return depth of save state stack before this call was made.
*/
int only_axis_aligned_saveBehind(const SkRect* subset);
void resetForNextPicture(const SkIRect& bounds);
// needs gettotalclip()
@ -2630,6 +2609,7 @@ private:
SrcRectConstraint);
void internalDrawPaint(const SkPaint& paint);
void internalSaveLayer(const SaveLayerRec&, SaveLayerStrategy);
void internalSaveBehind(const SkRect*);
void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*, SkImage* clipImage,
const SkMatrix& clipMatrix);
@ -2700,7 +2680,7 @@ private:
class SkAutoCanvasRestore {
public:
/** Preserves SkCanvas save count. Optionally saves SkCanvas clip and SkCanvas matrix.
/** Preserves SkCanvas::save() count. Optionally saves SkCanvas clip and SkCanvas matrix.
@param canvas SkCanvas to guard
@param doSave call SkCanvas::save()
@ -2725,7 +2705,7 @@ public:
}
/** Restores SkCanvas to saved state immediately. Subsequent calls and
~SkAutoCanvasRestore have no effect.
~SkAutoCanvasRestore() have no effect.
*/
void restore() {
if (fCanvas) {
@ -2743,6 +2723,8 @@ private:
SkAutoCanvasRestore& operator=(SkAutoCanvasRestore&&) = delete;
SkAutoCanvasRestore& operator=(const SkAutoCanvasRestore&) = delete;
};
// Private
#define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
#endif

Просмотреть файл

@ -30,14 +30,6 @@ protected:
void onDrawPath(const SkPath& path, const SkPaint& paint) override = 0;
void onDrawRegion(const SkRegion& region, const SkPaint& paint) override = 0;
void onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
const SkPaint& paint) override = 0;
void onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
const SkPaint& paint) override = 0;
void onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
SkScalar constY, const SkPaint& paint) override = 0;
void onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
const SkRect* cullRect, const SkPaint& paint) override = 0;
void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint) override = 0;
@ -58,6 +50,20 @@ protected:
void onDrawImageLattice(const SkImage* image, const SkCanvas::Lattice& lattice,
const SkRect& dst, const SkPaint* paint) override = 0;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
// This is under active development for Chrome and not used in Android. Hold off on adding
// implementations in Android's SkCanvas subclasses until this stabilizes.
void onDrawImageSet(const SkCanvas::ImageSetEntry[], int count, SkFilterQuality,
SkBlendMode) override {};
void onDrawEdgeAARect(const SkRect& rect, SkCanvas::QuadAAFlags edgeAA, SkColor color,
SkBlendMode mode) override {};
#else
void onDrawImageSet(const SkCanvas::ImageSetEntry[], int count, SkFilterQuality,
SkBlendMode) override = 0;
void onDrawEdgeAARect(const SkRect& rect, SkCanvas::QuadAAFlags edgeAA, SkColor color,
SkBlendMode mode) override = 0;
#endif
void onDrawBitmap(const SkBitmap& bitmap, SkScalar dx, SkScalar dy,
const SkPaint* paint) override = 0;
void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,

Просмотреть файл

@ -228,59 +228,142 @@ SK_API SkPMColor SkPreMultiplyARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
*/
SK_API SkPMColor SkPreMultiplyColor(SkColor c);
/** \struct SkRGBA4f
RGBA color value, holding four floating point components. Color components are always in
a known order. kAT determines if the SkRGBA4f's R, G, and B components are premultiplied
by alpha or not.
Skia's public API always uses unpremultiplied colors, which can be stored as
SkRGBA4f<kUnpremul_SkAlphaType>. For convenience, this type can also be referred to
as SkColor4f.
*/
template <SkAlphaType kAT>
struct SkRGBA4f {
float fR;
float fG;
float fB;
float fA;
float fR; //!< red component
float fG; //!< green component
float fB; //!< blue component
float fA; //!< alpha component
/** Compares SkRGBA4f with other, and returns true if all components are equal.
@param other SkRGBA4f to compare
@return true if SkRGBA4f equals other
*/
bool operator==(const SkRGBA4f& other) const {
return fA == other.fA && fR == other.fR && fG == other.fG && fB == other.fB;
}
/** Compares SkRGBA4f with other, and returns true if not all components are equal.
@param other SkRGBA4f to compare
@return true if SkRGBA4f is not equal to other
*/
bool operator!=(const SkRGBA4f& other) const {
return !(*this == other);
}
/** Returns SkRGBA4f multiplied by scale.
@param scale value to multiply by
@return SkRGBA4f as (fR * scale, fG * scale, fB * scale, fA * scale)
*/
SkRGBA4f operator*(float scale) const {
return { fR * scale, fG * scale, fB * scale, fA * scale };
}
/** Returns SkRGBA4f multiplied component-wise by scale.
@param scale SkRGBA4f to multiply by
@return SkRGBA4f as (fR * scale.fR, fG * scale.fG, fB * scale.fB, fA * scale.fA)
*/
SkRGBA4f operator*(const SkRGBA4f& scale) const {
return { fR * scale.fR, fG * scale.fG, fB * scale.fB, fA * scale.fA };
}
const float* vec() const { return &fR; }
float* vec() { return &fR; }
/** Returns a pointer to components of SkRGBA4f, for array access.
@return pointer to array [fR, fG, fB, fA]
*/
const float* vec() const { return &fR; }
/** Returns a pointer to components of SkRGBA4f, for array access.
@return pointer to array [fR, fG, fB, fA]
*/
float* vec() { return &fR; }
/** Returns one component. Asserts if index is out of range and SK_DEBUG is defined.
@param index one of: 0 (fR), 1 (fG), 2 (fB), 3 (fA)
@return value corresponding to index
*/
float operator[](int index) const {
SkASSERT(index >= 0 && index < 4);
return this->vec()[index];
}
/** Returns one component. Asserts if index is out of range and SK_DEBUG is defined.
@param index one of: 0 (fR), 1 (fG), 2 (fB), 3 (fA)
@return value corresponding to index
*/
float& operator[](int index) {
SkASSERT(index >= 0 && index < 4);
return this->vec()[index];
}
/** Returns true if SkRGBA4f is an opaque color. Asserts if fA is out of range and
SK_DEBUG is defined.
@return true if SkRGBA4f is opaque
*/
bool isOpaque() const {
SkASSERT(fA <= 1.0f && fA >= 0.0f);
return fA == 1.0f;
}
static SkRGBA4f Pin(float r, float g, float b, float a); // impl. depends on kAT
SkRGBA4f pin() const { return Pin(fR, fG, fB, fA); }
/** Returns true if all channels are in [0, 1]. */
bool fitsInBytes() const {
SkASSERT(fA >= 0.0f && fA <= 1.0f);
return fR >= 0.0f && fR <= 1.0f &&
fG >= 0.0f && fG <= 1.0f &&
fB >= 0.0f && fB <= 1.0f;
}
static SkRGBA4f FromColor(SkColor); // impl. depends on kAT
/** Returns closest SkRGBA4f to SkColor. Only allowed if SkRGBA4f is unpremultiplied.
@param color Color with Alpha, red, blue, and green components
@return SkColor as SkRGBA4f
*/
static SkRGBA4f FromColor(SkColor color); // impl. depends on kAT
/** Returns closest SkColor to SkRGBA4f. Only allowed if SkRGBA4f is unpremultiplied.
@return color as SkColor
*/
SkColor toSkColor() const; // impl. depends on kAT
/** Returns closest SkRGBA4f to SkPMColor. Only allowed if SkRGBA4f is premultiplied.
@return SkPMColor as SkRGBA4f
*/
static SkRGBA4f FromPMColor(SkPMColor); // impl. depends on kAT
/** Returns SkRGBA4f premultiplied by alpha. Asserts at compile time if SkRGBA4f is
already premultiplied.
@return premultiplied color
*/
SkRGBA4f<kPremul_SkAlphaType> premul() const {
static_assert(kAT == kUnpremul_SkAlphaType, "");
return { fR * fA, fG * fA, fB * fA, fA };
}
/** Returns SkRGBA4f unpremultiplied by alpha. Asserts at compile time if SkRGBA4f is
already unpremultiplied.
@return unpremultiplied color
*/
SkRGBA4f<kUnpremul_SkAlphaType> unpremul() const {
static_assert(kAT == kPremul_SkAlphaType, "");
@ -291,9 +374,24 @@ struct SkRGBA4f {
return { fR * invAlpha, fG * invAlpha, fB * invAlpha, fA };
}
}
// This produces bytes in RGBA order (eg GrColor). Impl. is the same, regardless of kAT
uint32_t toBytes_RGBA() const;
static SkRGBA4f FromBytes_RGBA(uint32_t color);
SkRGBA4f makeOpaque() const {
return { fR, fG, fB, 1.0f };
}
};
/** \struct SkColor4f
RGBA color value, holding four floating point components. Color components are always in
a known order, and are unpremultiplied.
This is a specialization of SkRGBA4f. For details, @see SkRGBA4f.
*/
using SkColor4f = SkRGBA4f<kUnpremul_SkAlphaType>;
template <> SK_API SkColor4f SkColor4f::FromColor(SkColor);
template <> SK_API SkColor SkColor4f::toSkColor() const;

Просмотреть файл

@ -13,9 +13,9 @@
#include "SkFlattenable.h"
#include "SkRefCnt.h"
class GrContext;
class GrColorSpaceInfo;
class GrFragmentProcessor;
class GrRecordingContext;
class SkArenaAlloc;
class SkBitmap;
class SkColorSpace;
@ -120,6 +120,17 @@ public:
*/
static sk_sp<SkColorFilter> MakeSRGBToLinearGamma();
/**
* Returns a new filter that returns the weighted average between the outputs of
* two other filters. If either is null, then it is treated as an identity filter.
*
* result = cf0(color) * (1 - weight) + cf1(color) * weight
*
* If both filters are null, or if weight is NaN, then null is returned.
*/
static sk_sp<SkColorFilter> MakeMixer(sk_sp<SkColorFilter> cf0, sk_sp<SkColorFilter> cf1,
float weight);
#if SK_SUPPORT_GPU
/**
* A subclass may implement this factory function to work with the GPU backend. It returns
@ -131,14 +142,14 @@ public:
* A null return indicates that the color filter isn't implemented for the GPU backend.
*/
virtual std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(
GrContext*, const GrColorSpaceInfo& dstColorSpaceInfo) const;
GrRecordingContext*, const GrColorSpaceInfo& dstColorSpaceInfo) const;
#endif
bool affectsTransparentBlack() const {
return this->filterColor(SK_ColorTRANSPARENT) != SK_ColorTRANSPARENT;
}
static void InitializeFlattenables();
static void RegisterFlattenables();
static SkFlattenable::Type GetFlattenableType() {
return kSkColorFilter_Type;

Просмотреть файл

@ -45,7 +45,7 @@ static inline U8CPU SkUnitScalarClampToByte(SkScalar x) {
#define SK_B32_MASK ((1 << SK_B32_BITS) - 1)
/*
* Skia's 32bit backend only supports 1 sizzle order at a time (compile-time).
* Skia's 32bit backend only supports 1 swizzle order at a time (compile-time).
* This is specified by 4 defines SK_A32_SHIFT, SK_R32_SHIFT, ... for G and B.
*
* For easier compatibility with Skia's GPU backend, we further restrict these
@ -61,6 +61,31 @@ static inline U8CPU SkUnitScalarClampToByte(SkScalar x) {
#define SK_RGBA_B32_SHIFT 16
#define SK_RGBA_A32_SHIFT 24
#define SK_BGRA_B32_SHIFT 0
#define SK_BGRA_G32_SHIFT 8
#define SK_BGRA_R32_SHIFT 16
#define SK_BGRA_A32_SHIFT 24
#if defined(SK_PMCOLOR_IS_RGBA) || defined(SK_PMCOLOR_IS_BGRA)
#error "Configure PMCOLOR by setting SK_R32_SHIFT, etc"
#endif
// Deduce which SK_PMCOLOR_IS_ to define from the _SHIFT defines
#if (SK_A32_SHIFT == SK_RGBA_A32_SHIFT && \
SK_R32_SHIFT == SK_RGBA_R32_SHIFT && \
SK_G32_SHIFT == SK_RGBA_G32_SHIFT && \
SK_B32_SHIFT == SK_RGBA_B32_SHIFT)
#define SK_PMCOLOR_IS_RGBA
#elif (SK_A32_SHIFT == SK_BGRA_A32_SHIFT && \
SK_R32_SHIFT == SK_BGRA_R32_SHIFT && \
SK_G32_SHIFT == SK_BGRA_G32_SHIFT && \
SK_B32_SHIFT == SK_BGRA_B32_SHIFT)
#define SK_PMCOLOR_IS_BGRA
#else
#error "need 32bit packing to be either RGBA or BGRA"
#endif
#define SkGetPackedA32(packed) ((uint32_t)((packed) << (24 - SK_A32_SHIFT)) >> 24)
#define SkGetPackedR32(packed) ((uint32_t)((packed) << (24 - SK_R32_SHIFT)) >> 24)
#define SkGetPackedG32(packed) ((uint32_t)((packed) << (24 - SK_G32_SHIFT)) >> 24)
@ -123,39 +148,4 @@ static inline SkPMColor SkPMSrcOver(SkPMColor src, SkPMColor dst) {
return src + SkAlphaMulQ(dst, SkAlpha255To256(255 - SkGetPackedA32(src)));
}
////////////////////////////////////////////////////////////////////////////////////////////
// Convert a 16bit pixel to a 32bit pixel
#define SK_R16_BITS 5
#define SK_G16_BITS 6
#define SK_B16_BITS 5
#define SK_R16_SHIFT (SK_B16_BITS + SK_G16_BITS)
#define SK_G16_SHIFT (SK_B16_BITS)
#define SK_B16_SHIFT 0
#define SK_R16_MASK ((1 << SK_R16_BITS) - 1)
#define SK_G16_MASK ((1 << SK_G16_BITS) - 1)
#define SK_B16_MASK ((1 << SK_B16_BITS) - 1)
#define SkGetPackedR16(color) (((unsigned)(color) >> SK_R16_SHIFT) & SK_R16_MASK)
#define SkGetPackedG16(color) (((unsigned)(color) >> SK_G16_SHIFT) & SK_G16_MASK)
#define SkGetPackedB16(color) (((unsigned)(color) >> SK_B16_SHIFT) & SK_B16_MASK)
static inline unsigned SkR16ToR32(unsigned r) {
return (r << (8 - SK_R16_BITS)) | (r >> (2 * SK_R16_BITS - 8));
}
static inline unsigned SkG16ToG32(unsigned g) {
return (g << (8 - SK_G16_BITS)) | (g >> (2 * SK_G16_BITS - 8));
}
static inline unsigned SkB16ToB32(unsigned b) {
return (b << (8 - SK_B16_BITS)) | (b >> (2 * SK_B16_BITS - 8));
}
#define SkPacked16ToR32(c) SkR16ToR32(SkGetPackedR16(c))
#define SkPacked16ToG32(c) SkG16ToG32(SkGetPackedG16(c))
#define SkPacked16ToB32(c) SkB16ToB32(SkGetPackedB16(c))
#endif

Просмотреть файл

@ -8,20 +8,14 @@
#ifndef SkColorSpace_DEFINED
#define SkColorSpace_DEFINED
#include "../private/SkFixed.h"
#include "../private/SkOnce.h"
#include "../../third_party/skcms/skcms.h"
#include "SkMatrix44.h"
#include "SkRefCnt.h"
#include <memory>
class SkData;
struct skcms_ICCProfile;
enum SkGammaNamed {
kLinear_SkGammaNamed,
kSRGB_SkGammaNamed,
k2Dot2Curve_SkGammaNamed,
kNonStandard_SkGammaNamed,
};
/**
* Describes a color gamut with primaries and a white point.
@ -40,27 +34,64 @@ struct SK_API SkColorSpacePrimaries {
* Convert primaries and a white point to a toXYZD50 matrix, the preferred color gamut
* representation of SkColorSpace.
*/
bool toXYZD50(SkMatrix44* toXYZD50) const;
bool toXYZD50(skcms_Matrix3x3* toXYZD50) const;
};
/**
* Contains the coefficients for a common transfer function equation, specified as
* a transformation from a curved space to linear.
*
* LinearVal = sign(InputVal) * ( C*|InputVal| + F ), for 0.0f <= |InputVal| < D
* LinearVal = sign(InputVal) * ( (A*|InputVal| + B)^G + E), for D <= |InputVal|
*
* Function must be positive and increasing.
*/
struct SK_API SkColorSpaceTransferFn {
float fG;
float fA;
float fB;
float fC;
float fD;
float fE;
float fF;
};
namespace SkNamedTransferFn {
// Like SkNamedGamut::kSRGB, keeping this bitwise exactly the same as skcms makes things fastest.
static constexpr skcms_TransferFunction kSRGB =
{ 2.4f, (float)(1/1.055), (float)(0.055/1.055), (float)(1/12.92), 0.04045f, 0.0f, 0.0f };
static constexpr skcms_TransferFunction k2Dot2 =
{ 2.2f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
static constexpr skcms_TransferFunction kLinear =
{ 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
}
namespace SkNamedGamut {
static constexpr skcms_Matrix3x3 kSRGB = {{
// ICC fixed-point (16.16) representation, taken from skcms. Please keep them exactly in sync.
// 0.436065674f, 0.385147095f, 0.143066406f,
// 0.222488403f, 0.716873169f, 0.060607910f,
// 0.013916016f, 0.097076416f, 0.714096069f,
{ SkFixedToFloat(0x6FA2), SkFixedToFloat(0x6299), SkFixedToFloat(0x24A0) },
{ SkFixedToFloat(0x38F5), SkFixedToFloat(0xB785), SkFixedToFloat(0x0F84) },
{ SkFixedToFloat(0x0390), SkFixedToFloat(0x18DA), SkFixedToFloat(0xB6CF) },
}};
static constexpr skcms_Matrix3x3 kAdobeRGB = {{
// ICC fixed-point (16.16) repesentation of:
// 0.60974, 0.20528, 0.14919,
// 0.31111, 0.62567, 0.06322,
// 0.01947, 0.06087, 0.74457,
{ SkFixedToFloat(0x9c18), SkFixedToFloat(0x348d), SkFixedToFloat(0x2631) },
{ SkFixedToFloat(0x4fa5), SkFixedToFloat(0xa02c), SkFixedToFloat(0x102f) },
{ SkFixedToFloat(0x04fc), SkFixedToFloat(0x0f95), SkFixedToFloat(0xbe9c) },
}};
static constexpr skcms_Matrix3x3 kDCIP3 = {{
{ 0.515102f, 0.291965f, 0.157153f },
{ 0.241182f, 0.692236f, 0.0665819f },
{ -0.00104941f, 0.0418818f, 0.784378f },
}};
static constexpr skcms_Matrix3x3 kRec2020 = {{
{ 0.673459f, 0.165661f, 0.125100f },
{ 0.279033f, 0.675338f, 0.0456288f },
{ -0.00193139f, 0.0299794f, 0.797162f },
}};
static constexpr skcms_Matrix3x3 kXYZ = {{
{ 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f },
}};
}
class SK_API SkColorSpace : public SkNVRefCnt<SkColorSpace> {
public:
@ -70,41 +101,15 @@ public:
static sk_sp<SkColorSpace> MakeSRGB();
/**
* Colorspace with the sRGB primaries, but a linear (1.0) gamma. Commonly used for
* half-float surfaces, and high precision individual colors (gradient stops, etc...)
* Colorspace with the sRGB primaries, but a linear (1.0) gamma.
*/
static sk_sp<SkColorSpace> MakeSRGBLinear();
enum RenderTargetGamma : uint8_t {
kLinear_RenderTargetGamma,
/**
* Transfer function is the canonical sRGB curve, which has a short linear segment
* followed by a 2.4f exponential.
*/
kSRGB_RenderTargetGamma,
};
enum Gamut {
kSRGB_Gamut,
kAdobeRGB_Gamut,
kDCIP3_D65_Gamut,
kRec2020_Gamut,
};
/**
* Create an SkColorSpace from a transfer function and a color gamut.
*
* Transfer function can be specified as an enum or as the coefficients to an equation.
* Gamut can be specified as an enum or as the matrix transformation to XYZ D50.
* Create an SkColorSpace from a transfer function and a row-major 3x3 transformation to XYZ.
*/
static sk_sp<SkColorSpace> MakeRGB(RenderTargetGamma gamma, Gamut gamut);
static sk_sp<SkColorSpace> MakeRGB(RenderTargetGamma gamma, const SkMatrix44& toXYZD50);
static sk_sp<SkColorSpace> MakeRGB(const SkColorSpaceTransferFn& coeffs, Gamut gamut);
static sk_sp<SkColorSpace> MakeRGB(const SkColorSpaceTransferFn& coeffs,
const SkMatrix44& toXYZD50);
static sk_sp<SkColorSpace> MakeRGB(SkGammaNamed gammaNamed, const SkMatrix44& toXYZD50);
static sk_sp<SkColorSpace> MakeRGB(const skcms_TransferFunction& transferFn,
const skcms_Matrix3x3& toXYZ);
/**
* Create an SkColorSpace from a parsed (skcms) ICC profile.
@ -116,17 +121,15 @@ public:
*/
void toProfile(skcms_ICCProfile*) const;
SkGammaNamed gammaNamed() const { return fGammaNamed; }
/**
* Returns true if the color space gamma is near enough to be approximated as sRGB.
*/
bool gammaCloseToSRGB() const { return kSRGB_SkGammaNamed == fGammaNamed; }
bool gammaCloseToSRGB() const;
/**
* Returns true if the color space gamma is linear.
*/
bool gammaIsLinear() const { return kLinear_SkGammaNamed == fGammaNamed; }
bool gammaIsLinear() const;
/**
* If the transfer function can be represented as coefficients to the standard
@ -134,7 +137,7 @@ public:
*
* If not, returns false.
*/
bool isNumericalTransferFn(SkColorSpaceTransferFn* fn) const;
bool isNumericalTransferFn(skcms_TransferFunction* fn) const;
/**
* Returns true and sets |toXYZD50| if the color gamut can be described as a matrix.
@ -142,6 +145,8 @@ public:
*/
bool toXYZD50(SkMatrix44* toXYZD50) const;
bool toXYZD50(skcms_Matrix3x3* toXYZD50) const;
/**
* Returns a hash of the gamut transformation to XYZ D50. Allows for fast equality checking
* of gamuts, at the (very small) risk of collision.
@ -216,13 +221,11 @@ public:
private:
friend class SkColorSpaceSingletonFactory;
SkColorSpace(SkGammaNamed gammaNamed,
const float transferFn[7],
const SkMatrix44& toXYZ);
SkColorSpace(const float transferFn[7],
const skcms_Matrix3x3& toXYZ);
void computeLazyDstFields() const;
SkGammaNamed fGammaNamed; // TODO: 2-bit, pack tightly? drop?
uint32_t fTransferFnHash;
uint32_t fToXYZD50Hash;

Просмотреть файл

@ -0,0 +1,146 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkContourMeasure_DEFINED
#define SkContourMeasure_DEFINED
#include "../private/SkNoncopyable.h"
#include "../private/SkTDArray.h"
#include "SkPath.h"
#include "SkRefCnt.h"
struct SkConic;
class SK_API SkContourMeasure : public SkRefCnt {
public:
/** Return the length of the contour.
*/
SkScalar length() const { return fLength; }
/** Pins distance to 0 <= distance <= length(), and then computes the corresponding
* position and tangent.
*/
bool SK_WARN_UNUSED_RESULT getPosTan(SkScalar distance, SkPoint* position,
SkVector* tangent) const;
enum MatrixFlags {
kGetPosition_MatrixFlag = 0x01,
kGetTangent_MatrixFlag = 0x02,
kGetPosAndTan_MatrixFlag = kGetPosition_MatrixFlag | kGetTangent_MatrixFlag
};
/** Pins distance to 0 <= distance <= getLength(), and then computes
the corresponding matrix (by calling getPosTan).
Returns false if there is no path, or a zero-length path was specified, in which case
matrix is unchanged.
*/
bool SK_WARN_UNUSED_RESULT getMatrix(SkScalar distance, SkMatrix* matrix,
MatrixFlags flags = kGetPosAndTan_MatrixFlag) const;
/** Given a start and stop distance, return in dst the intervening segment(s).
If the segment is zero-length, return false, else return true.
startD and stopD are pinned to legal values (0..getLength()). If startD > stopD
then return false (and leave dst untouched).
Begin the segment with a moveTo if startWithMoveTo is true
*/
bool SK_WARN_UNUSED_RESULT getSegment(SkScalar startD, SkScalar stopD, SkPath* dst,
bool startWithMoveTo) const;
/** Return true if the contour is closed()
*/
bool isClosed() const { return fIsClosed; }
private:
struct Segment {
SkScalar fDistance; // total distance up to this point
unsigned fPtIndex; // index into the fPts array
unsigned fTValue : 30;
unsigned fType : 2; // actually the enum SkSegType
// See SkPathMeasurePriv.h
SkScalar getScalarT() const;
static const Segment* Next(const Segment* seg) {
unsigned ptIndex = seg->fPtIndex;
do {
++seg;
} while (seg->fPtIndex == ptIndex);
return seg;
}
};
const SkTDArray<Segment> fSegments;
const SkTDArray<SkPoint> fPts; // Points used to define the segments
const SkScalar fLength;
const bool fIsClosed;
SkContourMeasure(SkTDArray<Segment>&& segs, SkTDArray<SkPoint>&& pts,
SkScalar length, bool isClosed);
~SkContourMeasure() override {}
const Segment* distanceToSegment(SkScalar distance, SkScalar* t) const;
friend class SkContourMeasureIter;
};
class SK_API SkContourMeasureIter : SkNoncopyable {
public:
SkContourMeasureIter();
/**
* Initialize the Iter with a path.
* The parts of the path that are needed are copied, so the client is free to modify/delete
* the path after this call.
*/
SkContourMeasureIter(const SkPath& path, bool forceClosed, SkScalar resScale = 1);
~SkContourMeasureIter();
/**
* Reset the Iter with a path.
* The parts of the path that are needed are copied, so the client is free to modify/delete
* the path after this call.
*/
void reset(const SkPath& path, bool forceClosed, SkScalar resScale = 1);
/**
* Iterates through contours in path, returning a contour-measure object for each contour
* in the path. Returns null when it is done.
*
* This only returns non-zero length contours, where a contour is the segments between
* a kMove_Verb and either ...
* - the next kMove_Verb
* - kClose_Verb (1 or more)
* - kDone_Verb
* If it encounters a zero-length contour, it is skipped.
*/
sk_sp<SkContourMeasure> next();
private:
SkPath::RawIter fIter;
SkPath fPath;
SkScalar fTolerance;
bool fForceClosed;
// temporary
SkTDArray<SkContourMeasure::Segment> fSegments;
SkTDArray<SkPoint> fPts; // Points used to define the segments
SkContourMeasure* buildSegments();
SkScalar compute_line_seg(SkPoint p0, SkPoint p1, SkScalar distance, unsigned ptIndex);
SkScalar compute_quad_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, unsigned ptIndex);
SkScalar compute_conic_segs(const SkConic& conic, SkScalar distance,
int mint, const SkPoint& minPt,
int maxt, const SkPoint& maxPt,
unsigned ptIndex);
SkScalar compute_cubic_segs(const SkPoint pts[4], SkScalar distance,
int mint, int maxt, unsigned ptIndex);
};
#endif

Просмотреть файл

@ -18,15 +18,9 @@
* pt[3] is implicitly { 1, 1 }
* pts[1,2] are inside the unit square
*/
class SkCubicMap {
class SK_API SkCubicMap {
public:
SkCubicMap() {} // must call setPts() before using
SkCubicMap(SkPoint p1, SkPoint p2) {
this->setPts(p1, p2);
}
void setPts(SkPoint p1, SkPoint p2);
SkCubicMap(SkPoint p1, SkPoint p2);
float computeYFromX(float x) const;
@ -38,6 +32,7 @@ private:
kCubeRoot_Type, // At^3 == x
kSolver_Type, // general monotonic cubic solver
};
SkPoint fCoeff[3];
Type fType;
};

Просмотреть файл

@ -5,24 +5,24 @@
* found in the LICENSE file.
*/
#ifndef SkDeferredDisplayListMaker_DEFINED
#define SkDeferredDisplayListMaker_DEFINED
#ifndef SkDeferredDisplayListRecorder_DEFINED
#define SkDeferredDisplayListRecorder_DEFINED
#include "../private/SkDeferredDisplayList.h"
#include "SkImageInfo.h"
#include "SkRefCnt.h"
#include "SkSurfaceCharacterization.h"
#include "SkTypes.h"
#include "../private/SkDeferredDisplayList.h"
class GrBackendFormat;
class GrBackendTexture;
class GrContext;
class SkCanvas;
class SkImage;
class SkPromiseImageTexture;
class SkSurface;
struct SkYUVAIndex;
struct SkYUVASizeInfo;
/*
* This class is intended to be used as:
@ -47,16 +47,16 @@ public:
// The backing canvas will become invalid (and this entry point will return
// null) once 'detach' is called.
// Note: ownership of the SkCanvas is not transfered via this call.
// Note: ownership of the SkCanvas is not transferred via this call.
SkCanvas* getCanvas();
std::unique_ptr<SkDeferredDisplayList> detach();
// Matches the defines in SkImage_Gpu.h
typedef void* TextureContext;
typedef void (*TextureReleaseProc)(TextureContext textureContext);
typedef void (*TextureFulfillProc)(TextureContext textureContext, GrBackendTexture* outTexture);
typedef void (*PromiseDoneProc)(TextureContext textureContext);
using PromiseImageTextureContext = void*;
using PromiseImageTextureFulfillProc =
sk_sp<SkPromiseImageTexture> (*)(PromiseImageTextureContext);
using PromiseImageTextureReleaseProc = void (*)(PromiseImageTextureContext);
using PromiseImageTextureDoneProc = void (*)(PromiseImageTextureContext);
/**
Create a new SkImage that is very similar to an SkImage created by MakeFromTexture. The main
@ -69,19 +69,18 @@ public:
match those set during the SkImage creation, and it must have a valid backend gpu texture.
The gpu texture supplied by the client must stay valid until we call the textureReleaseProc.
When we are done with the texture returned by the textureFulfillProc we will call the
textureReleaseProc passing in the textureContext. This is a signal to the client that they
are free to delete the underlying gpu texture. If future draws also use the same promise
image we will call the textureFulfillProc again if we've already called the
textureReleaseProc. We will always call textureFulfillProc and textureReleaseProc in pairs.
In other words we will never call textureFulfillProc or textureReleaseProc multiple times
for the same textureContext before calling the other.
When all the following are true:
* the promise image is deleted,
* any SkDeferredDisplayLists that recorded draws referencing the image are deleted,
* and the texture is safe to delete in the underlying API with respect to drawn
SkDeferredDisplayLists that reference the image
the textureReleaseProc and then textureDoneProc are called. The texture can be deleted
by the client as soon as textureReleaseProc is called. There is at most one call to each of
textureFulfillProc, textureReleaseProc, and textureDoneProc. textureDoneProc is always
called even if image creation fails or if the image is never fulfilled (e.g. it is never
drawn). If textureFulfillProc is called then textureReleaseProc will always be called even
if textureFulfillProc fails.
We call the promiseDoneProc when we will no longer call the textureFulfillProc again. We
pass in the textureContext as a parameter to the promiseDoneProc. We also guarantee that
there will be no outstanding textureReleaseProcs that still need to be called when we call
the textureDoneProc. Thus when the textureDoneProc gets called the client is able to cleanup
all GPU objects and meta data needed for the textureFulfill call.
This call is only valid if the SkDeferredDisplayListRecorder is backed by a gpu context.
@ -111,10 +110,10 @@ public:
SkColorType colorType,
SkAlphaType alphaType,
sk_sp<SkColorSpace> colorSpace,
TextureFulfillProc textureFulfillProc,
TextureReleaseProc textureReleaseProc,
PromiseDoneProc promiseDoneProc,
TextureContext textureContext);
PromiseImageTextureFulfillProc textureFulfillProc,
PromiseImageTextureReleaseProc textureReleaseProc,
PromiseImageTextureDoneProc textureDoneProc,
PromiseImageTextureContext textureContext);
/**
This entry point operates the same as 'makePromiseTexture' except that its
@ -125,15 +124,17 @@ public:
*/
sk_sp<SkImage> makeYUVAPromiseTexture(SkYUVColorSpace yuvColorSpace,
const GrBackendFormat yuvaFormats[],
const SkISize yuvaSizes[],
const SkYUVAIndex yuvaIndices[4],
int imageWidth,
int imageHeight,
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace,
TextureFulfillProc textureFulfillProc,
TextureReleaseProc textureReleaseProc,
PromiseDoneProc promiseDoneProc,
TextureContext textureContexts[]);
PromiseImageTextureFulfillProc textureFulfillProc,
PromiseImageTextureReleaseProc textureReleaseProc,
PromiseImageTextureDoneProc textureDoneProc,
PromiseImageTextureContext textureContexts[]);
private:
bool init();

Просмотреть файл

@ -9,11 +9,14 @@
#define SkDrawable_DEFINED
#include "SkFlattenable.h"
#include "SkImageInfo.h"
#include "SkScalar.h"
class GrBackendDrawableInfo;
class SkCanvas;
class SkMatrix;
class SkPicture;
enum class GrBackendApi : unsigned;
struct SkRect;
/**
@ -25,8 +28,6 @@ struct SkRect;
*/
class SK_API SkDrawable : public SkFlattenable {
public:
SkDrawable();
/**
* Draws into the specified content. The drawing sequence will be balanced upon return
* (i.e. the saveLevel() on the canvas will match what it was when draw() was called,
@ -35,6 +36,55 @@ public:
void draw(SkCanvas*, const SkMatrix* = nullptr);
void draw(SkCanvas*, SkScalar x, SkScalar y);
/**
* When using the GPU backend it is possible for a drawable to execute using the underlying 3D
* API rather than the SkCanvas API. It does so by creating a GpuDrawHandler. The GPU backend
* is deferred so the handler will be given access to the 3D API at the correct point in the
* drawing stream as the GPU backend flushes. Since the drawable may mutate, each time it is
* drawn to a GPU-backed canvas a new handler is snapped, representing the drawable's state at
* the time of the snap.
*
* When the GPU backend flushes to the 3D API it will call the draw method on the
* GpuDrawHandler. At this time the drawable may add commands to the stream of GPU commands for
* the unerlying 3D API. The draw function takes a GrBackendDrawableInfo which contains
* information about the current state of 3D API which the caller must respect. See
* GrBackendDrawableInfo for more specific details on what information is sent and the
* requirements for different 3D APIs.
*
* Additionaly there may be a slight delay from when the drawable adds its commands to when
* those commands are actually submitted to the GPU. Thus the drawable or GpuDrawHandler is
* required to keep any resources that are used by its added commands alive and valid until
* those commands are submitted to the GPU. The GpuDrawHandler will be kept alive and then
* deleted once the commands are submitted to the GPU. The dtor of the GpuDrawHandler is the
* signal to the drawable that the commands have all been submitted. Different 3D APIs may have
* additional requirements for certain resources which require waiting for the GPU to finish
* all work on those resources before reusing or deleting them. In this case, the drawable can
* use the dtor call of the GpuDrawHandler to add a fence to the GPU to track when the GPU work
* has completed.
*
* Currently this is only supported for the GPU Vulkan backend.
*/
class GpuDrawHandler {
public:
virtual ~GpuDrawHandler() {}
virtual void draw(const GrBackendDrawableInfo&) {}
};
/**
* Snaps off a GpuDrawHandler to represent the state of the SkDrawable at the time the snap is
* called. This is used for executing GPU backend specific draws intermixed with normal Skia GPU
* draws. The GPU API, which will be used for the draw, as well as the full matrix, device clip
* bounds and imageInfo of the target buffer are passed in as inputs.
*/
std::unique_ptr<GpuDrawHandler> snapGpuDrawHandler(GrBackendApi backendApi,
const SkMatrix& matrix,
const SkIRect& clipBounds,
const SkImageInfo& bufferInfo) {
return this->onSnapGpuDrawHandler(backendApi, matrix, clipBounds, bufferInfo);
}
SkPicture* newPictureSnapshot();
/**
@ -76,11 +126,25 @@ public:
}
Factory getFactory() const override { return nullptr; }
const char* getTypeName() const override { return nullptr; }
protected:
SkDrawable();
virtual SkRect onGetBounds() = 0;
virtual void onDraw(SkCanvas*) = 0;
virtual std::unique_ptr<GpuDrawHandler> onSnapGpuDrawHandler(GrBackendApi, const SkMatrix&,
const SkIRect& /*clipBounds*/,
const SkImageInfo&) {
return nullptr;
}
// TODO: Delete this once Android gets updated to take the clipBounds version above.
virtual std::unique_ptr<GpuDrawHandler> onSnapGpuDrawHandler(GrBackendApi, const SkMatrix&) {
return nullptr;
}
/**
* Default implementation calls onDraw() with a canvas that records into a picture. Subclasses
* may override if they have a more efficient way to return a picture for the current state

Просмотреть файл

@ -10,8 +10,9 @@
#include <functional>
#include <memory>
#include "SkTypes.h"
class SkExecutor {
class SK_API SkExecutor {
public:
virtual ~SkExecutor();

Просмотреть файл

@ -52,27 +52,13 @@ public:
/**
* Returns the name of the object's class.
*
* Subclasses should override this function if they intend to provide
* support for flattening without using the global registry.
*
* If the flattenable is registered, there is no need to override.
*/
virtual const char* getTypeName() const {
#ifdef SK_DISABLE_READBUFFER
// Should not be reachable by PathKit WebAssembly Code.
SkASSERT(false);
return nullptr;
#else
return FactoryToName(getFactory());
#endif
}
virtual const char* getTypeName() const = 0;
static Factory NameToFactory(const char name[]);
static const char* FactoryToName(Factory);
static bool NameToType(const char name[], Type* type);
static void Register(const char name[], Factory, Type);
static void Register(const char name[], Factory);
/**
* Override this if your subclass needs to record data that it will need to recreate itself
@ -96,13 +82,12 @@ public:
protected:
class PrivateInitializer {
public:
static void InitCore();
static void InitEffects();
static void InitImageFilters();
};
private:
static void InitializeFlattenablesIfNeeded();
static void RegisterFlattenablesIfNeeded();
static void Finalize();
friend class SkGraphics;
@ -110,4 +95,12 @@ private:
typedef SkRefCnt INHERITED;
};
#define SK_REGISTER_FLATTENABLE(type) SkFlattenable::Register(#type, type::CreateProc)
#define SK_FLATTENABLE_HOOKS(type) \
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&); \
friend class SkFlattenable::PrivateInitializer; \
Factory getFactory() const override { return type::CreateProc; } \
const char* getTypeName() const override { return #type; }
#endif

Просмотреть файл

@ -8,157 +8,511 @@
#ifndef SkFont_DEFINED
#define SkFont_DEFINED
#include "SkRefCnt.h"
#include "SkFontTypes.h"
#include "SkScalar.h"
#include "SkTypeface.h"
class SkMatrix;
class SkPaint;
class SkTypeface;
class SkPath;
struct SkFontMetrics;
enum SkTextEncoding {
kUTF8_SkTextEncoding,
kUTF16_SkTextEncoding,
kUTF32_SkTextEncoding,
kGlyphID_SkTextEncoding,
};
/*
1. The Hinting enum in SkPaint is gone entirely, absorbed into SkFont's flags.
2. SkPaint Flags look like this today
enum Flags {
kAntiAlias_Flag = 0x01, //!< mask to enable antialiasing
kDither_Flag = 0x04, //!< mask to enable dithering
kFakeBoldText_Flag = 0x20, //!< mask to enable fake-bold text
kLinearText_Flag = 0x40, //!< mask to enable linear-text
kSubpixelText_Flag = 0x80, //!< mask to enable subpixel text positioning
kLCDRenderText_Flag = 0x200, //!< mask to enable subpixel glyph renderering
kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes
kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter
kVerticalText_Flag = 0x1000,
};
SkFont would absorb these:
kFakeBoldText_Flag = 0x20, //!< mask to enable fake-bold text
kLinearText_Flag = 0x40, //!< mask to enable linear-text
kSubpixelText_Flag = 0x80, //!< mask to enable subpixel text positioning
kLCDRenderText_Flag = 0x200, //!< mask to enable subpixel glyph renderering
kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes
kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter
kVerticalText_Flag = 0x1000,
leaving these still in paint
kAntiAlias_Flag = 0x01, //!< mask to enable antialiasing
kDither_Flag = 0x04, //!< mask to enable dithering
3. Antialiasing
SkFont has a mask-type: BW, AA, LCD
SkPaint has antialias boolean
What to do if the font's mask-type disagrees with the paint?
*/
class SkFont : public SkRefCnt {
/** \class SkFont
SkFont controls options applied when drawing and measuring text.
*/
class SK_API SkFont {
public:
enum Flags {
/**
* Use the system's automatic hinting mechanism to hint the typeface.
* This is a last resort hinting method applied only if other hinting methods do not apply.
* TODO: where to put auto-normal vs auto-light?
*/
kEnableAutoHints_Flag = 1 << 0,
/**
* If the typeface contains explicit bytecodes for hinting, use them.
* If both bytecode and auto hints are specified, attempt to use the bytecodes first;
* if that fails (e.g. there are no codes), then attempt to autohint.
*/
kEnableByteCodeHints_Flag = 1 << 1,
/**
* If the typeface contains explicit bitmaps for hinting, use them.
* If both bytecode and auto hints are also specified, attempt to use the bitmaps first;
* if that fails (e.g. there are no bitmaps), then attempt to bytecode or autohint.
*/
kEmbeddedBitmaps_Flag = 1 << 2,
/**
* Use rounded metric values (e.g. advance).
* If either auto or bytecode hinting was used, apply those results to the metrics of the
* glyphs as well. If no hinting was applied, the metrics will just be rounded to the
* nearest integer.
*
* This applies to calls that return metrics (e.g. measureText) and to drawing the glyphs
* (see SkCanvas drawText and drawPosText).
*/
kUseNonlinearMetrics_Flag = 1 << 3,
kVertical_Flag = 1 << 4,
kEmbolden_Flag = 1 << 6,
/** Whether edge pixels draw opaque or with partial transparency.
*/
enum class Edging {
kAlias, //!< no transparent pixels on glyph edges
kAntiAlias, //!< may have transparent pixels on glyph edges
kSubpixelAntiAlias, //!< glyph positioned in pixel using transparency
};
enum MaskType {
kBW_MaskType,
kA8_MaskType,
kLCD_MaskType,
};
/** Constructs SkFont with default values.
static sk_sp<SkFont> Make(sk_sp<SkTypeface>, SkScalar size, MaskType, uint32_t flags);
static sk_sp<SkFont> Make(sk_sp<SkTypeface>, SkScalar size, SkScalar scaleX, SkScalar skewX,
MaskType, uint32_t flags);
@return default initialized SkFont
*/
SkFont();
/**
* Return a font with the same attributes of this font, but with the specified size.
* If size is not supported (e.g. <= 0 or non-finite) NULL will be returned.
/** Constructs SkFont with default values with SkTypeface and size in points.
@param typeface font and style used to draw and measure text
@param size typographic height of text
@return initialized SkFont
*/
SkFont(sk_sp<SkTypeface> typeface, SkScalar size);
/** Constructs SkFont with default values with SkTypeface.
@param typeface font and style used to draw and measure text
@return initialized SkFont
*/
explicit SkFont(sk_sp<SkTypeface> typeface);
/** Constructs SkFont with default values with SkTypeface and size in points,
horizontal scale, and horizontal skew. Horizontal scale emulates condensed
and expanded fonts. Horizontal skew emulates oblique fonts.
@param typeface font and style used to draw and measure text
@param size typographic height of text
@param scaleX text horizontal scale
@param skewX additional shear on x-axis relative to y-axis
@return initialized SkFont
*/
SkFont(sk_sp<SkTypeface> typeface, SkScalar size, SkScalar scaleX, SkScalar skewX);
/** Compares SkFont and font, and returns true if they are equivalent.
May return false if SkTypeface has identical contents but different pointers.
@param font font to compare
@return true if SkFont pair are equivalent
*/
bool operator==(const SkFont& font) const;
/** Compares SkFont and font, and returns true if they are not equivalent.
May return true if SkTypeface has identical contents but different pointers.
@param font font to compare
@return true if SkFont pair are not equivalent
*/
bool operator!=(const SkFont& font) const { return !(*this == font); }
/** If true, instructs the font manager to always hint glyphs.
Returned value is only meaningful if platform uses FreeType as the font manager.
@return true if all glyphs are hinted
*/
bool isForceAutoHinting() const { return SkToBool(fFlags & kForceAutoHinting_PrivFlag); }
/** Returns true if font engine may return glyphs from font bitmaps instead of from outlines.
@return true if glyphs may be font bitmaps
*/
bool isEmbeddedBitmaps() const { return SkToBool(fFlags & kEmbeddedBitmaps_PrivFlag); }
/** Returns true if glyphs at different sub-pixel positions may differ on pixel edge coverage.
@return true if glyph positioned in pixel using transparency
*/
bool isSubpixel() const { return SkToBool(fFlags & kSubpixel_PrivFlag); }
/** Returns true if text is converted to SkPath before drawing and measuring.
@return true glyph hints are never applied
*/
bool isLinearMetrics() const { return SkToBool(fFlags & kLinearMetrics_PrivFlag); }
/** Returns true if bold is approximated by increasing the stroke width when creating glyph
bitmaps from outlines.
@return bold is approximated through stroke width
*/
bool isEmbolden() const { return SkToBool(fFlags & kEmbolden_PrivFlag); }
/** Sets whether to always hint glyphs.
If forceAutoHinting is set, instructs the font manager to always hint glyphs.
Only affects platforms that use FreeType as the font manager.
@param forceAutoHinting setting to always hint glyphs
*/
void setForceAutoHinting(bool forceAutoHinting);
/** Requests, but does not require, to use bitmaps in fonts instead of outlines.
@param embeddedBitmaps setting to use bitmaps in fonts
*/
void setEmbeddedBitmaps(bool embeddedBitmaps);
/** Requests, but does not require, that glyphs respect sub-pixel positioning.
@param subpixel setting for sub-pixel positioning
*/
void setSubpixel(bool subpixel);
/** Requests, but does not require, that glyphs are converted to SkPath
before drawing and measuring.
@param linearMetrics setting for converting glyphs to paths
*/
void setLinearMetrics(bool linearMetrics);
/** Increases stroke width when creating glyph bitmaps to approximate a bold typeface.
@param embolden setting for bold approximation
*/
void setEmbolden(bool embolden);
/** Whether edge pixels draw opaque or with partial transparency.
@return one of: Edging::kAlias, Edging::kAntiAlias, Edging::kSubpixelAntiAlias
*/
Edging getEdging() const { return (Edging)fEdging; }
/** Requests, but does not require, that edge pixels draw opaque or with
partial transparency.
@param edging one of: Edging::kAlias, Edging::kAntiAlias, Edging::kSubpixelAntiAlias
*/
void setEdging(Edging edging);
/** Sets level of glyph outline adjustment.
Does not check for valid values of hintingLevel.
@param hintingLevel one of: SkFontHinting::kNone, SkFontHinting::kSlight,
SkFontHinting::kNormal, SkFontHinting::kFull
*/
void setHinting(SkFontHinting hintingLevel);
/** Returns level of glyph outline adjustment.
@return one of: SkFontHinting::kNone, SkFontHinting::kSlight, SkFontHinting::kNormal,
SkFontHinting::kFull
*/
sk_sp<SkFont> makeWithSize(SkScalar size) const;
/**
* Return a font with the same attributes of this font, but with the flags.
*/
sk_sp<SkFont> makeWithFlags(uint32_t newFlags) const;
SkFontHinting getHinting() const { return (SkFontHinting)fHinting; }
SkTypeface* getTypeface() const { return fTypeface.get(); }
/** Returns a font with the same attributes of this font, but with the specified size.
Returns nullptr if size is less than zero, infinite, or NaN.
@param size typographic height of text
@return initialized SkFont
*/
SkFont makeWithSize(SkScalar size) const;
/** Returns SkTypeface if set, or nullptr.
Does not alter SkTypeface SkRefCnt.
@return SkTypeface if previously set, nullptr otherwise
*/
SkTypeface* getTypeface() const {return fTypeface.get(); }
/** Returns SkTypeface if set, or the default typeface.
Does not alter SkTypeface SkRefCnt.
@return SkTypeface if previously set or, a pointer to the default typeface if not
previously set.
*/
SkTypeface* getTypefaceOrDefault() const;
/** Returns text size in points.
@return typographic height of text
*/
SkScalar getSize() const { return fSize; }
/** Returns text scale on x-axis.
Default value is 1.
@return text horizontal scale
*/
SkScalar getScaleX() const { return fScaleX; }
/** Returns text skew on x-axis.
Default value is zero.
@return additional shear on x-axis relative to y-axis
*/
SkScalar getSkewX() const { return fSkewX; }
uint32_t getFlags() const { return fFlags; }
MaskType getMaskType() const { return (MaskType)fMaskType; }
bool isVertical() const { return SkToBool(fFlags & kVertical_Flag); }
bool isEmbolden() const { return SkToBool(fFlags & kEmbolden_Flag); }
bool isEnableAutoHints() const { return SkToBool(fFlags & kEnableAutoHints_Flag); }
bool isEnableByteCodeHints() const { return SkToBool(fFlags & kEnableByteCodeHints_Flag); }
bool isUseNonLinearMetrics() const { return SkToBool(fFlags & kUseNonlinearMetrics_Flag); }
/** Increases SkTypeface SkRefCnt by one.
int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding,
@return SkTypeface if previously set, nullptr otherwise
*/
sk_sp<SkTypeface> refTypeface() const { return fTypeface; }
/** Increases SkTypeface SkRefCnt by one.
@return SkTypeface if previously set or, a pointer to the default typeface if not
previously set.
*/
sk_sp<SkTypeface> refTypefaceOrDefault() const;
/** Sets SkTypeface to typeface, decreasing SkRefCnt of the previous SkTypeface.
Pass nullptr to clear SkTypeface and use the default typeface. Increments
tf SkRefCnt by one.
@param tf font and style used to draw text
*/
void setTypeface(sk_sp<SkTypeface> tf) { fTypeface = tf; }
/** Sets text size in points.
Has no effect if textSize is not greater than or equal to zero.
@param textSize typographic height of text
*/
void setSize(SkScalar textSize);
/** Sets text scale on x-axis.
Default value is 1.
@param scaleX text horizontal scale
*/
void setScaleX(SkScalar scaleX);
/** Sets text skew on x-axis.
Default value is zero.
@param skewX additional shear on x-axis relative to y-axis
*/
void setSkewX(SkScalar skewX);
/** Converts text into glyph indices.
Returns the number of glyph indices represented by text.
SkTextEncoding specifies how text represents characters or glyphs.
glyphs may be nullptr, to compute the glyph count.
Does not check text for valid character codes or valid glyph indices.
If byteLength equals zero, returns zero.
If byteLength includes a partial character, the partial character is ignored.
If encoding is kUTF8_SkTextEncoding and text contains an invalid UTF-8 sequence,
zero is returned.
When encoding is SkTextEncoding::kUTF8, SkTextEncoding::kUTF16, or
SkTextEncoding::kUTF32; then each Unicode codepoint is mapped to a
single glyph. This function uses the default character-to-glyph
mapping from the SkTypeface and maps characters not found in the
SkTypeface to zero.
If maxGlyphCount is not sufficient to store all the glyphs, no glyphs are copied.
The total glyph count is returned for subsequent buffer reallocation.
@param text character storage encoded with SkTextEncoding
@param byteLength length of character storage in bytes
@param encoding one of: kUTF8_SkTextEncoding, kUTF16_SkTextEncoding,
kUTF32_SkTextEncoding, kGlyphID_SkTextEncoding
@param glyphs storage for glyph indices; may be nullptr
@param maxGlyphCount storage capacity
@return number of glyphs represented by text of length byteLength
*/
int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
SkGlyphID glyphs[], int maxGlyphCount) const;
int countText(const void* text, size_t byteLength, SkTextEncoding encoding) {
/** Returns glyph index for Unicode character.
If the character is not supported by the SkTypeface, returns 0.
@param uni Unicode character
@return glyph index
*/
SkGlyphID unicharToGlyph(SkUnichar uni) const;
/** Returns number of glyphs represented by text.
If encoding is kUTF8_SkTextEncoding, kUTF16_SkTextEncoding, or
kUTF32_SkTextEncoding; then each Unicode codepoint is mapped to a
single glyph.
@param text character storage encoded with SkTextEncoding
@param byteLength length of character storage in bytes
@param encoding one of: kUTF8_SkTextEncoding, kUTF16_SkTextEncoding,
kUTF32_SkTextEncoding, kGlyphID_SkTextEncoding
@return number of glyphs represented by text of length byteLength
*/
int countText(const void* text, size_t byteLength, SkTextEncoding encoding) const {
return this->textToGlyphs(text, byteLength, encoding, nullptr, 0);
}
SkScalar measureText(const void* text, size_t byteLength, SkTextEncoding) const;
/** Returns the advance width of text.
The advance is the normal distance to move before drawing additional text.
Returns the bounding box of text if bounds is not nullptr.
static sk_sp<SkFont> Testing_CreateFromPaint(const SkPaint&);
@param text character storage encoded with SkTextEncoding
@param byteLength length of character storage in bytes
@param encoding one of: kUTF8_SkTextEncoding, kUTF16_SkTextEncoding,
kUTF32_SkTextEncoding, kGlyphID_SkTextEncoding
@param bounds returns bounding box relative to (0, 0) if not nullptr
@return number of glyphs represented by text of length byteLength
*/
SkScalar measureText(const void* text, size_t byteLength, SkTextEncoding encoding,
SkRect* bounds = nullptr) const {
return this->measureText(text, byteLength, encoding, bounds, nullptr);
}
/** Returns the advance width of text.
The advance is the normal distance to move before drawing additional text.
Returns the bounding box of text if bounds is not nullptr. paint
stroke width or SkPathEffect may modify the advance with.
@param text character storage encoded with SkTextEncoding
@param byteLength length of character storage in bytes
@param encoding one of: kUTF8_SkTextEncoding, kUTF16_SkTextEncoding,
kUTF32_SkTextEncoding, kGlyphID_SkTextEncoding
@param bounds returns bounding box relative to (0, 0) if not nullptr
@param paint optional; may be nullptr
@return number of glyphs represented by text of length byteLength
*/
SkScalar measureText(const void* text, size_t byteLength, SkTextEncoding encoding,
SkRect* bounds, const SkPaint* paint) const;
/** DEPRECATED
Retrieves the advance and bounds for each glyph in glyphs.
Both widths and bounds may be nullptr.
If widths is not nullptr, widths must be an array of count entries.
if bounds is not nullptr, bounds must be an array of count entries.
@param glyphs array of glyph indices to be measured
@param count number of glyphs
@param widths returns text advances for each glyph; may be nullptr
@param bounds returns bounds for each glyph relative to (0, 0); may be nullptr
*/
void getWidths(const uint16_t glyphs[], int count, SkScalar widths[], SkRect bounds[]) const {
this->getWidthsBounds(glyphs, count, widths, bounds, nullptr);
}
// DEPRECATED
void getWidths(const uint16_t glyphs[], int count, SkScalar widths[], std::nullptr_t) const {
this->getWidths(glyphs, count, widths);
}
/** Retrieves the advance and bounds for each glyph in glyphs.
Both widths and bounds may be nullptr.
If widths is not nullptr, widths must be an array of count entries.
if bounds is not nullptr, bounds must be an array of count entries.
@param glyphs array of glyph indices to be measured
@param count number of glyphs
@param widths returns text advances for each glyph
*/
void getWidths(const uint16_t glyphs[], int count, SkScalar widths[]) const {
this->getWidthsBounds(glyphs, count, widths, nullptr, nullptr);
}
/** Retrieves the advance and bounds for each glyph in glyphs.
Both widths and bounds may be nullptr.
If widths is not nullptr, widths must be an array of count entries.
if bounds is not nullptr, bounds must be an array of count entries.
@param glyphs array of glyph indices to be measured
@param count number of glyphs
@param widths returns text advances for each glyph; may be nullptr
@param bounds returns bounds for each glyph relative to (0, 0); may be nullptr
@param paint optional, specifies stroking, SkPathEffect and SkMaskFilter
*/
void getWidthsBounds(const uint16_t glyphs[], int count, SkScalar widths[], SkRect bounds[],
const SkPaint* paint) const;
/** Retrieves the bounds for each glyph in glyphs.
bounds must be an array of count entries.
If paint is not nullptr, its stroking, SkPathEffect, and SkMaskFilter fields are respected.
@param glyphs array of glyph indices to be measured
@param count number of glyphs
@param bounds returns bounds for each glyph relative to (0, 0); may be nullptr
@param paint optional, specifies stroking, SkPathEffect, and SkMaskFilter
*/
void getBounds(const uint16_t glyphs[], int count, SkRect bounds[],
const SkPaint* paint) const {
this->getWidthsBounds(glyphs, count, nullptr, bounds, paint);
}
/** Retrieves the positions for each glyph, beginning at the specified origin. The caller
must allocated at least count number of elements in the pos[] array.
@param glyphs array of glyph indices to be positioned
@param count number of glyphs
@param pos returns glyphs positions
@param origin location of the first glyph. Defaults to {0, 0}.
*/
void getPos(const uint16_t glyphs[], int count, SkPoint pos[], SkPoint origin = {0, 0}) const;
/** Retrieves the x-positions for each glyph, beginning at the specified origin. The caller
must allocated at least count number of elements in the xpos[] array.
@param glyphs array of glyph indices to be positioned
@param count number of glyphs
@param xpos returns glyphs x-positions
@param origin x-position of the first glyph. Defaults to 0.
*/
void getXPos(const uint16_t glyphs[], int count, SkScalar xpos[], SkScalar origin = 0) const;
/** Returns path corresponding to glyph outline.
If glyph has an outline, copies outline to path and returns true.
path returned may be empty.
If glyph is described by a bitmap, returns false and ignores path parameter.
@param glyphID index of glyph
@param path pointer to existing SkPath
@return true if glyphID is described by path
*/
bool getPath(uint16_t glyphID, SkPath* path) const;
/** Returns path corresponding to glyph array.
@param glyphIDs array of glyph indices
@param count number of glyphs
@param glyphPathProc function returning one glyph description as path
@param ctx function context
*/
void getPaths(const uint16_t glyphIDs[], int count,
void (*glyphPathProc)(const SkPath* pathOrNull, const SkMatrix& mx, void* ctx),
void* ctx) const;
/** Returns SkFontMetrics associated with SkTypeface.
The return value is the recommended spacing between lines: the sum of metrics
descent, ascent, and leading.
If metrics is not nullptr, SkFontMetrics is copied to metrics.
Results are scaled by text size but does not take into account
dimensions required by text scale, text skew, fake bold,
style stroke, and SkPathEffect.
@param metrics storage for SkFontMetrics; may be nullptr
@return recommended spacing between lines
*/
SkScalar getMetrics(SkFontMetrics* metrics) const;
/** Returns the recommended spacing between lines: the sum of metrics
descent, ascent, and leading.
Result is scaled by text size but does not take into account
dimensions required by stroking and SkPathEffect.
Returns the same result as getMetrics().
@return recommended spacing between lines
*/
SkScalar getSpacing() const { return this->getMetrics(nullptr); }
/** Experimental.
* Dumps fields of the font to SkDebugf. May change its output over time, so clients should
* not rely on this for anything specific. Used to aid in debugging.
*/
void dump() const;
private:
static constexpr int kAllFlags = 0xFF;
enum PrivFlags {
kForceAutoHinting_PrivFlag = 1 << 0,
kEmbeddedBitmaps_PrivFlag = 1 << 1,
kSubpixel_PrivFlag = 1 << 2,
kLinearMetrics_PrivFlag = 1 << 3,
kEmbolden_PrivFlag = 1 << 4,
};
SkFont(sk_sp<SkTypeface>, SkScalar size, SkScalar scaleX, SkScalar skewX, MaskType,
uint32_t flags);
static constexpr unsigned kAllFlags = 0x1F;
sk_sp<SkTypeface> fTypeface;
SkScalar fSize;
SkScalar fScaleX;
SkScalar fSkewX;
uint16_t fFlags;
uint8_t fMaskType;
// uint8_t fPad;
uint8_t fFlags;
uint8_t fEdging;
uint8_t fHinting;
SkScalar setupForAsPaths(SkPaint*);
bool hasSomeAntiAliasing() const;
void glyphsToUnichars(const SkGlyphID glyphs[], int count, SkUnichar text[]) const;
friend class GrTextBlob;
friend class SkCanonicalizeFont;
friend class SkFontPriv;
friend class SkGlyphRunListPainter;
friend class SkTextBlobCacheDiffCanvas;
friend class SVGTextBuilder;
};
#endif

Просмотреть файл

@ -0,0 +1,106 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkFontMetrics_DEFINED
#define SkFontMetrics_DEFINED
#include "SkScalar.h"
struct SK_API SkFontMetrics {
/** \enum FontMetricsFlags
FontMetricsFlags are set in fFlags when underline and strikeout metrics are valid;
the underline or strikeout metric may be valid and zero.
Fonts with embedded bitmaps may not have valid underline or strikeout metrics.
*/
enum FontMetricsFlags {
kUnderlineThicknessIsValid_Flag = 1 << 0, //!< set if fUnderlineThickness is valid
kUnderlinePositionIsValid_Flag = 1 << 1, //!< set if fUnderlinePosition is valid
kStrikeoutThicknessIsValid_Flag = 1 << 2, //!< set if fStrikeoutThickness is valid
kStrikeoutPositionIsValid_Flag = 1 << 3, //!< set if fStrikeoutPosition is valid
};
uint32_t fFlags; //!< is set to FontMetricsFlags when metrics are valid
SkScalar fTop; //!< extent above baseline
SkScalar fAscent; //!< distance to reserve above baseline
SkScalar fDescent; //!< distance to reserve below baseline
SkScalar fBottom; //!< extent below baseline
SkScalar fLeading; //!< distance to add between lines
SkScalar fAvgCharWidth; //!< average character width
SkScalar fMaxCharWidth; //!< maximum character width
SkScalar fXMin; //!< minimum x
SkScalar fXMax; //!< maximum x
SkScalar fXHeight; //!< height of lower-case 'x'
SkScalar fCapHeight; //!< height of an upper-case letter
SkScalar fUnderlineThickness; //!< underline thickness
SkScalar fUnderlinePosition; //!< underline position relative to baseline
SkScalar fStrikeoutThickness; //!< strikeout thickness
SkScalar fStrikeoutPosition; //!< strikeout position relative to baseline
/** Returns true if SkFontMetrics has a valid underline thickness, and sets
thickness to that value. If the underline thickness is not valid,
return false, and ignore thickness.
@param thickness storage for underline width
@return true if font specifies underline width
*/
bool hasUnderlineThickness(SkScalar* thickness) const {
if (SkToBool(fFlags & kUnderlineThicknessIsValid_Flag)) {
*thickness = fUnderlineThickness;
return true;
}
return false;
}
/** Returns true if SkFontMetrics has a valid underline position, and sets
position to that value. If the underline position is not valid,
return false, and ignore position.
@param position storage for underline position
@return true if font specifies underline position
*/
bool hasUnderlinePosition(SkScalar* position) const {
if (SkToBool(fFlags & kUnderlinePositionIsValid_Flag)) {
*position = fUnderlinePosition;
return true;
}
return false;
}
/** Returns true if SkFontMetrics has a valid strikeout thickness, and sets
thickness to that value. If the underline thickness is not valid,
return false, and ignore thickness.
@param thickness storage for strikeout width
@return true if font specifies strikeout width
*/
bool hasStrikeoutThickness(SkScalar* thickness) const {
if (SkToBool(fFlags & kStrikeoutThicknessIsValid_Flag)) {
*thickness = fStrikeoutThickness;
return true;
}
return false;
}
/** Returns true if SkFontMetrics has a valid strikeout position, and sets
position to that value. If the underline position is not valid,
return false, and ignore position.
@param position storage for strikeout position
@return true if font specifies strikeout position
*/
bool hasStrikeoutPosition(SkScalar* position) const {
if (SkToBool(fFlags & kStrikeoutPositionIsValid_Flag)) {
*position = fStrikeoutPosition;
return true;
}
return false;
}
};
#endif

Просмотреть файл

@ -0,0 +1,39 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkFontTypes_DEFINED
#define SkFontTypes_DEFINED
#include "SkTypes.h"
// remove me once google3 uses IWYU
#include "SkTypeface.h"
enum class SkTextEncoding {
kUTF8, //!< uses bytes to represent UTF-8 or ASCII
kUTF16, //!< uses two byte words to represent most of Unicode
kUTF32, //!< uses four byte words to represent all of Unicode
kGlyphID, //!< uses two byte words to represent glyph indices
};
#define kUTF8_SkTextEncoding SkTextEncoding::kUTF8
#define kUTF16_SkTextEncoding SkTextEncoding::kUTF16
#define kUTF32_SkTextEncoding SkTextEncoding::kUTF32
#define kGlyphID_SkTextEncoding SkTextEncoding::kGlyphID
enum class SkFontHinting {
kNone, //!< glyph outlines unchanged
kSlight, //!< minimal modification to improve constrast
kNormal, //!< glyph outlines modified to improve constrast
kFull, //!< modifies glyph outlines for maximum constrast
};
#define kNo_SkFontHinting SkFontHinting::kNone
#define kSlight_SkFontHinting SkFontHinting::kSlight
#define kNormal_SkFontHinting SkFontHinting::kNormal
#define kFull_SkFontHinting SkFontHinting::kFull
#endif

Просмотреть файл

@ -9,30 +9,11 @@
#define SkICC_DEFINED
#include "SkData.h"
#include "SkMatrix44.h"
#include "SkRefCnt.h"
struct SkColorSpaceTransferFn;
struct skcms_Matrix3x3;
struct skcms_TransferFunction;
SK_API sk_sp<SkData> SkWriteICCProfile(const SkColorSpaceTransferFn&, const float toXYZD50[9]);
namespace SkICC {
static inline sk_sp<SkData> WriteToICC(const SkColorSpaceTransferFn& fn,
const SkMatrix44& toXYZD50) {
if (toXYZD50.get(3,0) == 0 && toXYZD50.get(3,1) == 0 && toXYZD50.get(3,2) == 0 &&
toXYZD50.get(3,3) == 1 &&
toXYZD50.get(0,3) == 0 && toXYZD50.get(1,3) == 0 && toXYZD50.get(2,3) == 0) {
float m33[9];
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++) {
m33[3*r+c] = toXYZD50.get(r,c);
}
return SkWriteICCProfile(fn, m33);
}
return nullptr;
}
}
SK_API sk_sp<SkData> SkWriteICCProfile(const skcms_TransferFunction&,
const skcms_Matrix3x3& toXYZD50);
#endif//SkICC_DEFINED

Просмотреть файл

@ -145,11 +145,11 @@ public:
*/
static sk_sp<SkImage> MakeFromBitmap(const SkBitmap& bitmap);
/** Creates SkImage from data returned by imageGenerator. Generated data is owned by SkImage and may not
be shared or accessed.
/** Creates SkImage from data returned by imageGenerator. Generated data is owned by SkImage and
may not be shared or accessed.
subset allows selecting a portion of the full image. Pass nullptr to select the entire image;
otherwise, subset must be contained by image bounds.
subset allows selecting a portion of the full image. Pass nullptr to select the entire
image; otherwise, subset must be contained by image bounds.
SkImage is returned if generator data is valid. Valid data parameters vary by type of data
and platform.
@ -164,8 +164,8 @@ public:
const SkIRect* subset = nullptr);
/** Creates SkImage from encoded data.
subset allows selecting a portion of the full image. Pass nullptr to select the entire image;
otherwise, subset must be contained by image bounds.
subset allows selecting a portion of the full image. Pass nullptr to select the entire
image; otherwise, subset must be contained by image bounds.
SkImage is returned if format of the encoded data is recognized and supported.
Recognized formats vary by platform.
@ -176,6 +176,27 @@ public:
*/
static sk_sp<SkImage> MakeFromEncoded(sk_sp<SkData> encoded, const SkIRect* subset = nullptr);
// Experimental
enum CompressionType {
kETC1_CompressionType,
kLast_CompressionType = kETC1_CompressionType,
};
/** Creates a GPU-backed SkImage from compressed data.
SkImage is returned if format of the compressed data is supported.
Supported formats vary by platform.
@param context GPU context
@param data compressed data to store in SkImage
@param width width of full SkImage
@param height height of full SkImage
@param type type of compression used
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromCompressed(GrContext* context, sk_sp<SkData> data,
int width, int height, CompressionType type);
/** User function called when supplied texture may be deleted.
*/
typedef void (*TextureReleaseProc)(ReleaseContext releaseContext);
@ -191,8 +212,9 @@ public:
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kRGB_888x_SkColorType, kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
@ -221,10 +243,12 @@ public:
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType,
kRGB_101010x_SkColorType, kGray_8_SkColorType,
kRGBA_F16_SkColorType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@ -310,10 +334,12 @@ public:
@param backendTexture texture residing on GPU
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType,
kRGB_101010x_SkColorType, kGray_8_SkColorType,
kRGBA_F16_SkColorType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@ -334,10 +360,10 @@ public:
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of (up to four) YUVA textures on GPU which contain the,
@param yuvaTextures array of (up to four) YUVA textures on GPU which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which texture (in 'yuvaTextures') and channel
(in the specified texture) maps to each of Y, U, V, and A.
@param yuvaIndices array indicating which texture in yuvaTextures, and channel
in that texture, maps to each component of YUVA.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of: kBottomLeft_GrSurfaceOrigin,
kTopLeft_GrSurfaceOrigin
@ -359,10 +385,10 @@ public:
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of (up to four) YUVA textures on GPU which contain the,
@param yuvaTextures array of (up to four) YUVA textures on GPU which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which texture (in 'yuvaTextures') and channel
(in the specified texture) maps to each of Y, U, V, and A.
@param yuvaIndices array indicating which texture in yuvaTextures, and channel
in that texture, maps to each component of YUVA.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of: kBottomLeft_GrSurfaceOrigin,
kTopLeft_GrSurfaceOrigin
@ -380,36 +406,71 @@ public:
const GrBackendTexture& backendTexture,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of yuvTextures, an array of textures on GPU.
yuvTextures contain pixels for YUV planes of SkImage. Returned SkImage has the dimensions
yuvTextures[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
/** Creates an SkImage by storing the specified YUVA planes into an image, to be rendered
via multitexturing.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param imageColorSpace range of colors; may be nullptr
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvaTextures array of (up to four) YUVA textures on GPU which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which texture in yuvaTextures, and channel
in that texture, maps to each component of YUVA.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of: kBottomLeft_GrSurfaceOrigin,
kTopLeft_GrSurfaceOrigin
@param imageColorSpace range of colors of the resulting image; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVATextures(GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvaTextures[],
const SkYUVAIndex yuvaIndices[4],
SkISize imageSize,
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from pixmap array representing YUVA data.
SkImage is uploaded to GPU back-end using context.
Each GrBackendTexture created from yuvaPixmaps array is uploaded to match SkSurface
using SkColorSpace of SkPixmap. SkColorSpace of SkImage is determined by imageColorSpace.
SkImage is returned referring to GPU back-end if context is not nullptr and
format of data is recognized and supported. Otherwise, nullptr is returned.
Recognized GPU formats vary by platform and GPU back-end.
@param context GPU context
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvaPixmaps array of (up to four) SkPixmap which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which pixmap in yuvaPixmaps, and channel
in that pixmap, maps to each component of YUVA.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of:
kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param buildMips create internal YUVA textures as mip map if true
@param limitToMaxTextureSize downscale image to GPU maximum texture size, if necessary
@param imageColorSpace range of colors of the resulting image; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVAPixmaps(
GrContext* context, SkYUVColorSpace yuvColorSpace, const SkPixmap yuvaPixmaps[],
const SkYUVAIndex yuvaIndices[4], SkISize imageSize, GrSurfaceOrigin imageOrigin,
bool buildMips, bool limitToMaxTextureSize = false,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** To be deprecated.
*/
static sk_sp<SkImage> MakeFromYUVTexturesCopy(GrContext* context, SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvTextures[3],
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of yuvTextures, an array of textures on GPU.
yuvTextures contain pixels for YUV planes of SkImage. Returned SkImage has the dimensions
yuvTextures[0] and stores pixels in backendTexture. yuvColorSpace describes how YUV colors
convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param backendTexture the resource that stores the final pixels
@param imageColorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
/** To be deprecated.
*/
static sk_sp<SkImage> MakeFromYUVTexturesCopyWithExternalBackend(
GrContext* context, SkYUVColorSpace yuvColorSpace,
@ -486,7 +547,7 @@ public:
sk_sp<SkColorSpace> colorSpace);
#if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
/** (see skbug.com/7447)
/** (See Skia bug 7447)
Creates SkImage from Android hardware buffer.
Returned SkImage takes a reference on the buffer.
@ -505,6 +566,22 @@ public:
SkAlphaType alphaType = kPremul_SkAlphaType,
sk_sp<SkColorSpace> colorSpace = nullptr,
GrSurfaceOrigin surfaceOrigin = kTopLeft_GrSurfaceOrigin);
/** Creates SkImage from Android hardware buffer and uploads the data from the SkPixmap to it.
Returned SkImage takes a reference on the buffer.
Only available on Android, when __ANDROID_API__ is defined to be 26 or greater.
@param pixmap SkPixmap that contains data to be uploaded to the AHardwareBuffer
@param hardwareBuffer AHardwareBuffer Android hardware buffer
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromAHardwareBufferWithData(
GrContext* context,
const SkPixmap& pixmap,
AHardwareBuffer* hardwareBuffer,
GrSurfaceOrigin surfaceOrigin = kTopLeft_GrSurfaceOrigin);
#endif
/** Returns pixel count in each row.
@ -770,8 +847,8 @@ public:
filterQuality kNone_SkFilterQuality is fastest, typically implemented with
nearest neighbor filter. kLow_SkFilterQuality is typically implemented with
bilerp filter. kMedium_SkFilterQuality is typically implemented with
bilerp filter, and Filter_Quality_MipMap when size is reduced.
kHigh_SkFilterQuality is slowest, typically implemented with Filter_Quality_BiCubic.
bilerp filter, and mip-map filter when size is reduced.
kHigh_SkFilterQuality is slowest, typically implemented with bicubic filter.
If cachingHint is kAllow_CachingHint, pixels may be retained locally.
If cachingHint is kDisallow_CachingHint, pixels are not added to the local cache.
@ -892,6 +969,7 @@ public:
of GPU texture returned. offset translates the returned SkImage to keep subsequent
animation frames aligned with respect to each other.
@param context the GrContext in play - if it exists
@param filter how SkImage is sampled when transformed
@param subset bounds of SkImage processed by filter
@param clipBounds expected bounds of filtered SkImage
@ -899,6 +977,13 @@ public:
@param offset storage for returned SkImage translation
@return filtered SkImage, or nullptr
*/
sk_sp<SkImage> makeWithFilter(GrContext* context,
const SkImageFilter* filter, const SkIRect& subset,
const SkIRect& clipBounds, SkIRect* outSubset,
SkIPoint* offset) const;
/** To be deprecated.
*/
sk_sp<SkImage> makeWithFilter(const SkImageFilter* filter, const SkIRect& subset,
const SkIRect& clipBounds, SkIRect* outSubset,
SkIPoint* offset) const;
@ -934,20 +1019,24 @@ public:
GrBackendTexture* backendTexture,
BackendTextureReleaseProc* backendTextureReleaseProc);
/** Deprecated.
*/
enum LegacyBitmapMode {
kRO_LegacyBitmapMode, //!< returned bitmap is read-only and immutable
};
/** Creates raster SkBitmap with same pixels as SkImage. If legacyBitmapMode is
/** Deprecated.
Creates raster SkBitmap with same pixels as SkImage. If legacyBitmapMode is
kRO_LegacyBitmapMode, returned bitmap is read-only and immutable.
Returns true if SkBitmap is stored in bitmap. Returns false and resets bitmap if
SkBitmap write did not succeed.
@param bitmap storage for legacy SkBitmap
@param legacyBitmapMode to be deprecated
@param legacyBitmapMode bitmap is read-only and immutable
@return true if SkBitmap was created
*/
bool asLegacyBitmap(SkBitmap* bitmap, LegacyBitmapMode legacyBitmapMode = kRO_LegacyBitmapMode) const;
bool asLegacyBitmap(SkBitmap* bitmap,
LegacyBitmapMode legacyBitmapMode = kRO_LegacyBitmapMode) const;
/** Returns true if SkImage is backed by an image-generator or other service that creates
and caches its pixels or texture on-demand.
@ -968,6 +1057,19 @@ public:
*/
sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> target) const;
/** Experimental.
Creates SkImage in target SkColorType and SkColorSpace.
Returns nullptr if SkImage could not be created.
Returns original SkImage if it is in target SkColorType and SkColorSpace.
@param targetColorType SkColorType of returned SkImage
@param targetColorSpace SkColorSpace of returned SkImage
@return created SkImage in target SkColorType and SkColorSpace
*/
sk_sp<SkImage> makeColorTypeAndColorSpace(SkColorType targetColorType,
sk_sp<SkColorSpace> targetColorSpace) const;
private:
SkImage(int width, int height, uint32_t uniqueID);
friend class SkImage_Base;

Просмотреть файл

@ -27,7 +27,8 @@
* Will always return false if Skia is compiled without image
* encoders.
*
* Note that webp encodes will use webp lossy compression.
* For SkEncodedImageFormat::kWEBP, if quality is 100, it will use lossless compression. Otherwise
* it will use lossy.
*
* For examples of encoding an image to a file or to a block of memory,
* see tools/sk_tool_utils.h.
@ -56,7 +57,8 @@ inline bool SkEncodeImage(SkWStream* dst, const SkBitmap& src, SkEncodedImageFor
* Will always return nullptr if Skia is compiled without image
* encoders.
*
* Note that webp encodes will use webp lossy compression.
* For SkEncodedImageFormat::kWEBP, if quality is 100, it will use lossless compression. Otherwise
* it will use lossy.
*/
SK_API sk_sp<SkData> SkEncodePixmap(const SkPixmap& src, SkEncodedImageFormat format, int quality);

Просмотреть файл

@ -18,11 +18,11 @@
#include "SkMatrix.h"
#include "SkRect.h"
class GrContext;
class GrFragmentProcessor;
class SkColorFilter;
class SkColorSpaceXformer;
struct SkIPoint;
class GrRecordingContext;
class SkSpecialImage;
class SkImageFilterCache;
struct SkImageFilterCacheKey;
@ -167,7 +167,7 @@ public:
MapDirection, const SkIRect* inputRect = nullptr) const;
#if SK_SUPPORT_GPU
static sk_sp<SkSpecialImage> DrawWithFP(GrContext* context,
static sk_sp<SkSpecialImage> DrawWithFP(GrRecordingContext* context,
std::unique_ptr<GrFragmentProcessor> fp,
const SkIRect& bounds,
const OutputProperties& outputProperties);
@ -252,7 +252,7 @@ public:
SkFilterQuality quality,
sk_sp<SkImageFilter> input);
static void InitializeFlattenables();
static void RegisterFlattenables();
static SkFlattenable::Type GetFlattenableType() {
return kSkImageFilter_Type;

Просмотреть файл

@ -12,10 +12,10 @@
#include "SkColor.h"
#include "SkImage.h"
#include "SkImageInfo.h"
#include "SkYUVSizeInfo.h"
#include "SkYUVAIndex.h"
#include "SkYUVASizeInfo.h"
class GrContext;
class GrContextThreadSafeProxy;
class GrRecordingContext;
class GrTextureProxy;
class GrSamplerState;
class SkBitmap;
@ -86,23 +86,30 @@ public:
* If decoding to YUV is supported, this returns true. Otherwise, this
* returns false and does not modify any of the parameters.
*
* @param sizeInfo Output parameter indicating the sizes and required
* allocation widths of the Y, U, and V planes.
* @param colorSpace Output parameter.
* @param sizeInfo Output parameter indicating the sizes and required
* allocation widths of the Y, U, V, and A planes.
* @param yuvaIndices How the YUVA planes are organized/used
* @param colorSpace Output parameter.
*/
bool queryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const;
bool queryYUVA8(SkYUVASizeInfo* sizeInfo,
SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
SkYUVColorSpace* colorSpace) const;
/**
* Returns true on success and false on failure.
* This always attempts to perform a full decode. If the client only
* wants size, it should call queryYUV8().
* wants size, it should call queryYUVA8().
*
* @param sizeInfo Needs to exactly match the values returned by the
* query, except the WidthBytes may be larger than the
* recommendation (but not smaller).
* @param planes Memory for each of the Y, U, and V planes.
* @param sizeInfo Needs to exactly match the values returned by the
* query, except the WidthBytes may be larger than the
* recommendation (but not smaller).
* @param yuvaIndices Needs to exactly match the values returned by the query.
* @param planes Memory for the Y, U, V, and A planes. Note that, depending on the
* settings in yuvaIndices, anywhere from 1..4 planes could be returned.
*/
bool getYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]);
bool getYUVA8Planes(const SkYUVASizeInfo& sizeInfo,
const SkYUVAIndex yuvaIndices[SkYUVAIndex::kIndexCount],
void* planes[]);
#if SK_SUPPORT_GPU
/**
@ -132,7 +139,7 @@ public:
* the generator is allowed to return a non mipped proxy, but this will have some additional
* overhead in later allocating mips and copying of the base layer.
*/
sk_sp<GrTextureProxy> generateTexture(GrContext*, const SkImageInfo& info,
sk_sp<GrTextureProxy> generateTexture(GrRecordingContext*, const SkImageInfo& info,
const SkIPoint& origin,
bool willNeedMipMaps);
#endif
@ -163,9 +170,10 @@ protected:
struct Options {};
virtual bool onGetPixels(const SkImageInfo&, void*, size_t, const Options&) { return false; }
virtual bool onIsValid(GrContext*) const { return true; }
virtual bool onQueryYUV8(SkYUVSizeInfo*, SkYUVColorSpace*) const { return false; }
virtual bool onGetYUV8Planes(const SkYUVSizeInfo&, void*[3] /*planes*/) { return false; }
virtual bool onQueryYUVA8(SkYUVASizeInfo*, SkYUVAIndex[SkYUVAIndex::kIndexCount],
SkYUVColorSpace*) const { return false; }
virtual bool onGetYUVA8Planes(const SkYUVASizeInfo&, const SkYUVAIndex[SkYUVAIndex::kIndexCount],
void*[4] /*planes*/) { return false; }
#if SK_SUPPORT_GPU
enum class TexGenType {
kNone, //image generator does not implement onGenerateTexture
@ -174,7 +182,8 @@ protected:
};
virtual TexGenType onCanGenerateTexture() const { return TexGenType::kNone; }
virtual sk_sp<GrTextureProxy> onGenerateTexture(GrContext*, const SkImageInfo&, const SkIPoint&,
virtual sk_sp<GrTextureProxy> onGenerateTexture(GrRecordingContext*, const SkImageInfo&,
const SkIPoint&,
bool willNeedMipMaps); // returns nullptr
#endif

Просмотреть файл

@ -92,7 +92,8 @@ enum SkColorType {
kRGBA_1010102_SkColorType, //!< 10 bits for red, green, blue; 2 bits for alpha; in 32-bit word
kRGB_101010x_SkColorType, //!< pixel with 10 bits each for red, green, blue; in 32-bit word
kGray_8_SkColorType, //!< pixel with grayscale level in 8-bit byte
kRGBA_F16_SkColorType, //!< pixel with half floats for red, green, blue, alpha; in 64-bit word
kRGBA_F16Norm_SkColorType, //!< pixel with half floats in [0,1] for red, green, blue, alpha; in 64-bit word
kRGBA_F16_SkColorType, //!< pixel with half floats for red, green, blue, alpha; in 64-bit word
kRGBA_F32_SkColorType, //!< pixel using C float for red, green, blue, alpha; in 128-bit word
kLastEnum_SkColorType = kRGBA_F32_SkColorType,//!< last valid value
@ -461,8 +462,8 @@ public:
@param newColorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType,
kRGB_101010x_SkColorType, kGray_8_SkColorType, kRGBA_F16_SkColorType
@return created SkImageInfo
*/
SkImageInfo makeColorType(SkColorType newColorType) const {

Просмотреть файл

@ -70,7 +70,7 @@ public:
}
private:
static void InitializeFlattenables();
static void RegisterFlattenables();
friend class SkFlattenable;
};

Просмотреть файл

@ -555,8 +555,8 @@ public:
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void setScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py);
@ -573,8 +573,8 @@ public:
Positive degrees rotates clockwise.
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void setRotate(SkScalar degrees, SkScalar px, SkScalar py);
@ -593,8 +593,8 @@ public:
@param sinValue rotation vector x-axis component
@param cosValue rotation vector y-axis component
@param px pivot x-axis
@param py pivot y-axis
@param px pivot on x-axis
@param py pivot on y-axis
*/
void setSinCos(SkScalar sinValue, SkScalar cosValue,
SkScalar px, SkScalar py);
@ -625,8 +625,8 @@ public:
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void setSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py);
@ -699,8 +699,8 @@ public:
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void preScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py);
@ -751,8 +751,8 @@ public:
| G H I | | 0 0 1 | | Gc+Hs -Gs+Hc G*dx+H*dy+I |
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void preRotate(SkScalar degrees, SkScalar px, SkScalar py);
@ -806,8 +806,8 @@ public:
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void preSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py);
@ -894,8 +894,8 @@ public:
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void postScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py);
@ -974,8 +974,8 @@ public:
|0 0 1| |P Q R| | P Q R|
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void postRotate(SkScalar degrees, SkScalar px, SkScalar py);
@ -1029,8 +1029,8 @@ public:
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
@param px pivot on x-axis
@param py pivot on y-axis
*/
void postSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py);
@ -1165,9 +1165,9 @@ public:
| 1 0 0 |
| 0 1 0 |
Affine 3x2 matrices in column major order are used by OpenGL and XPS.
Affine 3 by 2 matrices in column major order are used by OpenGL and XPS.
@param affine storage for 3x2 affine matrix
@param affine storage for 3 by 2 affine matrix
*/
static void SetAffineIdentity(SkScalar affine[6]);
@ -1178,7 +1178,7 @@ public:
If SkMatrix contains perspective, returns false and leaves affine unchanged.
@param affine storage for 3x2 affine matrix; may be nullptr
@param affine storage for 3 by 2 affine matrix; may be nullptr
@return true if SkMatrix does not contain perspective
*/
bool SK_WARN_UNUSED_RESULT asAffine(SkScalar affine[6]) const;
@ -1195,7 +1195,7 @@ public:
| skew-y scale-y translate-y |
| 0 0 1 |
@param affine 3x2 affine matrix
@param affine 3 by 2 affine matrix
*/
void setAffine(const SkScalar affine[6]);
@ -1225,12 +1225,7 @@ public:
@param src SkPoint to transform
@param count number of SkPoint to transform
*/
void mapPoints(SkPoint dst[], const SkPoint src[], int count) const {
SkASSERT((dst && src && count > 0) || 0 == count);
// no partial overlap
SkASSERT(src == dst || &dst[count] <= &src[0] || &src[count] <= &dst[0]);
this->getMapPtsProc()(*this, dst, src, count);
}
void mapPoints(SkPoint dst[], const SkPoint src[], int count) const;
/** Maps pts SkPoint array of length count in place. SkPoint are mapped by multiplying
each SkPoint by SkMatrix. Given:
@ -1294,10 +1289,7 @@ public:
@param y y-axis value of SkPoint to map
@param result storage for mapped SkPoint
*/
void mapXY(SkScalar x, SkScalar y, SkPoint* result) const {
SkASSERT(result);
this->getMapXYProc()(*this, x, y, result);
}
void mapXY(SkScalar x, SkScalar y, SkPoint* result) const;
/** Returns SkPoint (x, y) multiplied by SkMatrix. Given:
@ -1317,7 +1309,7 @@ public:
*/
SkPoint mapXY(SkScalar x, SkScalar y) const {
SkPoint result;
this->getMapXYProc()(*this, x, y, &result);
this->mapXY(x,y, &result);
return result;
}
@ -1377,7 +1369,7 @@ public:
this->mapVectors(vecs, vecs, count);
}
/** Maps vector (x, y) to result. Vector is mapped by multiplying by SkMatrix,
/** Maps vector (dx, dy) to result. Vector is mapped by multiplying by SkMatrix,
treating SkMatrix translation as zero. Given:
| A B 0 | | dx |
@ -1399,7 +1391,7 @@ public:
this->mapVectors(result, &vec, 1);
}
/** Returns vector (x, y) multiplied by SkMatrix, treating SkMatrix translation as zero.
/** Returns vector (dx, dy) multiplied by SkMatrix, treating SkMatrix translation as zero.
Given:
| A B 0 | | dx |
@ -1439,7 +1431,7 @@ public:
Returned value is the same as calling rectStaysRect().
@param rect rectangle to map, and storage for bounds of mapped corners
@return true if result is equivalent to mapped src
@return true if result is equivalent to mapped rect
*/
bool mapRect(SkRect* rect) const {
return this->mapRect(rect, *rect);

Просмотреть файл

@ -5,5 +5,5 @@
* found in the LICENSE file.
*/
#ifndef SK_MILESTONE
#define SK_MILESTONE 71
#define SK_MILESTONE 74
#endif

Просмотреть файл

@ -21,16 +21,12 @@ public:
/* Does not take ownership of canvas */
SkOverdrawCanvas(SkCanvas*);
void onDrawText(const void*, size_t, SkScalar, SkScalar, const SkPaint&) override;
void onDrawPosText(const void*, size_t, const SkPoint[], const SkPaint&) override;
void onDrawPosTextH(const void*, size_t, const SkScalar[], SkScalar, const SkPaint&) override;
void onDrawTextRSXform(const void*, size_t, const SkRSXform[], const SkRect*,
const SkPaint&) override;
void onDrawTextBlob(const SkTextBlob*, SkScalar, SkScalar, const SkPaint&) override;
void onDrawPatch(const SkPoint[12], const SkColor[4], const SkPoint[4], SkBlendMode,
const SkPaint&) override;
void onDrawPaint(const SkPaint&) override;
void onDrawRect(const SkRect&, const SkPaint&) override;
void onDrawEdgeAARect(const SkRect&, SkCanvas::QuadAAFlags, SkColor, SkBlendMode) override;
void onDrawRegion(const SkRegion&, const SkPaint&) override;
void onDrawOval(const SkRect&, const SkPaint&) override;
void onDrawArc(const SkRect&, SkScalar, SkScalar, bool, const SkPaint&) override;
@ -47,6 +43,7 @@ public:
SrcRectConstraint) override;
void onDrawImageNine(const SkImage*, const SkIRect&, const SkRect&, const SkPaint*) override;
void onDrawImageLattice(const SkImage*, const Lattice&, const SkRect&, const SkPaint*) override;
void onDrawImageSet(const ImageSetEntry[], int count, SkFilterQuality, SkBlendMode) override;
void onDrawBitmap(const SkBitmap&, SkScalar, SkScalar, const SkPaint*) override;
void onDrawBitmapRect(const SkBitmap&, const SkRect*, const SkRect&, const SkPaint*,
SrcRectConstraint) override;
@ -60,8 +57,8 @@ public:
void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override;
private:
void drawPosTextCommon(const void*, size_t, const SkScalar[], int, const SkPoint&,
const SkPaint&);
void drawPosTextCommon(const SkGlyphID[], int, const SkScalar[], int, const SkPoint&,
const SkFont&, const SkPaint&);
inline SkPaint overdrawPaint(const SkPaint& paint);

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -63,12 +63,12 @@ public:
kCW_Direction travel clockwise; the same added with kCCW_Direction
travel counterclockwise.
*/
enum Direction {
enum Direction : int {
kCW_Direction, //!< contour travels clockwise
kCCW_Direction, //!< contour travels counterclockwise
};
/** Constucts an empty SkPath. By default, SkPath has no verbs, no SkPoint, and no weights.
/** Constructs an empty SkPath. By default, SkPath has no verbs, no SkPoint, and no weights.
SkPath::FillType is set to kWinding_FillType.
@return empty SkPath
@ -160,13 +160,6 @@ public:
*/
bool interpolate(const SkPath& ending, SkScalar weight, SkPath* out) const;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** To be deprecated soon.
Only valid for Android framework.
*/
bool unique() const { return fPathRef->unique(); }
#endif
/** \enum SkPath::FillType
FillType selects the rule used to fill SkPath. SkPath set to kWinding_FillType
fills if the sum of contour edges is not zero, where clockwise edges add one, and
@ -240,7 +233,8 @@ public:
@return computed or stored SkPath::Convexity
*/
Convexity getConvexity() const {
for (Convexity convexity = fConvexity.load(); kUnknown_Convexity != convexity; ) {
Convexity convexity = this->getConvexityOrUnknown();
if (convexity != kUnknown_Convexity) {
return convexity;
}
return this->internalGetConvexity();
@ -251,7 +245,7 @@ public:
@return stored SkPath::Convexity
*/
Convexity getConvexityOrUnknown() const { return (Convexity)fConvexity; }
Convexity getConvexityOrUnknown() const { return fConvexity.load(std::memory_order_relaxed); }
/** Stores convexity so that it is later returned by getConvexity() or getConvexityOrUnknown().
convexity may differ from getConvexity(), although setting an incorrect value may
@ -289,7 +283,8 @@ public:
*/
bool isOval(SkRect* bounds) const;
/** Returns true if this path is recognized as a SkRRect (but not an oval/circle or rect).
/** Returns true if path is representable as SkRRect.
Returns false if path is representable as oval, circle, or SkRect.
rrect receives bounds of SkRRect.
@ -590,8 +585,8 @@ public:
lineTo() appends kMove_Verb to verb array and (0, 0) to SkPoint array, if needed.
lineTo() then appends kLine_Verb to verb array and (x, y) to SkPoint array.
@param x end of added line in x
@param y end of added line in y
@param x end of added line on x-axis
@param y end of added line on y-axis
@return reference to SkPath
*/
SkPath& lineTo(SkScalar x, SkScalar y);
@ -631,10 +626,10 @@ public:
then appends kQuad_Verb to verb array; and (x1, y1), (x2, y2)
to SkPoint array.
@param x1 control SkPoint of quad in x
@param y1 control SkPoint of quad in y
@param x2 end SkPoint of quad in x
@param y2 end SkPoint of quad in y
@param x1 control SkPoint of quad on x-axis
@param y1 control SkPoint of quad on y-axis
@param x2 end SkPoint of quad on x-axis
@param y2 end SkPoint of quad on y-axis
@return reference to SkPath
*/
SkPath& quadTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2);
@ -689,10 +684,10 @@ public:
If w is not finite, appends kLine_Verb twice to verb array, and
(x1, y1), (x2, y2) to SkPoint array.
@param x1 control SkPoint of conic in x
@param y1 control SkPoint of conic in y
@param x2 end SkPoint of conic in x
@param y2 end SkPoint of conic in y
@param x1 control SkPoint of conic on x-axis
@param y1 control SkPoint of conic on y-axis
@param x2 end SkPoint of conic on x-axis
@param y2 end SkPoint of conic on y-axis
@param w weight of added conic
@return reference to SkPath
*/
@ -759,12 +754,12 @@ public:
then appends kCubic_Verb to verb array; and (x1, y1), (x2, y2), (x3, y3)
to SkPoint array.
@param x1 first control SkPoint of cubic in x
@param y1 first control SkPoint of cubic in y
@param x2 second control SkPoint of cubic in x
@param y2 second control SkPoint of cubic in y
@param x3 end SkPoint of cubic in x
@param y3 end SkPoint of cubic in y
@param x1 first control SkPoint of cubic on x-axis
@param y1 first control SkPoint of cubic on y-axis
@param x2 second control SkPoint of cubic on x-axis
@param y2 second control SkPoint of cubic on y-axis
@param x3 end SkPoint of cubic on x-axis
@param y3 end SkPoint of cubic on y-axis
@return reference to SkPath
*/
SkPath& cubicTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2,
@ -799,16 +794,16 @@ public:
Cubic end is last point plus vector (dx2, dy2).
Function name stands for "relative cubic to".
@param x1 offset from last point to first cubic control on x-axis
@param y1 offset from last point to first cubic control on y-axis
@param x2 offset from last point to second cubic control on x-axis
@param y2 offset from last point to second cubic control on y-axis
@param x3 offset from last point to cubic end on x-axis
@param y3 offset from last point to cubic end on y-axis
@param dx1 offset from last point to first cubic control on x-axis
@param dy1 offset from last point to first cubic control on y-axis
@param dx2 offset from last point to second cubic control on x-axis
@param dy2 offset from last point to second cubic control on y-axis
@param dx3 offset from last point to cubic end on x-axis
@param dy3 offset from last point to cubic end on y-axis
@return reference to SkPath
*/
SkPath& rCubicTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2,
SkScalar x3, SkScalar y3);
SkPath& rCubicTo(SkScalar dx1, SkScalar dy1, SkScalar dx2, SkScalar dy2,
SkScalar dx3, SkScalar dy3);
/** Appends arc to SkPath. Arc added is part of ellipse
bounded by oval, from startAngle through sweepAngle. Both startAngle and
@ -829,9 +824,18 @@ public:
/** Appends arc to SkPath, after appending line if needed. Arc is implemented by conic
weighted to describe part of circle. Arc is contained by tangent from
last SkPath point (x0, y0) to (x1, y1), and tangent from (x1, y1) to (x2, y2). Arc
last SkPath point to (x1, y1), and tangent from (x1, y1) to (x2, y2). Arc
is part of circle sized to radius, positioned so it touches both tangent lines.
If last Path Point does not start Arc, arcTo appends connecting Line to Path.
The length of Vector from (x1, y1) to (x2, y2) does not affect Arc.
Arc sweep is always less than 180 degrees. If radius is zero, or if
tangents are nearly parallel, arcTo appends Line from last Path Point to (x1, y1).
arcTo appends at most one Line and one conic.
arcTo implements the functionality of PostScript arct and HTML Canvas arcTo.
@param x1 x-axis value common to pair of tangents
@param y1 y-axis value common to pair of tangents
@param x2 x-axis value end of second tangent
@ -853,7 +857,7 @@ public:
tangents are nearly parallel, arcTo() appends line from last SkPath SkPoint to p1.
arcTo() appends at most one line and one conic.
arcTo() implements the functionality of PostScript_Arct and HTML_Canvas_ArcTo.
arcTo() implements the functionality of PostScript arct and HTML Canvas arcTo.
@param p1 SkPoint common to pair of tangents
@param p2 end of second tangent
@ -884,12 +888,12 @@ public:
too small.
arcTo() appends up to four conic curves.
arcTo() implements the functionality of svg arc, although SVG "sweep-flag" value
is opposite the integer value of sweep; SVG "sweep-flag" uses 1 for clockwise,
while kCW_Direction cast to int is zero.
arcTo() implements the functionality of SVG arc, although SVG sweep-flag value
is opposite the integer value of sweep; SVG sweep-flag uses 1 for clockwise,
while kCW_Direction cast to int is zero.
@param rx radius in x before x-axis rotation
@param ry radius in y before x-axis rotation
@param rx radius on x-axis before x-axis rotation
@param ry radius on y-axis before x-axis rotation
@param xAxisRotate x-axis rotation in degrees; positive values are clockwise
@param largeArc chooses smaller or larger arc
@param sweep chooses clockwise or counterclockwise arc
@ -907,13 +911,13 @@ public:
and smaller or larger.
Arc sweep is always less than 360 degrees. arcTo() appends line to xy if either
radii are zero, or if last SkPath SkPoint equals (x, y). arcTo() scales radii r to fit
last SkPath SkPoint and xy if both are greater than zero but too small to describe
radii are zero, or if last SkPath SkPoint equals (xy.fX, xy.fY). arcTo() scales radii r to
fit last SkPath SkPoint and xy if both are greater than zero but too small to describe
an arc.
arcTo() appends up to four conic curves.
arcTo() implements the functionality of svg arc, although SVG "sweep-flag" value is
opposite the integer value of sweep; SVG "sweep-flag" uses 1 for clockwise, while
arcTo() implements the functionality of SVG arc, although SVG sweep-flag value is
opposite the integer value of sweep; SVG sweep-flag uses 1 for clockwise, while
kCW_Direction cast to int is zero.
@param r radii on axes before x-axis rotation
@ -930,8 +934,8 @@ public:
/** Appends arc to SkPath, relative to last SkPath SkPoint. Arc is implemented by one or
more conic, weighted to describe part of oval with radii (rx, ry) rotated by
xAxisRotate degrees. Arc curves from last SkPath SkPoint (x0, y0) to end SkPoint:
(x0 + dx, y0 + dy), choosing one of four possible routes: clockwise or
xAxisRotate degrees. Arc curves from last SkPath SkPoint to relative end SkPoint:
(dx, dy), choosing one of four possible routes: clockwise or
counterclockwise, and smaller or larger. If SkPath is empty, the start arc SkPoint
is (0, 0).
@ -1046,8 +1050,8 @@ public:
If false, rect and dirs are unchanged.
If true, rect and dirs are written to if not nullptr:
setting rect[0] to outer SkRect, and rect[1] to inner SkRect;
setting dirs[0] to SkPath::Direction of outer SkRect, and dirs[1] to SkPath::Direction of inner
SkRect.
setting dirs[0] to SkPath::Direction of outer SkRect, and dirs[1] to SkPath::Direction of
inner SkRect.
@param rect storage for SkRect pair; may be nullptr
@param dirs storage for SkPath::Direction pair; may be nullptr
@ -1158,7 +1162,7 @@ public:
corners fit. If rx or ry is less than or equal to zero, addRoundRect() appends
SkRect rect to SkPath.
After appending, SkPath may be empty, or may contain: SkRect, oval, or RoundRect.
After appending, SkPath may be empty, or may contain: SkRect, oval, or SkRRect.
@param rect bounds of SkRRect
@param rx x-axis radius of rounded corners on the SkRRect
@ -1403,15 +1407,16 @@ public:
class SK_API Iter {
public:
/** Initializes SkPath::Iter with an empty SkPath. next() on SkPath::Iter returns kDone_Verb.
/** Initializes SkPath::Iter with an empty SkPath. next() on SkPath::Iter returns
kDone_Verb.
Call setPath to initialize SkPath::Iter at a later time.
@return SkPath::Iter of empty SkPath
*/
Iter();
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in path.
If forceClose is true, SkPath::Iter will add kLine_Verb and kClose_Verb after each
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in
path. If forceClose is true, SkPath::Iter will add kLine_Verb and kClose_Verb after each
open contour. path is not altered.
@param path SkPath to iterate
@ -1420,8 +1425,8 @@ public:
*/
Iter(const SkPath& path, bool forceClose);
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in path.
If forceClose is true, SkPath::Iter will add kLine_Verb and kClose_Verb after each
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in
path. If forceClose is true, SkPath::Iter will add kLine_Verb and kClose_Verb after each
open contour. path is not altered.
@param path SkPath to iterate
@ -1530,7 +1535,8 @@ public:
setPath(path);
}
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in path.
/** Sets SkPath::Iter to return elements of verb array, SkPoint array, and conic weight in
path.
@param path SkPath to iterate
*/
@ -1651,20 +1657,19 @@ public:
*/
size_t readFromMemory(const void* buffer, size_t length);
/** (see skbug.com/1762)
/** (See Skia bug 1762.)
Returns a non-zero, globally unique value. A different value is returned
if verb array, SkPoint array, or conic weight changes.
Setting SkPath::FillType does not change generation id.
Setting SkPath::FillType does not change generation identifier.
Each time the path is modified, a different generation id will be returned.
SkPath::FillType does affect generation id on Android framework.
Each time the path is modified, a different generation identifier will be returned.
SkPath::FillType does affect generation identifier on Android framework.
@return non-zero, globally unique value
*/
uint32_t getGenerationID() const;
#ifdef SK_SUPPORT_DIRECT_PATHREF_VALIDATION
/** Returns if SkPath data is consistent. Corrupt SkPath data is detected if
internal values are out of range or internal storage does not match
array dimensions.
@ -1672,19 +1677,15 @@ public:
@return true if SkPath data is consistent
*/
bool isValid() const { return this->isValidImpl() && fPathRef->isValid(); }
#else
bool isValid() const { return this->isValidImpl(); }
bool pathRefIsValid() const { return fPathRef->isValid(); }
#endif
private:
sk_sp<SkPathRef> fPathRef;
int fLastMoveToIndex;
mutable SkAtomic<Convexity, sk_memory_order_relaxed> fConvexity; // SkPath::Convexity
mutable SkAtomic<uint8_t, sk_memory_order_relaxed> fFirstDirection; // SkPathPriv::FirstDirection
uint8_t fFillType : 2;
uint8_t fIsVolatile : 1;
uint8_t fIsBadForDAA : 1;
sk_sp<SkPathRef> fPathRef;
int fLastMoveToIndex;
mutable std::atomic<Convexity> fConvexity;
mutable std::atomic<uint8_t> fFirstDirection; // really an SkPathPriv::FirstDirection
uint8_t fFillType : 2;
uint8_t fIsVolatile : 1;
uint8_t fIsBadForDAA : 1;
/** Resets all fields other than fPathRef to their initial 'empty' values.
* Assumes the caller has already emptied fPathRef.
@ -1756,6 +1757,12 @@ private:
void setPt(int index, SkScalar x, SkScalar y);
// Bottlenecks for working with fConvexity and fFirstDirection.
// Notice the setters are const... these are mutable atomic fields.
void setConvexity(Convexity) const;
void setFirstDirection(uint8_t) const;
uint8_t getFirstDirection() const;
friend class SkAutoPathBoundsUpdate;
friend class SkAutoDisableOvalCheck;
friend class SkAutoDisableDirectionCheck;

Просмотреть файл

@ -144,7 +144,7 @@ public:
DashType asADash(DashInfo* info) const;
static void InitializeFlattenables();
static void RegisterFlattenables();
static SkFlattenable::Type GetFlattenableType() {
return kSkPathEffect_Type;
@ -161,11 +161,6 @@ public:
kSkPathEffect_Type, data, size, procs).release()));
}
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/// Override for subclasses as appropriate.
virtual bool exposedInAndroidJavaAPI() const { return false; }
#endif
protected:
SkPathEffect() {}

Просмотреть файл

@ -8,30 +8,26 @@
#ifndef SkPathMeasure_DEFINED
#define SkPathMeasure_DEFINED
#include "../private/SkNoncopyable.h"
#include "../private/SkTDArray.h"
#include "SkContourMeasure.h"
#include "SkPath.h"
struct SkConic;
class SK_API SkPathMeasure : SkNoncopyable {
public:
SkPathMeasure();
/** Initialize the pathmeasure with the specified path. The path must remain valid
for the lifetime of the measure object, or until setPath() is called with
a different path (or null), since the measure object keeps a pointer to the
path object (does not copy its data).
resScale controls the precision of the measure. values > 1 increase the
precision (and possible slow down the computation).
*/
/** Initialize the pathmeasure with the specified path. The parts of the path that are needed
* are copied, so the client is free to modify/delete the path after this call.
*
* resScale controls the precision of the measure. values > 1 increase the
* precision (and possible slow down the computation).
*/
SkPathMeasure(const SkPath& path, bool forceClosed, SkScalar resScale = 1);
~SkPathMeasure();
/** Reset the pathmeasure with the specified path. The path must remain valid
for the lifetime of the measure object, or until setPath() is called with
a different path (or null), since the measure object keeps a pointer to the
path object (does not copy its data).
*/
/** Reset the pathmeasure with the specified path. The parts of the path that are needed
* are copied, so the client is free to modify/delete the path after this call..
*/
void setPath(const SkPath*, bool forceClosed);
/** Return the total length of the current contour, or 0 if no path
@ -83,43 +79,8 @@ public:
#endif
private:
SkPath::Iter fIter;
SkPath fPath;
SkScalar fTolerance;
SkScalar fLength; // relative to the current contour
unsigned fFirstPtIndex; // relative to the current contour
bool fIsClosed; // relative to the current contour
bool fForceClosed;
#if defined(IS_FUZZING_WITH_LIBFUZZER)
int fSubdivisionsMax;
#endif
struct Segment {
SkScalar fDistance; // total distance up to this point
unsigned fPtIndex; // index into the fPts array
unsigned fTValue : 30;
unsigned fType : 2; // actually the enum SkSegType
// See SkPathMeasurePriv.h
SkScalar getScalarT() const;
};
SkTDArray<Segment> fSegments;
SkTDArray<SkPoint> fPts; // Points used to define the segments
static const Segment* NextSegment(const Segment*);
void buildSegments();
SkScalar compute_quad_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, unsigned ptIndex);
SkScalar compute_conic_segs(const SkConic&, SkScalar distance,
int mint, const SkPoint& minPt,
int maxt, const SkPoint& maxPt, unsigned ptIndex);
SkScalar compute_cubic_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, unsigned ptIndex);
const Segment* distanceToSegment(SkScalar distance, SkScalar* t);
bool quad_too_curvy(const SkPoint pts[3]);
bool conic_too_curvy(const SkPoint& firstPt, const SkPoint& midTPt,const SkPoint& lastPt);
bool cheap_dist_exceeds_limit(const SkPoint& pt, SkScalar x, SkScalar y);
bool cubic_too_curvy(const SkPoint pts[4]);
SkContourMeasureIter fIter;
sk_sp<SkContourMeasure> fContour;
};
#endif

Просмотреть файл

@ -49,9 +49,9 @@ public:
if successful; otherwise, returns nullptr. Fails if data does not permit
constructing valid SkPicture.
procs.fPictureProc permits supplying a custom function to decode SkPicture.
If procs.fPictureProc is nullptr, default decoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
procs->fPictureProc permits supplying a custom function to decode SkPicture.
If procs->fPictureProc is nullptr, default decoding is used. procs->fPictureCtx
may be used to provide user context to procs->fPictureProc; procs->fPictureProc
is called with a pointer to data, data byte length, and user context.
@param stream container for serial data
@ -65,9 +65,9 @@ public:
if successful; otherwise, returns nullptr. Fails if data does not permit
constructing valid SkPicture.
procs.fPictureProc permits supplying a custom function to decode SkPicture.
If procs.fPictureProc is nullptr, default decoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
procs->fPictureProc permits supplying a custom function to decode SkPicture.
If procs->fPictureProc is nullptr, default decoding is used. procs->fPictureCtx
may be used to provide user context to procs->fPictureProc; procs->fPictureProc
is called with a pointer to data, data byte length, and user context.
@param data container for serial data
@ -148,14 +148,14 @@ public:
@return identifier for SkPicture
*/
uint32_t uniqueID() const;
uint32_t uniqueID() const { return fUniqueID; }
/** Returns storage containing SkData describing SkPicture, using optional custom
encoders.
procs.fPictureProc permits supplying a custom function to encode SkPicture.
If procs.fPictureProc is nullptr, default encoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
procs->fPictureProc permits supplying a custom function to encode SkPicture.
If procs->fPictureProc is nullptr, default encoding is used. procs->fPictureCtx
may be used to provide user context to procs->fPictureProc; procs->fPictureProc
is called with a pointer to SkPicture and user context.
@param procs custom serial data encoders; may be nullptr
@ -165,9 +165,9 @@ public:
/** Writes picture to stream, using optional custom encoders.
procs.fPictureProc permits supplying a custom function to encode SkPicture.
If procs.fPictureProc is nullptr, default encoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
procs->fPictureProc permits supplying a custom function to encode SkPicture.
If procs->fPictureProc is nullptr, default encoding is used. procs->fPictureCtx
may be used to provide user context to procs->fPictureProc; procs->fPictureProc
is called with a pointer to SkPicture and user context.
@param stream writable serial data stream
@ -263,10 +263,14 @@ private:
// V62: Don't negate size of custom encoded images (don't write origin x,y either)
// V63: Store image bounds (including origin) instead of just width/height to support subsets
// V64: Remove occluder feature from blur maskFilter
// V65: Float4 paint color
// V66: Add saveBehind
// V67: Blobs serialize fonts instead of paints
// V68: Paint doesn't serialize font-related stuff
// Only SKPs within the min/current picture version range (inclusive) can be read.
static const uint32_t MIN_PICTURE_VERSION = 56; // august 2017
static const uint32_t CURRENT_PICTURE_VERSION = 65;
static const uint32_t CURRENT_PICTURE_VERSION = 68;
static_assert(MIN_PICTURE_VERSION <= 62, "Remove kFontAxes_bad from SkFontDescriptor.cpp");
@ -278,7 +282,7 @@ private:
struct SkPictInfo createHeader() const;
class SkPictureData* backport() const;
mutable uint32_t fUniqueID;
uint32_t fUniqueID;
};
#endif

Просмотреть файл

@ -120,13 +120,7 @@ private:
void restoreMutability();
friend class SkSurface_Raster; // For the two methods above.
friend class SkImage_Raster;
friend class SkSpecialImage_Raster;
void setImmutableWithID(uint32_t genID);
friend class SkImage_Gpu;
friend class SkImage_Lazy;
friend class SkSpecialImage_Gpu;
friend void SkBitmapCache_setImmutableWithID(SkPixelRef*, uint32_t);
typedef SkRefCnt INHERITED;

Просмотреть файл

@ -106,7 +106,7 @@ public:
*/
void setColorSpace(sk_sp<SkColorSpace> colorSpace);
/** To be deprecated soon.
/** Deprecated.
*/
bool SK_WARN_UNUSED_RESULT reset(const SkMask& mask);
@ -124,7 +124,7 @@ public:
/** Returns width, height, SkAlphaType, SkColorType, and SkColorSpace.
@return reference to ImageInfo
@return reference to SkImageInfo
*/
const SkImageInfo& info() const { return fInfo; }
@ -185,6 +185,16 @@ public:
*/
SkColorSpace* colorSpace() const { return fInfo.colorSpace(); }
/** Returns smart pointer to SkColorSpace, the range of colors, associated with
SkImageInfo. The smart pointer tracks the number of objects sharing this
SkColorSpace reference so the memory is released when the owners destruct.
The returned SkColorSpace is immutable.
@return SkColorSpace in SkImageInfo wrapped in a smart pointer
*/
sk_sp<SkColorSpace> refColorSpace() const { return fInfo.refColorSpace(); }
/** Returns true if SkAlphaType is kOpaque_SkAlphaType.
Does not check if SkColorType allows alpha, or if any pixel value has
transparency.
@ -541,7 +551,7 @@ public:
dstInfo specifies width, height, SkColorType, SkAlphaType, and
SkColorSpace of destination. dstRowBytes specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if
dstInfo.addr() equals nullptr, or dstRowBytes is less than dstInfo.minRowBytes().
dstInfo address equals nullptr, or dstRowBytes is less than dstInfo.minRowBytes().
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match.
@ -567,7 +577,7 @@ public:
dstInfo specifies width, height, SkColorType, SkAlphaType, and
SkColorSpace of destination. dstRowBytes specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if
dstInfo.addr() equals nullptr, or dstRowBytes is less than dstInfo.minRowBytes().
dstInfo address equals nullptr, or dstRowBytes is less than dstInfo.minRowBytes().
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match.
@ -593,7 +603,7 @@ public:
/** Copies a SkRect of pixels to dst. Copy starts at (srcX, srcY), and does not
exceed SkPixmap (width(), height()). dst specifies width, height, SkColorType,
SkAlphaType, and SkColorSpace of destination. Returns true if pixels are copied.
Returns false if dst.addr() equals nullptr, or dst.rowBytes() is less than
Returns false if dst address equals nullptr, or dst.rowBytes() is less than
dst SkImageInfo::minRowBytes.
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
@ -618,7 +628,7 @@ public:
/** Copies pixels inside bounds() to dst. dst specifies width, height, SkColorType,
SkAlphaType, and SkColorSpace of destination. Returns true if pixels are copied.
Returns false if dst.addr() equals nullptr, or dst.rowBytes() is less than
Returns false if dst address equals nullptr, or dst.rowBytes() is less than
dst SkImageInfo::minRowBytes.
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
@ -639,7 +649,7 @@ public:
/** Copies SkBitmap to dst, scaling pixels to fit dst.width() and dst.height(), and
converting pixels to match dst.colorType() and dst.alphaType(). Returns true if
pixels are copied. Returns false if dst.addr() is nullptr, or dst.rowBytes() is
pixels are copied. Returns false if dst address is nullptr, or dst.rowBytes() is
less than dst SkImageInfo::minRowBytes.
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
@ -655,8 +665,8 @@ public:
filterQuality kNone_SkFilterQuality is fastest, typically implemented with
nearest neighbor filter. kLow_SkFilterQuality is typically implemented with
bilerp filter. kMedium_SkFilterQuality is typically implemented with
bilerp filter, and Filter_Quality_MipMap when size is reduced.
kHigh_SkFilterQuality is slowest, typically implemented with Filter_Quality_BiCubic.
bilerp filter, and mip-map filter when size is reduced.
kHigh_SkFilterQuality is slowest, typically implemented with bicubic filter.
@param dst SkImageInfo and pixel address to write to
@param filterQuality one of: kNone_SkFilterQuality, kLow_SkFilterQuality,

Просмотреть файл

@ -488,9 +488,9 @@ struct SK_API SkPoint {
*/
static SkScalar Length(SkScalar x, SkScalar y);
/** Scales (vec->fX, vec->fY) so that length() returns one, while preserving ratio of vec->fX to vec->fY,
if possible. If original length is nearly zero, sets vec to (0, 0) and returns zero;
otherwise, returns length of vec before vec is scaled.
/** Scales (vec->fX, vec->fY) so that length() returns one, while preserving ratio of vec->fX
to vec->fY, if possible. If original length is nearly zero, sets vec to (0, 0) and returns
zero; otherwise, returns length of vec before vec is scaled.
Returned prior length may be SK_ScalarInfinity if it can not be represented by SkScalar.

Просмотреть файл

@ -40,6 +40,12 @@
# error "must define either SK_CPU_LENDIAN or SK_CPU_BENDIAN"
#endif
#if defined(SK_CPU_BENDIAN) && !defined(I_ACKNOWLEDGE_SKIA_DOES_NOT_SUPPORT_BIG_ENDIAN)
#error "The Skia team is not endian-savvy enough to support big-endian CPUs."
#error "If you still want to use Skia,"
#error "please define I_ACKNOWLEDGE_SKIA_DOES_NOT_SUPPORT_BIG_ENDIAN."
#endif
/**
* Ensure the port has defined all of SK_X32_SHIFT, or none of them.
*/
@ -296,4 +302,8 @@
# define SK_HISTOGRAM_ENUMERATION(name, value, boundary_value)
#endif
#ifndef SK_DISABLE_LEGACY_SHADERCONTEXT
#define SK_ENABLE_LEGACY_SHADERCONTEXT
#endif
#endif // SkPostConfig_DEFINED

Просмотреть файл

@ -42,18 +42,9 @@
#endif
/* Even if the user only defined the framework variant we still need to build
* the default (NDK-compliant) Android code. Therefore, when attempting to
* include/exclude something from the framework variant check first that we are
* building for Android then check the status of the framework define.
*/
#if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) && !defined(SK_BUILD_FOR_ANDROID)
#define SK_BUILD_FOR_ANDROID
#endif
//////////////////////////////////////////////////////////////////////
#ifdef SK_BUILD_FOR_WIN
#if defined(SK_BUILD_FOR_WIN) && !defined(__clang__)
#if !defined(SK_RESTRICT)
#define SK_RESTRICT __restrict
#endif

Просмотреть файл

@ -0,0 +1,59 @@
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkPromiseImageTexture_DEFINED
#define SkPromiseImageTexture_DEFINED
#include "../private/GrResourceKey.h"
#include "GrBackendSurface.h"
#include "SkRefCnt.h"
#if SK_SUPPORT_GPU
/**
* This type is used to fulfill textures for PromiseImages. Once an instance is returned from a
* PromiseImageTextureFulfillProc it must remain valid until the corresponding
* PromiseImageTextureReleaseProc is called. For performance reasons it is recommended that the
* the client reuse a single PromiseImageTexture every time a given texture is returned by
* the PromiseImageTextureFulfillProc rather than recreating PromiseImageTextures representing
* the same underlying backend API texture.
*/
class SK_API SkPromiseImageTexture : public SkNVRefCnt<SkPromiseImageTexture> {
public:
SkPromiseImageTexture() = delete;
SkPromiseImageTexture(const SkPromiseImageTexture&) = delete;
SkPromiseImageTexture(SkPromiseImageTexture&&) = delete;
~SkPromiseImageTexture();
SkPromiseImageTexture& operator=(const SkPromiseImageTexture&) = delete;
SkPromiseImageTexture& operator=(SkPromiseImageTexture&&) = delete;
static sk_sp<SkPromiseImageTexture> Make(const GrBackendTexture& backendTexture) {
if (!backendTexture.isValid()) {
return nullptr;
}
return sk_sp<SkPromiseImageTexture>(new SkPromiseImageTexture(backendTexture));
}
const GrBackendTexture& backendTexture() const { return fBackendTexture; }
void addKeyToInvalidate(uint32_t contextID, const GrUniqueKey& key);
uint32_t uniqueID() const { return fUniqueID; }
#if GR_TEST_UTILS
SkTArray<GrUniqueKey> testingOnly_uniqueKeysToInvalidate() const;
#endif
private:
explicit SkPromiseImageTexture(const GrBackendTexture& backendTexture);
SkSTArray<1, GrUniqueKeyInvalidatedMessage> fMessages;
GrBackendTexture fBackendTexture;
uint32_t fUniqueID = SK_InvalidUniqueID;
static std::atomic<uint32_t> gUniqueID;
};
#endif
#endif

Просмотреть файл

@ -107,14 +107,14 @@ public:
/** Returns span on the x-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return bounds().fRight minus bounds().fLeft
@return rect().fRight minus rect().fLeft
*/
SkScalar width() const { return fRect.width(); }
/** Returns span on the y-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return bounds().fBottom minus bounds().fTop
@return rect().fBottom minus rect().fTop
*/
SkScalar height() const { return fRect.height(); }
@ -310,7 +310,7 @@ public:
/** Returns true if bounds and radii in a are equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
contain zeroes with different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare
@ -323,7 +323,7 @@ public:
/** Returns true if bounds and radii in a are not equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
contain zeroes with different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare

Просмотреть файл

@ -51,14 +51,6 @@ struct SK_API SkIRect {
return SkIRect{0, 0, 0, 0};
}
#ifdef SK_SUPPORT_LEGACY_RECTMAKELARGEST
/** Deprecated.
*/
static SkIRect SK_WARN_UNUSED_RESULT MakeLargest() {
return { SK_MinS32, SK_MinS32, SK_MaxS32, SK_MaxS32 };
}
#endif
/** Returns constructed SkIRect set to (0, 0, w, h). Does not validate input; w or h
may be negative.
@ -150,6 +142,9 @@ struct SK_API SkIRect {
*/
int32_t y() const { return fTop; }
// Experimental
SkIPoint topLeft() const { return {fLeft, fTop}; }
/** Returns span on the x-axis. This does not check if SkIRect is sorted, or if
result fits in 32-bit signed integer; result may be negative.
@ -702,14 +697,6 @@ struct SK_API SkRect {
return SkRect{0, 0, 0, 0};
}
#ifdef SK_SUPPORT_LEGACY_RECTMAKELARGEST
/** Deprecated.
*/
static SkRect SK_WARN_UNUSED_RESULT MakeLargest() {
return { SK_ScalarMin, SK_ScalarMin, SK_ScalarMax, SK_ScalarMax };
}
#endif
/** Returns constructed SkRect set to SkScalar values (0, 0, w, h). Does not
validate input; w or h may be negative.
@ -903,7 +890,7 @@ struct SK_API SkRect {
/** Returns average of left edge and right edge. Result does not change if SkRect
is sorted. Result may overflow to infinity if SkRect is far from the origin.
@return midpoint in x
@return midpoint on x-axis
*/
SkScalar centerX() const {
// don't use SkScalarHalf(fLeft + fBottom) as that might overflow before the 0.5
@ -913,7 +900,7 @@ struct SK_API SkRect {
/** Returns average of top edge and bottom edge. Result does not change if SkRect
is sorted.
@return midpoint in y
@return midpoint on y-axis
*/
SkScalar centerY() const {
// don't use SkScalarHalf(fTop + fBottom) as that might overflow before the 0.5
@ -924,7 +911,7 @@ struct SK_API SkRect {
equal to the corresponding members in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
contain zeroes with different signs.
@param a SkRect to compare
@param b SkRect to compare
@ -938,7 +925,7 @@ struct SK_API SkRect {
equal the corresponding members in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
contain zeroes with different signs.
@param a SkRect to compare
@param b SkRect to compare
@ -950,7 +937,8 @@ struct SK_API SkRect {
/** Returns four points in quad that enclose SkRect ordered as: top-left, top-right,
bottom-right, bottom-left.
Consider adding param to control whether quad is clockwise or counterclockwise.
TODO: Consider adding parameter to control whether quad is clockwise or counterclockwise.
@param quad storage for corners of SkRect
*/

Просмотреть файл

@ -37,24 +37,13 @@ public:
/** Destruct, asserting that the reference count is 1.
*/
virtual ~SkRefCntBase() {
#ifdef SK_DEBUG
SkASSERTF(getRefCnt() == 1, "fRefCnt was %d", getRefCnt());
#ifdef SK_DEBUG
SkASSERTF(this->getRefCnt() == 1, "fRefCnt was %d", this->getRefCnt());
// illegal value, to catch us if we reuse after delete
fRefCnt.store(0, std::memory_order_relaxed);
#endif
#endif
}
#ifdef SK_DEBUG
/** Return the reference count. Use only for debugging. */
int32_t getRefCnt() const {
return fRefCnt.load(std::memory_order_relaxed);
}
void validate() const {
SkASSERT(getRefCnt() > 0);
}
#endif
/** May return true if the caller is the only owner.
* Ensures that all previous owner's actions are complete.
*/
@ -71,7 +60,7 @@ public:
/** Increment the reference count. Must be balanced by a call to unref().
*/
void ref() const {
SkASSERT(getRefCnt() > 0);
SkASSERT(this->getRefCnt() > 0);
// No barrier required.
(void)fRefCnt.fetch_add(+1, std::memory_order_relaxed);
}
@ -81,7 +70,7 @@ public:
the object needs to have been allocated via new, and not on the stack.
*/
void unref() const {
SkASSERT(getRefCnt() > 0);
SkASSERT(this->getRefCnt() > 0);
// A release here acts in place of all releases we "should" have been doing in ref().
if (1 == fRefCnt.fetch_add(-1, std::memory_order_acq_rel)) {
// Like unique(), the acquire is only needed on success, to make sure
@ -90,23 +79,23 @@ public:
}
}
protected:
/**
* Allow subclasses to call this if they've overridden internal_dispose
* so they can reset fRefCnt before the destructor is called or if they
* choose not to call the destructor (e.g. using a free list).
*/
void internal_dispose_restore_refcnt_to_1() const {
SkASSERT(0 == getRefCnt());
fRefCnt.store(1, std::memory_order_relaxed);
}
private:
#ifdef SK_DEBUG
/** Return the reference count. Use only for debugging. */
int32_t getRefCnt() const {
return fRefCnt.load(std::memory_order_relaxed);
}
#endif
/**
* Called when the ref count goes to 0.
*/
virtual void internal_dispose() const {
this->internal_dispose_restore_refcnt_to_1();
#ifdef SK_DEBUG
SkASSERT(0 == this->getRefCnt());
fRefCnt.store(1, std::memory_order_relaxed);
#endif
delete this;
}
@ -171,7 +160,12 @@ template <typename Derived>
class SkNVRefCnt {
public:
SkNVRefCnt() : fRefCnt(1) {}
~SkNVRefCnt() { SkASSERTF(1 == getRefCnt(), "NVRefCnt was %d", getRefCnt()); }
~SkNVRefCnt() {
#ifdef SK_DEBUG
int rc = fRefCnt.load(std::memory_order_relaxed);
SkASSERTF(rc == 1, "NVRefCnt was %d", rc);
#endif
}
// Implementation is pretty much the same as SkRefCntBase. All required barriers are the same:
// - unique() needs acquire when it returns true, and no barrier if it returns false;
@ -191,9 +185,6 @@ public:
private:
mutable std::atomic<int32_t> fRefCnt;
int32_t getRefCnt() const {
return fRefCnt.load(std::memory_order_relaxed);
}
SkNVRefCnt(SkNVRefCnt&&) = delete;
SkNVRefCnt(const SkNVRefCnt&) = delete;

Просмотреть файл

@ -452,8 +452,8 @@ public:
*/
bool op(const SkRegion& rgna, const SkRegion& rgnb, Op op);
#ifdef SK_BUILD_FOR_ANDROID
/** Android framework only.
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** Private. Android framework only.
@return string representation of SkRegion
*/
@ -467,10 +467,11 @@ public:
class SK_API Iterator {
public:
/** Initializes SkRegion::Iterator with an empty SkRegion. done() on SkRegion::Iterator returns true.
/** Initializes SkRegion::Iterator with an empty SkRegion. done() on SkRegion::Iterator
returns true.
Call reset() to initialized SkRegion::Iterator at a later time.
@return empty SkRegion ierator
@return empty SkRegion iterator
*/
Iterator() : fRgn(nullptr), fDone(true) {}
@ -549,8 +550,8 @@ public:
*/
void next();
/** Returns SkIRect element in SkRegion, intersected with clip passed to SkRegion::Cliperator
constructor. Does not return predictable results if SkRegion
/** Returns SkIRect element in SkRegion, intersected with clip passed to
SkRegion::Cliperator constructor. Does not return predictable results if SkRegion
is empty.
@return part of SkRegion inside clip as SkIRect

Просмотреть файл

@ -122,9 +122,7 @@ SkScalar SkScalarSinCos(SkScalar radians, SkScalar* cosValue);
static inline SkScalar SkScalarSquare(SkScalar x) { return x * x; }
#define SkScalarDiv(numer, denom) sk_ieee_float_divide(numer, denom)
#define SkScalarInvert(x) sk_ieee_float_divide(SK_Scalar1, (x))
#define SkScalarFastInvert(x) sk_ieee_float_divide(SK_Scalar1, (x))
#define SkScalarInvert(x) sk_ieee_float_divide_TODO_IS_DIVIDE_BY_ZERO_SAFE_HERE(SK_Scalar1, (x))
#define SkScalarAve(a, b) (((a) + (b)) * SK_ScalarHalf)
#define SkScalarHalf(a) ((a) * SK_ScalarHalf)

Просмотреть файл

@ -40,22 +40,25 @@ class GrFragmentProcessor;
class SK_API SkShader : public SkFlattenable {
public:
enum TileMode {
/** replicate the edge color if the shader draws outside of its
* original bounds
/**
* Replicate the edge color if the shader draws outside of its
* original bounds.
*/
kClamp_TileMode,
/** repeat the shader's image horizontally and vertically */
/**
* Repeat the shader's image horizontally and vertically.
*/
kRepeat_TileMode,
/** repeat the shader's image horizontally and vertically, alternating
* mirror images so that adjacent images always seam
/**
* Repeat the shader's image horizontally and vertically, alternating
* mirror images so that adjacent images always seam.
*/
kMirror_TileMode,
/**
* Only draw within the original domain, return transparent-black everywhere else.
* EXPERIMENTAL -- DO NOT USE YET
*/
kDecal_TileMode,
@ -80,19 +83,6 @@ public:
*/
virtual bool isOpaque() const { return false; }
#ifdef SK_SUPPORT_LEGACY_SHADER_ISABITMAP
/**
* Returns true if this shader is just a bitmap, and if not null, returns the bitmap,
* localMatrix, and tilemodes. If this is not a bitmap, returns false and ignores the
* out-parameters.
*/
bool isABitmap(SkBitmap* outTexture, SkMatrix* outMatrix, TileMode xy[2]) const;
bool isABitmap() const {
return this->isABitmap(nullptr, nullptr, nullptr);
}
#endif
/**
* Iff this shader is backed by a single SkImage, return its ptr (the caller must ref this
* if they want to keep it longer than the lifetime of the shader). If not, return nullptr.

Просмотреть файл

@ -66,7 +66,7 @@ struct SkSize {
*/
bool isZero() const { return 0 == fWidth && 0 == fHeight; }
/** Returns true if either widht or height are <= 0 */
/** Returns true if either width or height are <= 0 */
bool isEmpty() const { return fWidth <= 0 || fHeight <= 0; }
/** Set the width and height to 0 */

Просмотреть файл

@ -24,6 +24,10 @@
#include "GrTypes.h"
#if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
#include <android/hardware_buffer.h>
#endif
class SkCanvas;
class SkDeferredDisplayList;
class SkPaint;
@ -32,6 +36,7 @@ class GrBackendRenderTarget;
class GrBackendSemaphore;
class GrBackendTexture;
class GrContext;
class GrRecordingContext;
class GrRenderTarget;
/** \class SkSurface
@ -163,9 +168,16 @@ public:
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeRasterN32Premul(int width, int height,
const SkSurfaceProps* surfaceProps = nullptr) {
return MakeRaster(SkImageInfo::MakeN32Premul(width, height), surfaceProps);
}
const SkSurfaceProps* surfaceProps = nullptr);
/** Caller data passed to RenderTarget/TextureReleaseProc; may be nullptr. */
typedef void* ReleaseContext;
/** User function called when supplied render target may be deleted. */
typedef void (*RenderTargetReleaseProc)(ReleaseContext releaseContext);
/** User function called when supplied texture may be deleted. */
typedef void (*TextureReleaseProc)(ReleaseContext releaseContext);
/** Wraps a GPU-backed texture into SkSurface. Caller must ensure the texture is
valid for the lifetime of returned SkSurface. If sampleCnt greater than zero,
@ -180,26 +192,31 @@ public:
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kRGB_888x_SkColorType, kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@param textureReleaseProc function called when texture can be released
@param releaseContext state passed to textureReleaseProc
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeFromBackendTexture(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin origin, int sampleCnt,
SkColorType colorType,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
const SkSurfaceProps* surfaceProps,
TextureReleaseProc textureReleaseProc = nullptr,
ReleaseContext releaseContext = nullptr);
/** Wraps a GPU-backed buffer into SkSurface. Caller must ensure backendRenderTarget
is valid for the lifetime of returned SkSurface.
@ -213,25 +230,32 @@ public:
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@param context GPU context
@param backendRenderTarget GPU intermediate memory buffer
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
@param context GPU context
@param backendRenderTarget GPU intermediate memory buffer
@param origin one of:
kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kRGB_888x_SkColorType, kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@param releaseProc function called when texture can be released
@param releaseContext state passed to textureReleaseProc
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeFromBackendRenderTarget(GrContext* context,
const GrBackendRenderTarget& backendRenderTarget,
GrSurfaceOrigin origin,
SkColorType colorType,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
const SkSurfaceProps* surfaceProps,
RenderTargetReleaseProc releaseProc = nullptr,
ReleaseContext releaseContext = nullptr);
/** Wraps a GPU-backed texture into SkSurface. Caller must ensure backendTexture is
valid for the lifetime of returned SkSurface. If sampleCnt greater than zero,
@ -254,8 +278,9 @@ public:
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kRGB_888x_SkColorType, kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
@ -270,8 +295,36 @@ public:
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
#if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
/** Private.
Creates SkSurface from Android hardware buffer.
Returned SkSurface takes a reference on the buffer. The ref on the buffer will be released
when the SkSurface is destroyed and there is no pending work on the GPU involving the
buffer.
Only available on Android, when __ANDROID_API__ is defined to be 26 or greater.
Currently this is only supported for buffers that can be textured as well as rendered to.
In other workds that must have both AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT and
AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE usage bits.
@param context GPU context
@param hardwareBuffer AHardwareBuffer Android hardware buffer
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return created SkSurface, or nullptr
*/
static sk_sp<SkSurface> MakeFromAHardwareBuffer(GrContext* context,
AHardwareBuffer* hardwareBuffer,
GrSurfaceOrigin origin,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
#endif
/** Returns SkSurface on GPU indicated by context. Allocates memory for
pixels, based on the width, height, and SkColorType in ImageInfo. budgeted
pixels, based on the width, height, and SkColorType in SkImageInfo. budgeted
selects whether allocation for pixels is tracked by context. imageInfo
describes the pixel format in SkColorType, and transparency in
SkAlphaType, and color matching in SkColorSpace.
@ -305,7 +358,7 @@ public:
bool shouldCreateWithMips = false);
/** Returns SkSurface on GPU indicated by context. Allocates memory for
pixels, based on the width, height, and SkColorType in ImageInfo. budgeted
pixels, based on the width, height, and SkColorType in SkImageInfo. budgeted
selects whether allocation for pixels is tracked by context. imageInfo
describes the pixel format in SkColorType, and transparency in
SkAlphaType, and color matching in SkColorSpace.
@ -334,7 +387,7 @@ public:
}
/** Returns SkSurface on GPU indicated by context. Allocates memory for
pixels, based on the width, height, and SkColorType in ImageInfo. budgeted
pixels, based on the width, height, and SkColorType in SkImageInfo. budgeted
selects whether allocation for pixels is tracked by context. imageInfo
describes the pixel format in SkColorType, and transparency in
SkAlphaType, and color matching in SkColorSpace.
@ -364,7 +417,7 @@ public:
@param budgeted one of: SkBudgeted::kNo, SkBudgeted::kYes
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeRenderTarget(GrContext* context,
static sk_sp<SkSurface> MakeRenderTarget(GrRecordingContext* context,
const SkSurfaceCharacterization& characterization,
SkBudgeted budgeted);
@ -408,8 +461,7 @@ public:
/** Notifies that SkSurface contents will be changed by code outside of Skia.
Subsequent calls to generationID() return a different value.
mode is normally passed as kRetain_ContentChangeMode.
Can we deprecate this?
TODO: Can kRetain_ContentChangeMode be deprecated?
@param mode one of: kDiscard_ContentChangeMode, kRetain_ContentChangeMode
*/
@ -443,7 +495,8 @@ public:
The returned GrBackendTexture should be discarded if the SkSurface is drawn to or deleted.
@param backendHandleAccess one of: kFlushRead_BackendHandleAccess,
kFlushWrite_BackendHandleAccess, kDiscardWrite_BackendHandleAccess
kFlushWrite_BackendHandleAccess,
kDiscardWrite_BackendHandleAccess
@return GPU texture reference; invalid on failure
*/
GrBackendTexture getBackendTexture(BackendHandleAccess backendHandleAccess);
@ -456,7 +509,8 @@ public:
or deleted.
@param backendHandleAccess one of: kFlushRead_BackendHandleAccess,
kFlushWrite_BackendHandleAccess, kDiscardWrite_BackendHandleAccess
kFlushWrite_BackendHandleAccess,
kDiscardWrite_BackendHandleAccess
@return GPU render target reference; invalid on failure
*/
GrBackendRenderTarget getBackendRenderTarget(BackendHandleAccess backendHandleAccess);
@ -490,6 +544,17 @@ public:
*/
sk_sp<SkImage> makeImageSnapshot();
/**
* Like the no-parameter version, this returns an image of the current surface contents.
* This variant takes a rectangle specifying the subset of the surface that is of interest.
* These bounds will be sanitized before being used.
* - If bounds extends beyond the surface, it will be trimmed to just the intersection of
* it and the surface.
* - If bounds does not intersect the surface, then this returns nullptr.
* - If bounds == the surface, then this is the same as calling the no-parameter variant.
*/
sk_sp<SkImage> makeImageSnapshot(const SkIRect& bounds);
/** Draws SkSurface contents to canvas, with its top-left corner at (x, y).
If SkPaint paint is not nullptr, apply SkColorFilter, alpha, SkImageFilter,
@ -641,7 +706,7 @@ public:
*/
const SkSurfaceProps& props() const { return fProps; }
/** To be deprecated soon.
/** Deprecated.
*/
void prepareForExternalIO();
@ -653,6 +718,59 @@ public:
*/
void flush();
enum class BackendSurfaceAccess {
kNoAccess, //!< back-end object will not be used by client
kPresent, //!< back-end surface will be used for presenting to screen
};
enum FlushFlags {
kNone_FlushFlags = 0,
// flush will wait till all submitted GPU work is finished before returning.
kSyncCpu_FlushFlag = 0x1,
};
/** Issues pending SkSurface commands to the GPU-backed API and resolves any SkSurface MSAA.
After issuing all commands, signalSemaphores of count numSemaphores are signaled by the GPU.
The work that is submitted to the GPU will be dependent on the BackendSurfaceAccess that is
passed in.
If BackendSurfaceAccess::kNoAccess is passed in all commands will be issued to the GPU.
If BackendSurfaceAccess::kPresent is passed in and the backend API is not Vulkan, it is
treated the same as kNoAccess. If the backend API is Vulkan, the VkImage that backs the
SkSurface will be transferred back to its original queue. If the SkSurface was created by
wrapping a VkImage, the queue will be set to the queue which was originally passed in on
the GrVkImageInfo. Additionally, if the original queue was not external or foreign the
layout of the VkImage will be set to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
For each GrBackendSemaphore in signalSemaphores:
if GrBackendSemaphore is initialized, the GPU back-end uses the semaphore as is;
otherwise, a new semaphore is created and initializes GrBackendSemaphore.
The caller must delete the semaphores created and returned in signalSemaphores.
GrBackendSemaphore can be deleted as soon as this function returns.
If the back-end API is OpenGL only uninitialized backend semaphores are supported.
If the back-end API is Vulkan semaphores may be initialized or uninitialized.
If uninitialized, created semaphores are valid only with the VkDevice
with which they were created.
If GrSemaphoresSubmitted::kNo is returned, the GPU back-end did not create or
add any semaphores to signal on the GPU; the caller should not instruct the GPU
to wait on any of the semaphores.
Pending surface commands are flushed regardless of the return result.
@param access type of access the call will do on the backend object after flush
@param flags flush options
@param numSemaphores size of signalSemaphores array
@param signalSemaphores array of semaphore containers
@return one of: GrSemaphoresSubmitted::kYes, GrSemaphoresSubmitted::kNo
*/
GrSemaphoresSubmitted flush(BackendSurfaceAccess access, FlushFlags flags,
int numSemaphores, GrBackendSemaphore signalSemaphores[]);
/** Issues pending SkSurface commands to the GPU-backed API and resolves any SkSurface MSAA.
After issuing all commands, signalSemaphores of count numSemaphores semaphores
are signaled by the GPU.
@ -697,7 +815,7 @@ public:
/** Initializes SkSurfaceCharacterization that can be used to perform GPU back-end
processing in a separate thread. Typically this is used to divide drawing
into multiple tiles. DeferredDisplayListRecorder records the drawing commands
into multiple tiles. SkDeferredDisplayListRecorder records the drawing commands
for each tile.
Return true if SkSurface supports characterization. raster surface returns false.

Просмотреть файл

@ -17,7 +17,9 @@
class SkColorSpace;
#if SK_SUPPORT_GPU
// TODO: remove the GrContext.h include once Flutter is updated
#include "GrContext.h"
#include "GrContextThreadSafeProxy.h"
/** \class SkSurfaceCharacterization
A surface characterization contains all the information Ganesh requires to makes its internal
@ -31,6 +33,8 @@ public:
enum class Textureable : bool { kNo = false, kYes = true };
enum class MipMapped : bool { kNo = false, kYes = true };
enum class UsesGLFBO0 : bool { kNo = false, kYes = true };
// This flag indicates if the surface is wrapping a raw Vulkan secondary command buffer.
enum class VulkanSecondaryCBCompatible : bool { kNo = false, kYes = true };
SkSurfaceCharacterization()
: fCacheMaxResourceBytes(0)
@ -41,6 +45,7 @@ public:
, fIsTextureable(Textureable::kYes)
, fIsMipMapped(MipMapped::kYes)
, fUsesGLFBO0(UsesGLFBO0::kNo)
, fVulkanSecondaryCBCompatible(VulkanSecondaryCBCompatible::kNo)
, fSurfaceProps(0, kUnknown_SkPixelGeometry) {
}
@ -72,12 +77,16 @@ public:
bool isTextureable() const { return Textureable::kYes == fIsTextureable; }
bool isMipMapped() const { return MipMapped::kYes == fIsMipMapped; }
bool usesGLFBO0() const { return UsesGLFBO0::kYes == fUsesGLFBO0; }
bool vulkanSecondaryCBCompatible() const {
return VulkanSecondaryCBCompatible::kYes == fVulkanSecondaryCBCompatible;
}
SkColorSpace* colorSpace() const { return fImageInfo.colorSpace(); }
sk_sp<SkColorSpace> refColorSpace() const { return fImageInfo.refColorSpace(); }
const SkSurfaceProps& surfaceProps()const { return fSurfaceProps; }
private:
friend class SkSurface_Gpu; // for 'set' & 'config'
friend class GrVkSecondaryCBDrawContext; // for 'set' & 'config'
friend class GrContextThreadSafeProxy; // for private ctor
friend class SkDeferredDisplayListRecorder; // for 'config'
friend class SkSurface; // for 'config'
@ -92,6 +101,7 @@ private:
GrFSAAType FSAAType, int stencilCnt,
Textureable isTextureable, MipMapped isMipMapped,
UsesGLFBO0 usesGLFBO0,
VulkanSecondaryCBCompatible vulkanSecondaryCBCompatible,
const SkSurfaceProps& surfaceProps)
: fContextInfo(std::move(contextInfo))
, fCacheMaxResourceBytes(cacheMaxResourceBytes)
@ -103,6 +113,7 @@ private:
, fIsTextureable(isTextureable)
, fIsMipMapped(isMipMapped)
, fUsesGLFBO0(usesGLFBO0)
, fVulkanSecondaryCBCompatible(vulkanSecondaryCBCompatible)
, fSurfaceProps(surfaceProps) {
}
@ -116,10 +127,16 @@ private:
Textureable isTextureable,
MipMapped isMipMapped,
UsesGLFBO0 usesGLFBO0,
VulkanSecondaryCBCompatible vulkanSecondaryCBCompatible,
const SkSurfaceProps& surfaceProps) {
SkASSERT(MipMapped::kNo == isMipMapped || Textureable::kYes == isTextureable);
SkASSERT(Textureable::kNo == isTextureable || UsesGLFBO0::kNo == usesGLFBO0);
SkASSERT(VulkanSecondaryCBCompatible::kNo == vulkanSecondaryCBCompatible ||
UsesGLFBO0::kNo == usesGLFBO0);
SkASSERT(Textureable::kNo == isTextureable ||
VulkanSecondaryCBCompatible::kNo == vulkanSecondaryCBCompatible);
fContextInfo = contextInfo;
fCacheMaxResourceBytes = cacheMaxResourceBytes;
@ -131,6 +148,7 @@ private:
fIsTextureable = isTextureable;
fIsMipMapped = isMipMapped;
fUsesGLFBO0 = usesGLFBO0;
fVulkanSecondaryCBCompatible = vulkanSecondaryCBCompatible;
fSurfaceProps = surfaceProps;
}
@ -145,6 +163,7 @@ private:
Textureable fIsTextureable;
MipMapped fIsMipMapped;
UsesGLFBO0 fUsesGLFBO0;
VulkanSecondaryCBCompatible fVulkanSecondaryCBCompatible;
SkSurfaceProps fSurfaceProps;
};
@ -173,6 +192,7 @@ public:
bool isTextureable() const { return false; }
bool isMipMapped() const { return false; }
bool usesGLFBO0() const { return false; }
bool vulkanSecondaryCBCompatible() const { return false; }
SkColorSpace* colorSpace() const { return nullptr; }
sk_sp<SkColorSpace> refColorSpace() const { return nullptr; }
const SkSurfaceProps& surfaceProps()const { return fSurfaceProps; }

Просмотреть файл

@ -19,23 +19,16 @@
*/
template <typename T> class SkTLazy {
public:
SkTLazy() : fPtr(nullptr) {}
SkTLazy() = default;
explicit SkTLazy(const T* src) : fPtr(src ? new (&fStorage) T(*src) : nullptr) {}
SkTLazy(const SkTLazy& that) { *this = that; }
SkTLazy(SkTLazy&& that) { *this = std::move(that); }
explicit SkTLazy(const T* src)
: fPtr(src ? new (fStorage.get()) T(*src) : nullptr) {}
SkTLazy(const SkTLazy& that) : fPtr(nullptr) { *this = that; }
SkTLazy(SkTLazy&& that) : fPtr(nullptr) { *this = std::move(that); }
~SkTLazy() {
if (this->isValid()) {
fPtr->~T();
}
}
~SkTLazy() { this->reset(); }
SkTLazy& operator=(const SkTLazy& that) {
if (that.isValid()) {
this->set(*that.get());
this->set(*that);
} else {
this->reset();
}
@ -44,7 +37,7 @@ public:
SkTLazy& operator=(SkTLazy&& that) {
if (that.isValid()) {
this->set(std::move(*that.get()));
this->set(std::move(*that));
} else {
this->reset();
}
@ -58,10 +51,8 @@ public:
* instance is always returned.
*/
template <typename... Args> T* init(Args&&... args) {
if (this->isValid()) {
fPtr->~T();
}
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(std::forward<Args>(args)...);
this->reset();
fPtr = new (&fStorage) T(std::forward<Args>(args)...);
return fPtr;
}
@ -75,7 +66,7 @@ public:
if (this->isValid()) {
*fPtr = src;
} else {
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(src);
fPtr = new (&fStorage) T(src);
}
return fPtr;
}
@ -84,7 +75,7 @@ public:
if (this->isValid()) {
*fPtr = std::move(src);
} else {
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(std::move(src));
fPtr = new (&fStorage) T(std::move(src));
}
return fPtr;
}
@ -110,6 +101,8 @@ public:
* knows that the object has been initialized.
*/
T* get() const { SkASSERT(this->isValid()); return fPtr; }
T* operator->() const { return this->get(); }
T& operator*() const { return *this->get(); }
/**
* Like above but doesn't assert if object isn't initialized (in which case
@ -118,8 +111,8 @@ public:
T* getMaybeNull() const { return fPtr; }
private:
SkAlignedSTStorage<1, T> fStorage;
T* fPtr; // nullptr or fStorage
typename std::aligned_storage<sizeof(T), alignof(T)>::type fStorage;
T* fPtr{nullptr}; // nullptr or fStorage
};
/**

Просмотреть файл

@ -19,12 +19,14 @@
#define SkTextBlob_DEFINED
#include "../private/SkTemplates.h"
#include "SkFont.h"
#include "SkPaint.h"
#include "SkString.h"
#include "SkRefCnt.h"
#include <atomic>
struct SkRSXform;
struct SkSerialProcs;
struct SkDeserialProcs;
@ -50,43 +52,106 @@ public:
*/
uint32_t uniqueID() const { return fUniqueID; }
/** Creates SkTextBlob with a single run. text meaning depends on SkPaint::TextEncoding;
by default, text is encoded as UTF-8.
/** Returns the number of intervals that intersect bounds.
bounds describes a pair of lines parallel to the text advance.
The return count is zero or a multiple of two, and is at most twice the number of glyphs in
the the blob.
paint contains attributes used to define the run text:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Pass nullptr for intervals to determine the size of the interval array.
Runs within the blob that contain SkRSXform are ignored when computing intercepts.
@param bounds lower and upper line parallel to the advance
@param intervals returned intersections; may be nullptr
@param paint specifies stroking, SkPathEffect that affects the result; may be nullptr
@return number of intersections; may be zero
*/
int getIntercepts(const SkScalar bounds[2], SkScalar intervals[],
const SkPaint* paint = nullptr) const;
/** Creates SkTextBlob with a single run.
font contains attributes used to define the run text.
When encoding is SkTextEncoding::kUTF8, SkTextEncoding::kUTF16, or
SkTextEncoding::kUTF32, this function uses the default
character-to-glyph mapping from the SkTypeface in font. It does not
perform typeface fallback for characters not found in the SkTypeface.
It does not perform kerning or other complex shaping; glyphs are
positioned based on their default advances.
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param paint text size, typeface, text scale, and so on, used to draw
@param font text size, typeface, text scale, and so on, used to draw
@param encoding text encoding used in the text array
@return SkTextBlob constructed from one run
*/
static sk_sp<SkTextBlob> MakeFromText(
const void* text, size_t byteLength, const SkPaint& paint);
static sk_sp<SkTextBlob> MakeFromText(const void* text, size_t byteLength, const SkFont& font,
SkTextEncoding encoding = kUTF8_SkTextEncoding);
/** Creates SkTextBlob with a single run. string meaning depends on SkPaint::TextEncoding;
/** Creates SkTextBlob with a single run. string meaning depends on SkTextEncoding;
by default, string is encoded as UTF-8.
paint contains SkPaint::FontMetrics used to define the run text:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
font contains attributes used to define the run text.
@param string character code points or glyphs drawn
@param paint text size, typeface, text scale, and so on, used to draw
@return SkTextBlob constructed from one run
When encoding is SkTextEncoding::kUTF8, SkTextEncoding::kUTF16, or
SkTextEncoding::kUTF32, this function uses the default
character-to-glyph mapping from the SkTypeface in font. It does not
perform typeface fallback for characters not found in the SkTypeface.
It does not perform kerning or other complex shaping; glyphs are
positioned based on their default advances.
@param string character code points or glyphs drawn
@param font text size, typeface, text scale, and so on, used to draw
@param encoding text encoding used in the text array
@return SkTextBlob constructed from one run
*/
static sk_sp<SkTextBlob> MakeFromString(const char* string, const SkPaint& paint) {
static sk_sp<SkTextBlob> MakeFromString(const char* string, const SkFont& font,
SkTextEncoding encoding = kUTF8_SkTextEncoding) {
if (!string) {
return nullptr;
}
return MakeFromText(string, strlen(string), paint);
return MakeFromText(string, strlen(string), font, encoding);
}
/** Experimental.
Returns a textblob built from a single run of text with x-positions and a single y value.
This is equivalent to using SkTextBlobBuilder and calling allocRunPosH().
Returns nullptr if byteLength is zero.
@param text character code points or glyphs drawn (based on encoding)
@param byteLength byte length of text array
@param xpos array of x-positions, must contain values for all of the character points.
@param constY shared y-position for each character point, to be paired with each xpos.
@param font SkFont used for this run
@param encoding specifies the encoding of the text array.
@return new textblob or nullptr
*/
static sk_sp<SkTextBlob> MakeFromPosTextH(const void* text, size_t byteLength,
const SkScalar xpos[], SkScalar constY, const SkFont& font,
SkTextEncoding encoding = kUTF8_SkTextEncoding);
/** Experimental.
Returns a textblob built from a single run of text with positions.
This is equivalent to using SkTextBlobBuilder and calling allocRunPos().
Returns nullptr if byteLength is zero.
@param text character code points or glyphs drawn (based on encoding)
@param byteLength byte length of text array
@param pos array of positions, must contain values for all of the character points.
@param font SkFont used for this run
@param encoding specifies the encoding of the text array.
@return new textblob or nullptr
*/
static sk_sp<SkTextBlob> MakeFromPosText(const void* text, size_t byteLength,
const SkPoint pos[], const SkFont& font,
SkTextEncoding encoding = kUTF8_SkTextEncoding);
// Experimental
static sk_sp<SkTextBlob> MakeFromRSXform(const void* text, size_t byteLength,
const SkRSXform xform[], const SkFont& font,
SkTextEncoding encoding = kUTF8_SkTextEncoding);
/** Writes data to allow later reconstruction of SkTextBlob. memory points to storage
to receive the encoded data, and memory_size describes the size of storage.
Returns bytes used if provided storage is large enough to hold all data;
@ -97,10 +162,10 @@ public:
may be used to provide user context to procs.fTypefaceProc; procs.fTypefaceProc
is called with a pointer to SkTypeface and user context.
@param procs custom serial data encoders; may be nullptr
@param memory storage for data
@param size size of storage
@return bytes written, or zero if required storage is larger than memory_size
@param procs custom serial data encoders; may be nullptr
@param memory storage for data
@param memory_size size of storage
@return bytes written, or zero if required storage is larger than memory_size
*/
size_t serialize(const SkSerialProcs& procs, void* memory, size_t memory_size) const;
@ -206,9 +271,9 @@ public:
/** \struct SkTextBlobBuilder::RunBuffer
RunBuffer supplies storage for glyphs and positions within a run.
A run is a sequence of glyphs sharing SkPaint::FontMetrics and positioning.
A run is a sequence of glyphs sharing font metrics and positioning.
Each run may position its glyphs in one of three ways:
by specifying where the first glyph is drawn, and allowing SkPaint::FontMetrics to
by specifying where the first glyph is drawn, and allowing font metrics to
determine the advance to subsequent glyphs; by specifying a baseline, and
the position on that baseline for each glyph in run; or by providing SkPoint
array, one per glyph.
@ -218,115 +283,109 @@ public:
SkScalar* pos; //!< storage for positions in run
char* utf8text; //!< reserved for future use
uint32_t* clusters; //!< reserved for future use
// experimental
SkPoint* points() const { return reinterpret_cast<SkPoint*>(pos); }
// experimental
SkRSXform* xforms() const { return reinterpret_cast<SkRSXform*>(pos); }
};
/** Returns run with storage for glyphs. Caller must write count glyphs to
RunBuffer.glyphs() before next call to FontBlobBuilder.
RunBuffer::glyphs before next call to SkTextBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
RunBuffer::utf8text, and RunBuffer::clusters should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs share metrics in font.
Glyphs are positioned on a baseline at (x, y), using font SkPaint::FontMetrics to
Glyphs are positioned on a baseline at (x, y), using font metrics to
determine their relative placement.
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from (x, y) and RunBuffer.glyphs() SkPaint::FontMetrics.
is computed from (x, y) and RunBuffer::glyphs metrics.
@param font SkPaint used for this run
@param font SkFont used for this run
@param count number of glyphs
@param x horizontal offset within the blob
@param y vertical offset within the blob
@param bounds optional run bounding box
@return writable glyph buffer
*/
const RunBuffer& allocRun(const SkPaint& font, int count, SkScalar x, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunText(font, count, x, y, 0, SkString(), bounds);
}
const RunBuffer& allocRun(const SkFont& font, int count, SkScalar x, SkScalar y,
const SkRect* bounds = nullptr);
/** Returns run with storage for glyphs and positions along baseline. Caller must
write count glyphs to RunBuffer.glyphs(), and count scalars to RunBuffer.pos();
before next call to FontBlobBuilder.
write count glyphs to RunBuffer::glyphs, and count scalars to RunBuffer::pos;
before next call to SkTextBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
RunBuffer::utf8text, and RunBuffer::clusters should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs share metrics in font.
Glyphs are positioned on a baseline at y, using x-axis positions written by
caller to RunBuffer.pos().
caller to RunBuffer::pos.
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from y, RunBuffer.pos(), and RunBuffer.glyphs() SkPaint::FontMetrics.
is computed from y, RunBuffer::pos, and RunBuffer::glyphs metrics.
@param font SkPaint used for this run
@param font SkFont used for this run
@param count number of glyphs
@param y vertical offset within the blob
@param bounds optional run bounding box
@return writable glyph buffer and x-axis position buffer
*/
const RunBuffer& allocRunPosH(const SkPaint& font, int count, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunTextPosH(font, count, y, 0, SkString(), bounds);
}
const RunBuffer& allocRunPosH(const SkFont& font, int count, SkScalar y,
const SkRect* bounds = nullptr);
/** Returns run with storage for glyphs and SkPoint positions. Caller must
write count glyphs to RunBuffer.glyphs(), and count SkPoint to RunBuffer.pos();
before next call to FontBlobBuilder.
write count glyphs to RunBuffer::glyphs, and count SkPoint to RunBuffer::pos;
before next call to SkTextBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
RunBuffer::utf8text, and RunBuffer::clusters should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs share metrics in font.
Glyphs are positioned using SkPoint written by caller to RunBuffer.pos(), using
Glyphs are positioned using SkPoint written by caller to RunBuffer::pos, using
two scalar values for each SkPoint.
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from RunBuffer.pos(), and RunBuffer.glyphs() SkPaint::FontMetrics.
is computed from RunBuffer::pos, and RunBuffer::glyphs metrics.
@param font SkPaint used for this run
@param font SkFont used for this run
@param count number of glyphs
@param bounds optional run bounding box
@return writable glyph buffer and SkPoint buffer
*/
const RunBuffer& allocRunPos(const SkPaint& font, int count,
const SkRect* bounds = nullptr) {
return this->allocRunTextPos(font, count, 0, SkString(), bounds);
}
const RunBuffer& allocRunPos(const SkFont& font, int count,
const SkRect* bounds = nullptr);
// Experimental, RunBuffer.pos points to SkRSXform array
const RunBuffer& allocRunRSXform(const SkFont& font, int count);
private:
const RunBuffer& allocRunText(const SkPaint& font,
const RunBuffer& allocRunText(const SkFont& font,
int count,
SkScalar x,
SkScalar y,
int textByteCount,
SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRunTextPosH(const SkPaint& font, int count, SkScalar y,
const RunBuffer& allocRunTextPosH(const SkFont& font, int count, SkScalar y,
int textByteCount, SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRunTextPos(const SkPaint& font, int count,
const RunBuffer& allocRunTextPos(const SkFont& font, int count,
int textByteCount, SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRunRSXform(const SkFont& font, int count,
int textByteCount, SkString lang,
const SkRect* bounds = nullptr);
void reserve(size_t size);
void allocInternal(const SkPaint& font, SkTextBlob::GlyphPositioning positioning,
void allocInternal(const SkFont& font, SkTextBlob::GlyphPositioning positioning,
int count, int textBytes, SkPoint offset, const SkRect* bounds);
bool mergeRun(const SkPaint& font, SkTextBlob::GlyphPositioning positioning,
bool mergeRun(const SkFont& font, SkTextBlob::GlyphPositioning positioning,
uint32_t count, SkPoint offset);
void updateDeferredBounds();

Просмотреть файл

@ -176,7 +176,7 @@ public:
*/
static sk_sp<SkTypeface> MakeDeserialize(SkStream*);
enum Encoding {
enum Encoding : uint8_t {
kUTF8_Encoding,
kUTF16_Encoding,
kUTF32_Encoding
@ -201,6 +201,14 @@ public:
int charsToGlyphs(const void* chars, Encoding encoding, SkGlyphID glyphs[],
int glyphCount) const;
/**
* Return the glyphID that corresponds to the specified unicode code-point
* (in UTF32 encoding). If the unichar is not supported, returns 0.
*
* This is a short-cut for calling charsToGlyphs() with kUTF32_Encoding for one code-point.
*/
SkGlyphID unicharToGlyph(SkUnichar unichar) const;
/**
* Return the number of glyphs in the typeface.
*/
@ -306,7 +314,7 @@ public:
* collection.
* The caller is responsible for deleting the stream.
*/
SkStreamAsset* openStream(int* ttcIndex) const;
std::unique_ptr<SkStreamAsset> openStream(int* ttcIndex) const;
/**
* Return the font data, or nullptr on failure.
@ -378,7 +386,7 @@ protected:
// dstArray is non-null, and points to an array of size this->countGlyphs().
virtual void getGlyphToUnicodeMap(SkUnichar* dstArray) const;
virtual SkStreamAsset* onOpenStream(int* ttcIndex) const = 0;
virtual std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const = 0;
// TODO: make pure virtual.
virtual std::unique_ptr<SkFontData> onMakeFontData() const;
@ -432,7 +440,10 @@ private:
};
static SkFontStyle FromOldStyle(Style oldStyle);
static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal);
friend class SkFontPriv; // GetDefaultTypeface
friend class SkPaintPriv; // GetDefaultTypeface
friend class SkFont; // getGlyphToUnicodeMap
private:
SkFontID fUniqueID;

Просмотреть файл

@ -49,8 +49,6 @@ public:
static SkColor PMColorToColor(SkPMColor c);
static uint32_t UnPreMultiplyPreservingByteOrder(SkPMColor c);
private:
static const uint32_t gTable[256];
};

Просмотреть файл

@ -38,12 +38,16 @@ struct SK_API SkYUVAIndex {
}
// Index in the array of SkYUVAIndex
// TODO: rename as Component
enum Index {
kY_Index = 0,
kU_Index = 1,
kV_Index = 2,
kA_Index = 3
kA_Index = 3,
kLast_Index = kA_Index
};
static constexpr int kIndexCount = kLast_Index + 1;
/** The index is a number between -1..3 which definies which image source to read from, where -1
* means the image source doesn't exist. The assumption is we will always have image sources for

Просмотреть файл

@ -0,0 +1,68 @@
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkYUVASizeInfo_DEFINED
#define SkYUVASizeInfo_DEFINED
#include "SkEncodedOrigin.h"
#include "SkImageInfo.h"
#include "SkSize.h"
struct SK_API SkYUVASizeInfo {
static constexpr auto kMaxCount = 4;
SkISize fSizes[kMaxCount];
/**
* While the widths of the Y, U, V and A planes are not restricted, the
* implementation often requires that the width of the memory allocated
* for each plane be a multiple of 8.
*
* This struct allows us to inform the client how many "widthBytes"
* that we need. Note that we use the new idea of "widthBytes"
* because this idea is distinct from "rowBytes" (used elsewhere in
* Skia). "rowBytes" allow the last row of the allocation to not
* include any extra padding, while, in this case, every single row of
* the allocation must be at least "widthBytes".
*/
size_t fWidthBytes[kMaxCount];
/**
* YUVA data often comes from formats like JPEG that support EXIF orientation.
* Code that operates on the raw YUV data often needs to know that orientation.
*/
SkEncodedOrigin fOrigin = kDefault_SkEncodedOrigin;
bool operator==(const SkYUVASizeInfo& that) const {
for (int i = 0; i < kMaxCount; ++i) {
SkASSERT((!fSizes[i].isEmpty() && fWidthBytes[i]) ||
(fSizes[i].isEmpty() && !fWidthBytes[i]));
if (fSizes[i] != that.fSizes[i] || fWidthBytes[i] != that.fWidthBytes[i]) {
return false;
}
}
return true;
}
size_t computeTotalBytes() const {
size_t totalBytes = 0;
for (int i = 0; i < kMaxCount; ++i) {
SkASSERT((!fSizes[i].isEmpty() && fWidthBytes[i]) ||
(fSizes[i].isEmpty() && !fWidthBytes[i]));
totalBytes += fWidthBytes[i] * fSizes[i].height();
}
return totalBytes;
}
void computePlanes(void* base, void* planes[kMaxCount]) const;
};
#endif // SkYUVASizeInfo_DEFINED

Просмотреть файл

@ -1,36 +0,0 @@
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkYUVSizeInfo_DEFINED
#define SkYUVSizeInfo_DEFINED
#include "SkSize.h"
struct SkYUVSizeInfo {
enum YUVIndex {
kY = 0,
kU = 1,
kV = 2,
};
SkISize fSizes[3];
/**
* While the widths of the Y, U, and V planes are not restricted, the
* implementation often requires that the width of the memory allocated
* for each plane be a multiple of 8.
*
* This struct allows us to inform the client how many "widthBytes"
* that we need. Note that we use the new idea of "widthBytes"
* because this idea is distinct from "rowBytes" (used elsewhere in
* Skia). "rowBytes" allow the last row of the allocation to not
* include any extra padding, while, in this case, every single row of
* the allocation must be at least "widthBytes".
*/
size_t fWidthBytes[3];
};
#endif // SkYUVSizeInfo_DEFINED

Просмотреть файл

@ -9,62 +9,69 @@
#include "SkString.h"
#include "SkTime.h"
class SkExecutor;
namespace SkPDF {
/** Table 333 in PDF 32000-1:2008
/** Table 333 in PDF 32000-1:2008 §14.8.4.2
*/
enum class DocumentStructureType {
kDocument,
kPart,
kArt, // Article
kSect, // Section
kDiv,
kBlockQuote,
kCaption,
kTOC, // Table of Contents
kTOCI, // Table of Contents Item
kIndex,
kNonStruct,
kPrivate,
kH, // Heading
kH1, // Heading level 1
kH2,
kH3,
kH4,
kH5,
kH6, // Heading level 6
kP, // Paragraph
kL, // List
kLI, // List item
kLbl, // List item label
kLBody, // List item body
kTable,
kTR,
kTH,
kTD,
kTHead,
kTBody,
kTFoot,
kSpan,
kQuote,
kNote,
kReference,
kBibEntry,
kCode,
kLink,
kAnnot,
kRuby,
kWarichu,
kFigure,
kFormula,
kForm, // Form control (not like an HTML FORM element)
kDocument, //!< Document
kPart, //!< Part
kArt, //!< Article
kSect, //!< Section
kDiv, //!< Division
kBlockQuote, //!< Block quotation
kCaption, //!< Caption
kTOC, //!< Table of Contents
kTOCI, //!< Table of Contents Item
kIndex, //!< Index
kNonStruct, //!< Nonstructural element
kPrivate, //!< Private element
kH, //!< Heading
kH1, //!< Heading level 1
kH2, //!< Heading level 2
kH3, //!< Heading level 3
kH4, //!< Heading level 4
kH5, //!< Heading level 5
kH6, //!< Heading level 6
kP, //!< Paragraph
kL, //!< List
kLI, //!< List item
kLbl, //!< List item label
kLBody, //!< List item body
kTable, //!< Table
kTR, //!< Table row
kTH, //!< Table header cell
kTD, //!< Table data cell
kTHead, //!< Table header row group
kTBody, //!< Table body row group
kTFoot, //!< table footer row group
kSpan, //!< Span
kQuote, //!< Quotation
kNote, //!< Note
kReference, //!< Reference
kBibEntry, //!< Bibliography entry
kCode, //!< Code
kLink, //!< Link
kAnnot, //!< Annotation
kRuby, //!< Ruby annotation
kRB, //!< Ruby base text
kRT, //!< Ruby annotation text
kRP, //!< Ruby punctuation
kWarichu, //!< Warichu annotation
kWT, //!< Warichu text
kWP, //!< Warichu punctuation
kFigure, //!< Figure
kFormula, //!< Formula
kForm, //!< Form control (not like an HTML FORM element)
};
/**
* A node in a PDF structure tree, giving a semantic representation
* of the content. Each node ID is associated with content
* by passing the SkCanvas and node ID to SkPDF::SetNodeId() when drawing.
*/
/** A node in a PDF structure tree, giving a semantic representation
of the content. Each node ID is associated with content
by passing the SkCanvas and node ID to SkPDF::SetNodeId() when drawing.
NodeIDs should be unique within each tree.
*/
struct StructureElementNode {
const StructureElementNode* fChildren = nullptr;
size_t fChildCount;
@ -135,12 +142,23 @@ struct Metadata {
*/
int fEncodingQuality = 101;
/**
* An optional tree of structured document tags that provide
* a semantic representation of the content. The caller
* should retain ownership.
*/
/** An optional tree of structured document tags that provide
a semantic representation of the content. The caller
should retain ownership.
*/
const StructureElementNode* fStructureElementTreeRoot = nullptr;
/** Executor to handle threaded work within PDF Backend. If this is nullptr,
then all work will be done serially on the main thread. To have worker
threads assist with various tasks, set this to a valid SkExecutor
instance. Currently used for executing Deflate algorithm in parallel.
If set, the PDF output will be non-reproducible in the order and
internal numbering of objects, but should render the same.
Experimental.
*/
SkExecutor* fExecutor = nullptr;
};
/** Associate a node ID with subsequent drawing commands in an

Просмотреть файл

@ -31,10 +31,6 @@ protected:
*/
virtual SkScalar next(SkPath* dst, SkScalar dist, SkPathMeasure&) const = 0;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
bool exposedInAndroidJavaAPI() const override { return true; }
#endif
private:
typedef SkPathEffect INHERITED;
};
@ -58,8 +54,6 @@ public:
*/
static sk_sp<SkPathEffect> Make(const SkPath& path, SkScalar advance, SkScalar phase, Style);
Factory getFactory() const override { return CreateProc; }
protected:
SkPath1DPathEffect(const SkPath& path, SkScalar advance, SkScalar phase, Style);
void flatten(SkWriteBuffer&) const override;
@ -70,8 +64,7 @@ protected:
SkScalar next(SkPath*, SkScalar, SkPathMeasure&) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SK_FLATTENABLE_HOOKS(SkPath1DPathEffect)
SkPath fPath; // copied from constructor
SkScalar fAdvance; // copied from constructor

Просмотреть файл

@ -60,8 +60,6 @@ public:
}
Factory getFactory() const override { return CreateProc; }
protected:
SkLine2DPathEffect(SkScalar width, const SkMatrix& matrix)
: Sk2DPathEffect(matrix), fWidth(width) {
@ -73,8 +71,7 @@ protected:
void nextSpan(int u, int v, int ucount, SkPath*) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SK_FLATTENABLE_HOOKS(SkLine2DPathEffect)
SkScalar fWidth;
@ -91,8 +88,6 @@ public:
return sk_sp<SkPathEffect>(new SkPath2DPathEffect(matrix, path));
}
Factory getFactory() const override { return CreateProc; }
protected:
SkPath2DPathEffect(const SkMatrix&, const SkPath&);
void flatten(SkWriteBuffer&) const override;
@ -100,8 +95,7 @@ protected:
void next(const SkPoint&, int u, int v, SkPath*) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SK_FLATTENABLE_HOOKS(SkPath2DPathEffect)
SkPath fPath;

Просмотреть файл

@ -26,7 +26,7 @@ public:
const SkImageFilter::CropRect* cropRect = nullptr);
static void InitializeFlattenables();
static void RegisterFlattenables();
};
#endif

Просмотреть файл

@ -26,7 +26,7 @@ public:
sk_sp<SkImageFilter> foreground,
const SkImageFilter::CropRect* cropRect);
static void InitializeFlattenables();
static void RegisterFlattenables();
private:
SkArithmeticImageFilter(); // can't instantiate

Просмотреть файл

@ -16,6 +16,8 @@
* its original position.
*/
namespace SkBlurDrawLooper {
sk_sp<SkDrawLooper> SK_API Make(SkColor4f color, SkColorSpace* cs,
SkScalar sigma, SkScalar dx, SkScalar dy);
sk_sp<SkDrawLooper> SK_API Make(SkColor color, SkScalar sigma, SkScalar dx, SkScalar dy);
};

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше