diff --git a/browser/base/content/aboutNetError.xhtml b/browser/base/content/aboutNetError.xhtml
index e07e031d79..ddc60924ce 100644
--- a/browser/base/content/aboutNetError.xhtml
+++ b/browser/base/content/aboutNetError.xhtml
@@ -291,6 +291,8 @@
&nssFailure2.title;
&nssBadCert.title;
&malwareBlocked.title;
+ &unwantedBlocked.title;
+ &forbiddenBlocked.title;
&cspBlocked.title;
&remoteXUL.title;
&corruptedContentError.title;
@@ -317,6 +319,8 @@
&nssFailure2.longDesc2;
&nssBadCert.longDesc2;
&malwareBlocked.longDesc;
+ &unwantedBlocked.longDesc;
+ &forbiddenBlocked.longDesc;
&cspBlocked.longDesc;
&remoteXUL.longDesc;
&corruptedContentError.longDesc;
diff --git a/browser/locales/en-US/chrome/overrides/appstrings.properties b/browser/locales/en-US/chrome/overrides/appstrings.properties
index 1bf5447485..1d0a6a036b 100644
--- a/browser/locales/en-US/chrome/overrides/appstrings.properties
+++ b/browser/locales/en-US/chrome/overrides/appstrings.properties
@@ -30,7 +30,9 @@ externalProtocolUnknown=
externalProtocolChkMsg=Remember my choice for all links of this type.
externalProtocolLaunchBtn=Launch application
malwareBlocked=The site at %S has been reported as an attack site and has been blocked based on your security preferences.
+unwantedBlocked=The site at %S has been reported as serving unwanted software and has been blocked based on your security preferences.
phishingBlocked=The website at %S has been reported as a web forgery designed to trick users into sharing personal or financial information.
+forbiddenBlocked=The site at %S has been blocked by your browser configuration.
cspBlocked=This page has a content security policy that prevents it from being embedded in this way.
xssBlockMode=This page contains an XSS attack that has been blocked for your security.
corruptedContentError=The page you are trying to view cannot be shown because an error in the data transmission was detected.
diff --git a/browser/locales/en-US/chrome/overrides/netError.dtd b/browser/locales/en-US/chrome/overrides/netError.dtd
index 3ed288d900..6d25902b04 100644
--- a/browser/locales/en-US/chrome/overrides/netError.dtd
+++ b/browser/locales/en-US/chrome/overrides/netError.dtd
@@ -164,12 +164,21 @@ be temporary, and you can try again later.
Website owners who believe their site has been reported as an attack site in error may request a review.
">
+
+Unwanted software pages try to install software that can be deceptive and affect your system in unexpected ways.
+">
+
Entering any personal information on this page may result in identity theft or other fraud.
These types of web forgeries are used in scams known as phishing attacks, in which fraudulent web pages and emails are used to imitate sources you may trust.
">
+
+&brandShortName; prevented this page from loading because it is configured to block it.
+">
+
&brandShortName; prevented this page from loading in this way because the page has a content security policy that disallows it.">
diff --git a/db/sqlite3/src/moz.build b/db/sqlite3/src/moz.build
index 23ef1cae48..d190924f21 100644
--- a/db/sqlite3/src/moz.build
+++ b/db/sqlite3/src/moz.build
@@ -57,6 +57,10 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
DEFINES['SQLITE_ENABLE_LOCKING_STYLE'] = 1
+# sqlite defaults this to on on __APPLE_ but it breaks on newer iOS SDKs
+if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'uikit':
+ DEFINES['SQLITE_ENABLE_LOCKING_STYLE'] = 0
+
# Turn on SQLite's assertions in debug builds.
if CONFIG['MOZ_DEBUG']:
DEFINES['SQLITE_DEBUG'] = 1
diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp
index e062d9b8e6..d6b0c773ff 100644
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -4882,7 +4882,9 @@ nsDocShell::DisplayLoadError(nsresult aError, nsIURI* aURI,
}
}
} else if (NS_ERROR_PHISHING_URI == aError ||
- NS_ERROR_MALWARE_URI == aError) {
+ NS_ERROR_MALWARE_URI == aError ||
+ NS_ERROR_UNWANTED_URI == aError ||
+ NS_ERROR_FORBIDDEN_URI == aError) {
nsAutoCString host;
aURI->GetHost(host);
CopyUTF8toUTF16(host, formatStrs[0]);
@@ -7687,6 +7689,8 @@ nsDocShell::EndPageLoad(nsIWebProgress* aProgress,
aStatus == NS_ERROR_OFFLINE ||
aStatus == NS_ERROR_MALWARE_URI ||
aStatus == NS_ERROR_PHISHING_URI ||
+ aStatus == NS_ERROR_UNWANTED_URI ||
+ aStatus == NS_ERROR_FORBIDDEN_URI ||
aStatus == NS_ERROR_UNSAFE_CONTENT_TYPE ||
aStatus == NS_ERROR_REMOTE_XUL ||
aStatus == NS_ERROR_INTERCEPTION_FAILED ||
diff --git a/docshell/resources/content/netError.xhtml b/docshell/resources/content/netError.xhtml
index 98d1e72a3d..922dadb790 100644
--- a/docshell/resources/content/netError.xhtml
+++ b/docshell/resources/content/netError.xhtml
@@ -5,6 +5,9 @@
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
%htmlDTD;
+
+ %netErrorAppDTD;
%netErrorDTD;
@@ -291,6 +294,8 @@
&nssFailure2.title;
&nssBadCert.title;
&malwareBlocked.title;
+ &unwantedBlocked.title;
+ &forbiddenBlocked.title;
&cspBlocked.title;
&remoteXUL.title;
&corruptedContentError.title;
@@ -317,6 +322,8 @@
&nssFailure2.longDesc2;
&nssBadCert.longDesc2;
&malwareBlocked.longDesc;
+ &unwantedBlocked.longDesc;
+ &forbiddenBlocked.longDesc;
&cspBlocked.longDesc;
&remoteXUL.longDesc;
&corruptedContentError.longDesc;
diff --git a/dom/base/nsContentList.cpp b/dom/base/nsContentList.cpp
index a26d73ce94..389b90e4fa 100644
--- a/dom/base/nsContentList.cpp
+++ b/dom/base/nsContentList.cpp
@@ -579,9 +579,10 @@ nsContentList::GetSupportedNames(unsigned aFlags, nsTArray& aNames)
}
}
- aNames.SetCapacity(atoms.Length());
- for (uint32_t i = 0; i < atoms.Length(); ++i) {
- aNames.AppendElement(nsDependentAtomString(atoms[i]));
+ uint32_t atomsLen = atoms.Length();
+ nsString* names = aNames.AppendElements(atomsLen);
+ for (uint32_t i = 0; i < atomsLen; ++i) {
+ atoms[i]->ToString(names[i]);
}
}
diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp
index a779fe741d..956293ce96 100644
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -162,6 +162,7 @@
#include "nsIURIWithPrincipal.h"
#include "nsIURL.h"
#include "nsIWebNavigation.h"
+#include "nsIWindowMediator.h"
#include "nsIWordBreaker.h"
#include "nsIXPConnect.h"
#include "nsJSUtils.h"
@@ -5172,6 +5173,23 @@ nsContentUtils::GetWindowProviderForContentProcess()
return ContentChild::GetSingleton();
}
+/* static */
+already_AddRefed
+nsContentUtils::GetMostRecentNonPBWindow()
+{
+ nsCOMPtr windowMediator =
+ do_GetService(NS_WINDOWMEDIATOR_CONTRACTID);
+ nsCOMPtr wm = do_QueryInterface(windowMediator);
+
+ nsCOMPtr window;
+ wm->GetMostRecentNonPBWindow(MOZ_UTF16("navigator:browser"),
+ getter_AddRefs(window));
+ nsCOMPtr pwindow;
+ pwindow = do_QueryInterface(window);
+
+ return pwindow.forget();
+}
+
/* static */
void
nsContentUtils::WarnScriptWasIgnored(nsIDocument* aDocument)
diff --git a/dom/base/nsContentUtils.h b/dom/base/nsContentUtils.h
index 70ea5510c0..81ea4ea5fe 100644
--- a/dom/base/nsContentUtils.h
+++ b/dom/base/nsContentUtils.h
@@ -1653,6 +1653,11 @@ public:
static nsIWindowProvider*
GetWindowProviderForContentProcess();
+ // Returns the browser window with the most recent time stamp that is
+ // not in private browsing mode.
+ static already_AddRefed
+ GetMostRecentNonPBWindow();
+
/**
* Call this function if !IsSafeToRunScript() and we fail to run the script
* (rather than using AddScriptRunner as we usually do). |aDocument| is
diff --git a/dom/base/nsDOMMutationObserver.cpp b/dom/base/nsDOMMutationObserver.cpp
index 19f2125998..424128d6d6 100644
--- a/dom/base/nsDOMMutationObserver.cpp
+++ b/dom/base/nsDOMMutationObserver.cpp
@@ -759,12 +759,14 @@ nsDOMMutationObserver::GetObservingInfo(
info.mAttributeFilter.Construct();
mozilla::dom::Sequence& filtersAsStrings =
info.mAttributeFilter.Value();
+ nsString* strings = filtersAsStrings.AppendElements(filters.Count(),
+ mozilla::fallible);
+ if (!strings) {
+ aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
+ return;
+ }
for (int32_t j = 0; j < filters.Count(); ++j) {
- if (!filtersAsStrings.AppendElement(nsDependentAtomString(filters[j]),
- mozilla::fallible)) {
- aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
- return;
- }
+ filters[j]->ToString(strings[j]);
}
}
info.mObservedNode = mr->Target();
diff --git a/dom/browser-element/BrowserElementChildPreload.js b/dom/browser-element/BrowserElementChildPreload.js
index 59b7f6c364..9bd0cb9642 100644
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -2000,6 +2000,12 @@ BrowserElementChild.prototype = {
case Cr.NS_ERROR_MALWARE_URI :
sendAsyncMsg('error', { type: 'malwareBlocked' });
return;
+ case Cr.NS_ERROR_UNWANTED_URI :
+ sendAsyncMsg('error', { type: 'unwantedBlocked' });
+ return;
+ case Cr.NS_ERROR_FORBIDDEN_URI :
+ sendAsyncMsg('error', { type: 'forbiddenBlocked' });
+ return;
case Cr.NS_ERROR_OFFLINE :
sendAsyncMsg('error', { type: 'offline' });
diff --git a/dom/canvas/test/test_canvas.html b/dom/canvas/test/test_canvas.html
index 10e2057620..e9d2af1546 100644
--- a/dom/canvas/test/test_canvas.html
+++ b/dom/canvas/test/test_canvas.html
@@ -14457,12 +14457,7 @@ ctx.moveTo(50, 25);
ctx.bezierCurveTo(50, 25, 50, 25, 50, 25);
ctx.stroke();
-if (IsAzureSkia()) {
- isPixel(ctx, 50,25, 0,255,0,255, 0);
-} else {
- todo_isPixel(ctx, 50,25, 0,255,0,255, 0);
-}
-
+todo_isPixel(ctx, 50,25, 0,255,0,255, 0);
}
@@ -14494,11 +14489,7 @@ ctx.moveTo(50, 25);
ctx.lineTo(50, 25);
ctx.stroke();
-if (IsAzureSkia()) {
- isPixel(ctx, 50,25, 0,255,0,255, 0);
-} else {
- todo_isPixel(ctx, 50,25, 0,255,0,255, 0);
-}
+todo_isPixel(ctx, 50,25, 0,255,0,255, 0);
}
diff --git a/dom/html/HTMLAllCollection.cpp b/dom/html/HTMLAllCollection.cpp
index 85ef7d5081..098fd3ffcf 100644
--- a/dom/html/HTMLAllCollection.cpp
+++ b/dom/html/HTMLAllCollection.cpp
@@ -202,9 +202,10 @@ HTMLAllCollection::GetSupportedNames(unsigned aFlags, nsTArray& aNames
}
}
- aNames.SetCapacity(atoms.Length());
- for (uint32_t i = 0; i < atoms.Length(); ++i) {
- aNames.AppendElement(nsDependentAtomString(atoms[i]));
+ uint32_t atomsLen = atoms.Length();
+ nsString* names = aNames.AppendElements(atomsLen);
+ for (uint32_t i = 0; i < atomsLen; ++i) {
+ atoms[i]->ToString(names[i]);
}
}
diff --git a/dom/html/HTMLInputElement.cpp b/dom/html/HTMLInputElement.cpp
index b7dc413a98..4c03e0a730 100644
--- a/dom/html/HTMLInputElement.cpp
+++ b/dom/html/HTMLInputElement.cpp
@@ -2157,10 +2157,13 @@ HTMLInputElement::MozSetFileNameArray(const char16_t** aFileNames, uint32_t aLen
}
Sequence list;
+ nsString* names = list.AppendElements(aLength, fallible);
+ if (!names) {
+ return NS_ERROR_OUT_OF_MEMORY;
+ }
for (uint32_t i = 0; i < aLength; ++i) {
- if (!list.AppendElement(nsDependentString(aFileNames[i]), fallible)) {
- return NS_ERROR_OUT_OF_MEMORY;
- }
+ const char16_t* filename = aFileNames[i];
+ names[i].Rebind(filename, nsCharTraits::length(filename));
}
ErrorResult rv;
diff --git a/dom/html/HTMLOptionsCollection.cpp b/dom/html/HTMLOptionsCollection.cpp
index 3902dbee70..b4611aaf49 100644
--- a/dom/html/HTMLOptionsCollection.cpp
+++ b/dom/html/HTMLOptionsCollection.cpp
@@ -309,9 +309,10 @@ HTMLOptionsCollection::GetSupportedNames(unsigned aFlags,
}
}
- aNames.SetCapacity(atoms.Length());
- for (uint32_t i = 0; i < atoms.Length(); ++i) {
- aNames.AppendElement(nsDependentAtomString(atoms[i]));
+ uint32_t atomsLen = atoms.Length();
+ nsString* names = aNames.AppendElements(atomsLen);
+ for (uint32_t i = 0; i < atomsLen; ++i) {
+ atoms[i]->ToString(names[i]);
}
}
diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp
index b96181709c..52b211eab6 100755
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -143,7 +143,6 @@
#include "nsISystemMessagesInternal.h"
#include "nsITimer.h"
#include "nsIURIFixup.h"
-#include "nsIWindowMediator.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIXULWindow.h"
#include "nsIDOMChromeWindow.h"
@@ -5373,38 +5372,6 @@ ContentParent::DeallocPContentPermissionRequestParent(PContentPermissionRequestP
return true;
}
-static already_AddRefed
-FindMostRecentOpenWindow()
-{
- nsCOMPtr windowMediator =
- do_GetService(NS_WINDOWMEDIATOR_CONTRACTID);
- nsCOMPtr windowEnumerator;
- windowMediator->GetEnumerator(MOZ_UTF16("navigator:browser"),
- getter_AddRefs(windowEnumerator));
-
- nsCOMPtr latest;
-
- bool hasMore = false;
- MOZ_ALWAYS_TRUE(NS_SUCCEEDED(windowEnumerator->HasMoreElements(&hasMore)));
- while (hasMore) {
- nsCOMPtr item;
- MOZ_ALWAYS_TRUE(NS_SUCCEEDED(windowEnumerator->GetNext(getter_AddRefs(item))));
- nsCOMPtr window = do_QueryInterface(item);
-
- if (window) {
- bool closed = false;
- window->GetClosed(&closed);
- if (!closed) {
- latest = window;
- }
- }
-
- MOZ_ALWAYS_TRUE(NS_SUCCEEDED(windowEnumerator->HasMoreElements(&hasMore)));
- }
-
- return latest.forget();
-}
-
bool
ContentParent::RecvCreateWindow(PBrowserParent* aThisTab,
PBrowserParent* aNewTab,
@@ -5482,7 +5449,7 @@ ContentParent::RecvCreateWindow(PBrowserParent* aThisTab,
// If we haven't found a chrome window to open in, just use the most recently
// opened one.
if (!parent) {
- parent = FindMostRecentOpenWindow();
+ parent = nsContentUtils::GetMostRecentNonPBWindow();
if (NS_WARN_IF(!parent)) {
*aResult = NS_ERROR_FAILURE;
return true;
diff --git a/dom/locales/en-US/chrome/appstrings.properties b/dom/locales/en-US/chrome/appstrings.properties
index 910c2edf58..7ee76cd02b 100644
--- a/dom/locales/en-US/chrome/appstrings.properties
+++ b/dom/locales/en-US/chrome/appstrings.properties
@@ -29,7 +29,9 @@ externalProtocolUnknown=
externalProtocolChkMsg=Remember my choice for all links of this type.
externalProtocolLaunchBtn=Launch application
malwareBlocked=The site at %S has been reported as an attack site and has been blocked based on your security preferences.
+unwantedBlocked=The site at %S has been reported as serving unwanted software and has been blocked based on your security preferences.
phishingBlocked=The website at %S has been reported as a web forgery designed to trick users into sharing personal or financial information.
+forbiddenBlocked=The site at %S has been blocked by your browser configuration.
cspBlocked=This page has a content security policy that prevents it from being loaded in this way.
corruptedContentError=The page you are trying to view cannot be shown because an error in the data transmission was detected.
remoteXUL=This page uses an unsupported technology that is no longer available by default.
diff --git a/dom/locales/en-US/chrome/netError.dtd b/dom/locales/en-US/chrome/netError.dtd
index e13a57e0c9..d379108f53 100644
--- a/dom/locales/en-US/chrome/netError.dtd
+++ b/dom/locales/en-US/chrome/netError.dtd
@@ -87,6 +87,16 @@
These types of web forgeries are used in scams known as phishing attacks, in which fraudulent web pages and emails are used to imitate sources you may trust.
">
+
+The browser prevented this page from loading because it is configured to block it.
+">
+
+
+You should not add an exception if you are using an internet connection that you do not trust completely or if you are not used to seeing a warning for this server.
+If you still wish to add an exception for this site, you can do so in your advanced encryption settings.
+">
+
The browser prevented this page from loading in this way because the page has a content security policy that disallows it.">
@@ -95,10 +105,3 @@
- Please contact the website owners to inform them of this problem.
">
-
-
-
-%netErrorAppDTD;
diff --git a/dom/locales/en-US/chrome/netErrorApp.dtd b/dom/locales/en-US/chrome/netErrorApp.dtd
index 54e8da32b6..d245555380 100644
--- a/dom/locales/en-US/chrome/netErrorApp.dtd
+++ b/dom/locales/en-US/chrome/netErrorApp.dtd
@@ -2,12 +2,22 @@
- 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/. -->
-
+
+
+
diff --git a/dom/telephony/TelephonyDialCallback.cpp b/dom/telephony/TelephonyDialCallback.cpp
index d3a632944a..c67785cc41 100644
--- a/dom/telephony/TelephonyDialCallback.cpp
+++ b/dom/telephony/TelephonyDialCallback.cpp
@@ -121,8 +121,10 @@ TelephonyDialCallback::NotifyDialMMISuccessWithStrings(const nsAString& aStatusM
result.mStatusMessage.Assign(aStatusMessage);
nsTArray additionalInformation;
+ nsString* infos = additionalInformation.AppendElements(aCount);
for (uint32_t i = 0; i < aCount; i++) {
- additionalInformation.AppendElement(nsDependentString(aAdditionalInformation[i]));
+ infos[i].Rebind(aAdditionalInformation[i],
+ nsCharTraits::length(aAdditionalInformation[i]));
}
JS::Rooted jsAdditionalInformation(cx);
diff --git a/dom/telephony/ipc/TelephonyParent.cpp b/dom/telephony/ipc/TelephonyParent.cpp
index 68015c23b8..3ed8b0cdf4 100644
--- a/dom/telephony/ipc/TelephonyParent.cpp
+++ b/dom/telephony/ipc/TelephonyParent.cpp
@@ -41,7 +41,7 @@ TelephonyParent::RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActo
nsCOMPtr service = do_GetService(TELEPHONY_SERVICE_CONTRACTID);
if (!service) {
- return NS_SUCCEEDED(actor->NotifyError(NS_LITERAL_STRING("InvalidStateError")));
+ return NS_SUCCEEDED(actor->GetCallback()->NotifyError(NS_LITERAL_STRING("InvalidStateError")));
}
switch (aRequest.type()) {
@@ -57,79 +57,79 @@ TelephonyParent::RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActo
case IPCTelephonyRequest::TDialRequest: {
const DialRequest& request = aRequest.get_DialRequest();
service->Dial(request.clientId(), request.number(),
- request.isEmergency(), actor);
+ request.isEmergency(), actor->GetDialCallback());
return true;
}
case IPCTelephonyRequest::TSendUSSDRequest: {
const SendUSSDRequest& request = aRequest.get_SendUSSDRequest();
- service->SendUSSD(request.clientId(), request.ussd(), actor);
+ service->SendUSSD(request.clientId(), request.ussd(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TCancelUSSDRequest: {
const CancelUSSDRequest& request = aRequest.get_CancelUSSDRequest();
- service->CancelUSSD(request.clientId(), actor);
+ service->CancelUSSD(request.clientId(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TConferenceCallRequest: {
const ConferenceCallRequest& request = aRequest.get_ConferenceCallRequest();
- service->ConferenceCall(request.clientId(), actor);
+ service->ConferenceCall(request.clientId(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TSeparateCallRequest: {
const SeparateCallRequest& request = aRequest.get_SeparateCallRequest();
- service->SeparateCall(request.clientId(), request.callIndex(), actor);
+ service->SeparateCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::THangUpConferenceRequest: {
const HangUpConferenceRequest& request = aRequest.get_HangUpConferenceRequest();
- service->HangUpConference(request.clientId(), actor);
+ service->HangUpConference(request.clientId(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::THoldConferenceRequest: {
const HoldConferenceRequest& request = aRequest.get_HoldConferenceRequest();
- service->HoldConference(request.clientId(), actor);
+ service->HoldConference(request.clientId(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TResumeConferenceRequest: {
const ResumeConferenceRequest& request = aRequest.get_ResumeConferenceRequest();
- service->ResumeConference(request.clientId(), actor);
+ service->ResumeConference(request.clientId(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TAnswerCallRequest: {
const AnswerCallRequest& request = aRequest.get_AnswerCallRequest();
- service->AnswerCall(request.clientId(), request.callIndex(), actor);
+ service->AnswerCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::THangUpCallRequest: {
const HangUpCallRequest& request = aRequest.get_HangUpCallRequest();
- service->HangUpCall(request.clientId(), request.callIndex(), actor);
+ service->HangUpCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TRejectCallRequest: {
const RejectCallRequest& request = aRequest.get_RejectCallRequest();
- service->RejectCall(request.clientId(), request.callIndex(), actor);
+ service->RejectCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::THoldCallRequest: {
const HoldCallRequest& request = aRequest.get_HoldCallRequest();
- service->HoldCall(request.clientId(), request.callIndex(), actor);
+ service->HoldCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
case IPCTelephonyRequest::TResumeCallRequest: {
const ResumeCallRequest& request = aRequest.get_ResumeCallRequest();
- service->ResumeCall(request.clientId(), request.callIndex(), actor);
+ service->ResumeCall(request.clientId(), request.callIndex(), actor->GetCallback());
return true;
}
@@ -139,7 +139,7 @@ TelephonyParent::RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActo
request.dtmfChars(),
request.pauseDuration(),
request.toneDuration(),
- actor);
+ actor->GetCallback());
return true;
}
@@ -338,12 +338,12 @@ TelephonyParent::SupplementaryServiceNotification(uint32_t aClientId,
******************************************************************************/
NS_IMPL_ISUPPORTS(TelephonyRequestParent,
- nsITelephonyListener,
- nsITelephonyCallback,
- nsITelephonyDialCallback)
+ nsITelephonyListener)
TelephonyRequestParent::TelephonyRequestParent()
- : mActorDestroyed(false)
+ : mActorDestroyed(false),
+ mCallback(new Callback(*this)),
+ mDialCallback(new DialCallback(*this))
{
}
@@ -413,60 +413,80 @@ TelephonyRequestParent::SupplementaryServiceNotification(uint32_t aClientId,
MOZ_CRASH("Not a TelephonyParent!");
}
-// nsITelephonyDialCallback
+/*******************************************************************************
+ * TelephonyRequestParent::Callback
+ ******************************************************************************/
-NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMI(const nsAString& aServiceCode)
+NS_IMPL_ISUPPORTS(TelephonyRequestParent::Callback,
+ nsITelephonyCallback)
+
+nsresult TelephonyRequestParent::Callback::SendResponse(const IPCTelephonyResponse& aResponse)
{
- NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
- return SendNotifyDialMMI(nsAutoString(aServiceCode)) ? NS_OK : NS_ERROR_FAILURE;
+ return mParent.SendResponse(aResponse);
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifySuccess()
+TelephonyRequestParent::Callback::NotifySuccess()
{
return SendResponse(SuccessResponse());
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyError(const nsAString& aError)
+TelephonyRequestParent::Callback::NotifyError(const nsAString& aError)
{
return SendResponse(ErrorResponse(nsAutoString(aError)));
}
+/*******************************************************************************
+ * TelephonyRequestParent::DialCallback
+ ******************************************************************************/
+
+NS_IMPL_ISUPPORTS_INHERITED(TelephonyRequestParent::DialCallback,
+ TelephonyRequestParent::Callback,
+ nsITelephonyDialCallback)
+
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialCallSuccess(uint32_t aClientId,
- uint32_t aCallIndex,
- const nsAString& aNumber)
+TelephonyRequestParent::DialCallback::NotifyDialMMI(const nsAString& aServiceCode)
+{
+ NS_ENSURE_TRUE(!mParent.mActorDestroyed, NS_ERROR_FAILURE);
+
+ return mParent.SendNotifyDialMMI(nsAutoString(aServiceCode)) ? NS_OK : NS_ERROR_FAILURE;
+}
+
+NS_IMETHODIMP
+TelephonyRequestParent::DialCallback::NotifyDialCallSuccess(uint32_t aClientId,
+ uint32_t aCallIndex,
+ const nsAString& aNumber)
{
return SendResponse(DialResponseCallSuccess(aClientId, aCallIndex,
nsAutoString(aNumber)));
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMISuccess(const nsAString& aStatusMessage)
+TelephonyRequestParent::DialCallback::NotifyDialMMISuccess(const nsAString& aStatusMessage)
{
return SendResponse(DialResponseMMISuccess(nsAutoString(aStatusMessage),
AdditionalInformation(mozilla::void_t())));
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMISuccessWithInteger(const nsAString& aStatusMessage,
- uint16_t aAdditionalInformation)
+TelephonyRequestParent::DialCallback::NotifyDialMMISuccessWithInteger(const nsAString& aStatusMessage,
+ uint16_t aAdditionalInformation)
{
return SendResponse(DialResponseMMISuccess(nsAutoString(aStatusMessage),
AdditionalInformation(aAdditionalInformation)));
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMISuccessWithStrings(const nsAString& aStatusMessage,
- uint32_t aCount,
- const char16_t** aAdditionalInformation)
+TelephonyRequestParent::DialCallback::NotifyDialMMISuccessWithStrings(const nsAString& aStatusMessage,
+ uint32_t aCount,
+ const char16_t** aAdditionalInformation)
{
nsTArray additionalInformation;
+ nsString* infos = additionalInformation.AppendElements(aCount);
for (uint32_t i = 0; i < aCount; i++) {
- additionalInformation.AppendElement(nsDependentString(aAdditionalInformation[i]));
+ infos[i].Rebind(aAdditionalInformation[i],
+ nsCharTraits::length(aAdditionalInformation[i]));
}
return SendResponse(DialResponseMMISuccess(nsAutoString(aStatusMessage),
@@ -474,9 +494,9 @@ TelephonyRequestParent::NotifyDialMMISuccessWithStrings(const nsAString& aStatus
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMISuccessWithCallForwardingOptions(const nsAString& aStatusMessage,
- uint32_t aCount,
- nsIMobileCallForwardingOptions** aAdditionalInformation)
+TelephonyRequestParent::DialCallback::NotifyDialMMISuccessWithCallForwardingOptions(const nsAString& aStatusMessage,
+ uint32_t aCount,
+ nsIMobileCallForwardingOptions** aAdditionalInformation)
{
nsTArray additionalInformation;
for (uint32_t i = 0; i < aCount; i++) {
@@ -488,15 +508,15 @@ TelephonyRequestParent::NotifyDialMMISuccessWithCallForwardingOptions(const nsAS
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMIError(const nsAString& aError)
+TelephonyRequestParent::DialCallback::NotifyDialMMIError(const nsAString& aError)
{
return SendResponse(DialResponseMMIError(nsAutoString(aError),
AdditionalInformation(mozilla::void_t())));
}
NS_IMETHODIMP
-TelephonyRequestParent::NotifyDialMMIErrorWithInfo(const nsAString& aError,
- uint16_t aInfo)
+TelephonyRequestParent::DialCallback::NotifyDialMMIErrorWithInfo(const nsAString& aError,
+ uint16_t aInfo)
{
return SendResponse(DialResponseMMIError(nsAutoString(aError),
AdditionalInformation(aInfo)));
diff --git a/dom/telephony/ipc/TelephonyParent.h b/dom/telephony/ipc/TelephonyParent.h
index cc96bef459..d56ea9c511 100644
--- a/dom/telephony/ipc/TelephonyParent.h
+++ b/dom/telephony/ipc/TelephonyParent.h
@@ -72,15 +72,42 @@ private:
class TelephonyRequestParent : public PTelephonyRequestParent
, public nsITelephonyListener
- , public nsITelephonyDialCallback
{
friend class TelephonyParent;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSITELEPHONYLISTENER
- NS_DECL_NSITELEPHONYCALLBACK
- NS_DECL_NSITELEPHONYDIALCALLBACK
+
+ class Callback : public nsITelephonyCallback {
+ friend class TelephonyRequestParent;
+
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSITELEPHONYCALLBACK
+
+ protected:
+ explicit Callback(TelephonyRequestParent& aParent): mParent(aParent) {}
+ virtual ~Callback() {}
+
+ private:
+ nsresult SendResponse(const IPCTelephonyResponse& aResponse);
+ TelephonyRequestParent& mParent;
+ };
+
+ class DialCallback final : public Callback
+ , public nsITelephonyDialCallback {
+ friend class TelephonyRequestParent;
+
+ public:
+ NS_DECL_ISUPPORTS_INHERITED
+ NS_DECL_NSITELEPHONYDIALCALLBACK
+ NS_FORWARD_NSITELEPHONYCALLBACK(Callback::)
+
+ private:
+ explicit DialCallback(TelephonyRequestParent& aParent): Callback(aParent) {}
+ ~DialCallback() {}
+ };
protected:
TelephonyRequestParent();
@@ -92,8 +119,20 @@ protected:
nsresult
SendResponse(const IPCTelephonyResponse& aResponse);
+ Callback*
+ GetCallback() {
+ return mCallback;
+ }
+
+ DialCallback*
+ GetDialCallback() {
+ return mDialCallback;
+ }
+
private:
bool mActorDestroyed;
+ RefPtr mCallback;
+ RefPtr mDialCallback;
};
END_TELEPHONY_NAMESPACE
diff --git a/dom/workers/ServiceWorkerClients.cpp b/dom/workers/ServiceWorkerClients.cpp
index 4153b6a756..4f9752bbd0 100644
--- a/dom/workers/ServiceWorkerClients.cpp
+++ b/dom/workers/ServiceWorkerClients.cpp
@@ -615,10 +615,9 @@ private:
}
// Find the most recent browser window and open a new tab in it.
- nsCOMPtr browserWindow;
- rv = wm->GetMostRecentWindow(MOZ_UTF16("navigator:browser"),
- getter_AddRefs(browserWindow));
- if (NS_WARN_IF(NS_FAILED(rv)) || !browserWindow) {
+ nsCOMPtr browserWindow =
+ nsContentUtils::GetMostRecentNonPBWindow();
+ if (!browserWindow) {
// It is possible to be running without a browser window on Mac OS, so
// we need to open a new chrome window.
// TODO(catalinb): open new chrome window. Bug 1218080
diff --git a/dom/xul/XULDocument.cpp b/dom/xul/XULDocument.cpp
index 93e3855c63..14a3972d8c 100644
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -259,33 +259,6 @@ namespace dom {
// nsISupports interface
//
-static PLDHashOperator
-TraverseTemplateBuilders(nsISupports* aKey, nsIXULTemplateBuilder* aData,
- void* aContext)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(aContext);
-
- NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb, "mTemplateBuilderTable key");
- cb->NoteXPCOMChild(aKey);
- NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb, "mTemplateBuilderTable value");
- cb->NoteXPCOMChild(aData);
-
- return PL_DHASH_NEXT;
-}
-
-static PLDHashOperator
-TraverseObservers(nsIURI* aKey, nsIObserver* aData, void* aContext)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(aContext);
-
- NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb, "mOverlayLoadObservers/mPendingOverlayLoadNotifications value");
- cb->NoteXPCOMChild(aData);
-
- return PL_DHASH_NEXT;
-}
-
NS_IMPL_CYCLE_COLLECTION_CLASS(XULDocument)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(XULDocument, XMLDocument)
@@ -296,20 +269,38 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(XULDocument, XMLDocument)
// An element will only have a template builder as long as it's in the
// document, so we'll traverse the table here instead of from the element.
- if (tmp->mTemplateBuilderTable)
- tmp->mTemplateBuilderTable->EnumerateRead(TraverseTemplateBuilders, &cb);
+ if (tmp->mTemplateBuilderTable) {
+ for (auto iter = tmp->mTemplateBuilderTable->Iter();
+ !iter.Done();
+ iter.Next()) {
+ NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mTemplateBuilderTable key");
+ cb.NoteXPCOMChild(iter.Key());
+ NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mTemplateBuilderTable value");
+ cb.NoteXPCOMChild(iter.UserData());
+ }
+ }
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCurrentPrototype)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMasterPrototype)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCommandDispatcher)
- NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPrototypes);
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPrototypes)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLocalStore)
if (tmp->mOverlayLoadObservers) {
- tmp->mOverlayLoadObservers->EnumerateRead(TraverseObservers, &cb);
+ for (auto iter = tmp->mOverlayLoadObservers->Iter();
+ !iter.Done();
+ iter.Next()) {
+ NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mOverlayLoadObservers value");
+ cb.NoteXPCOMChild(iter.Data());
+ }
}
if (tmp->mPendingOverlayLoadNotifications) {
- tmp->mPendingOverlayLoadNotifications->EnumerateRead(TraverseObservers, &cb);
+ for (auto iter = tmp->mPendingOverlayLoadNotifications->Iter();
+ !iter.Done();
+ iter.Next()) {
+ NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mPendingOverlayLoadNotifications value");
+ cb.NoteXPCOMChild(iter.Data());
+ }
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
@@ -916,6 +907,23 @@ XULDocument::AttributeWillChange(nsIDocument* aDocument,
}
}
+static bool
+ShouldPersistAttribute(Element* aElement, nsIAtom* aAttribute)
+{
+ if (aElement->IsXULElement(nsGkAtoms::window)) {
+ // The following attributes of xul:window should be handled in
+ // nsXULWindow::SavePersistentAttributes instead of here.
+ if (aAttribute == nsGkAtoms::screenX ||
+ aAttribute == nsGkAtoms::screenY ||
+ aAttribute == nsGkAtoms::width ||
+ aAttribute == nsGkAtoms::height ||
+ aAttribute == nsGkAtoms::sizemode) {
+ return false;
+ }
+ }
+ return true;
+}
+
void
XULDocument::AttributeChanged(nsIDocument* aDocument,
Element* aElement, int32_t aNameSpaceID,
@@ -995,14 +1003,14 @@ XULDocument::AttributeChanged(nsIDocument* aDocument,
// XXX Namespace handling broken :-(
nsAutoString persist;
aElement->GetAttr(kNameSpaceID_None, nsGkAtoms::persist, persist);
- if (!persist.IsEmpty()) {
+ // Persistence of attributes of xul:window is handled in nsXULWindow.
+ if (ShouldPersistAttribute(aElement, aAttribute) && !persist.IsEmpty() &&
// XXXldb This should check that it's a token, not just a substring.
- if (persist.Find(nsDependentAtomString(aAttribute)) >= 0) {
- nsContentUtils::AddScriptRunner(NS_NewRunnableMethodWithArgs
-
- (this, &XULDocument::DoPersist, aElement, kNameSpaceID_None,
- aAttribute));
- }
+ persist.Find(nsDependentAtomString(aAttribute)) >= 0) {
+ nsContentUtils::AddScriptRunner(NS_NewRunnableMethodWithArgs
+
+ (this, &XULDocument::DoPersist, aElement, kNameSpaceID_None,
+ aAttribute));
}
}
@@ -2534,25 +2542,12 @@ XULDocument::LoadOverlayInternal(nsIURI* aURI, bool aIsDynamic,
if (aIsDynamic)
mResolutionPhase = nsForwardReference::eStart;
- // Chrome documents are allowed to load overlays from anywhere.
- // In all other cases, the overlay is only allowed to load if
- // the master document and prototype document have the same origin.
-
- bool documentIsChrome = IsChromeURI(mDocumentURI);
- if (!documentIsChrome) {
- // Make sure we're allowed to load this overlay.
- rv = NodePrincipal()->CheckMayLoad(aURI, true, false);
- if (NS_FAILED(rv)) {
- *aFailureFromContent = true;
- return rv;
- }
- }
-
// Look in the prototype cache for the prototype document with
// the specified overlay URI. Only use the cache if the containing
// document is chrome otherwise it may not have a system principal and
// the cached document will, see bug 565610.
bool overlayIsChrome = IsChromeURI(aURI);
+ bool documentIsChrome = IsChromeURI(mDocumentURI);
mCurrentPrototype = overlayIsChrome && documentIsChrome ?
nsXULPrototypeCache::GetInstance()->GetPrototype(aURI) : nullptr;
@@ -2636,12 +2631,13 @@ XULDocument::LoadOverlayInternal(nsIURI* aURI, bool aIsDynamic,
rv = NS_NewChannel(getter_AddRefs(channel),
aURI,
NodePrincipal(),
+ nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS |
nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL,
nsIContentPolicy::TYPE_OTHER,
group);
if (NS_SUCCEEDED(rv)) {
- rv = channel->AsyncOpen(listener, nullptr);
+ rv = channel->AsyncOpen2(listener);
}
if (NS_FAILED(rv)) {
@@ -3236,19 +3232,6 @@ XULDocument::LoadScript(nsXULPrototypeScript* aScriptProto, bool* aBlock)
}
}
- // Allow security manager and content policies to veto the load. Note that
- // at this point we already lost context information of the script.
- rv = nsScriptLoader::ShouldLoadScript(
- this,
- static_cast(this),
- aScriptProto->mSrcURI,
- NS_LITERAL_STRING("application/x-javascript"),
- false);
- if (NS_FAILED(rv)) {
- *aBlock = false;
- return rv;
- }
-
// Release script objects from FastLoad since we decided against using them
aScriptProto->UnlinkJSObjects();
@@ -3258,7 +3241,7 @@ XULDocument::LoadScript(nsXULPrototypeScript* aScriptProto, bool* aBlock)
"still loading a script when starting another load?");
mCurrentScriptProto = aScriptProto;
- if (aScriptProto->mSrcLoading) {
+ if (isChromeDoc && aScriptProto->mSrcLoading) {
// Another XULDocument load has started, which is still in progress.
// Remember to ResumeWalk this document when the load completes.
mNextSrcLoadWaiter = aScriptProto->mSrcLoadWaiters;
@@ -3274,9 +3257,8 @@ XULDocument::LoadScript(nsXULPrototypeScript* aScriptProto, bool* aBlock)
aScriptProto->mSrcURI,
this, // aObserver
this, // aRequestingContext
- nsILoadInfo::SEC_NORMAL,
- nsIContentPolicy::TYPE_OTHER,
- nullptr, // aContext
+ nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS,
+ nsIContentPolicy::TYPE_INTERNAL_SCRIPT,
group);
if (NS_FAILED(rv)) {
diff --git a/dom/xul/templates/nsXULTemplateBuilder.cpp b/dom/xul/templates/nsXULTemplateBuilder.cpp
index 0c1527adba..c0aa5920fb 100644
--- a/dom/xul/templates/nsXULTemplateBuilder.cpp
+++ b/dom/xul/templates/nsXULTemplateBuilder.cpp
@@ -222,23 +222,6 @@ nsXULTemplateBuilder::Uninit(bool aIsFinal)
mQueriesCompiled = false;
}
-static PLDHashOperator
-TraverseMatchList(nsISupports* aKey, nsTemplateMatch* aMatch, void* aContext)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(aContext);
-
- cb->NoteXPCOMChild(aKey);
- nsTemplateMatch* match = aMatch;
- while (match) {
- cb->NoteXPCOMChild(match->GetContainer());
- cb->NoteXPCOMChild(match->mResult);
- match = match->mNext;
- }
-
- return PL_DHASH_NEXT;
-}
-
NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULTemplateBuilder)
@@ -269,7 +252,17 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRootResult)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mListeners)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mQueryProcessor)
- tmp->mMatchMap.EnumerateRead(TraverseMatchList, &cb);
+
+ for (auto iter = tmp->mMatchMap.Iter(); !iter.Done(); iter.Next()) {
+ cb.NoteXPCOMChild(iter.Key());
+ nsTemplateMatch* match = iter.UserData();
+ while (match) {
+ cb.NoteXPCOMChild(match->GetContainer());
+ cb.NoteXPCOMChild(match->mResult);
+ match = match->mNext;
+ }
+ }
+
{
uint32_t i, count = tmp->mQuerySets.Length();
for (i = 0; i < count; ++i) {
diff --git a/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp b/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
index e2c01b3336..1cc43f4444 100644
--- a/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
+++ b/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
@@ -51,57 +51,32 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULTemplateQueryProcessorRDF)
tmp->Done();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-static PLDHashOperator
-BindingDependenciesTraverser(nsISupports* key,
- nsXULTemplateQueryProcessorRDF::ResultArray* array,
- void* userArg)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(userArg);
-
- int32_t i, count = array->Length();
- for (i = 0; i < count; ++i) {
- cb->NoteXPCOMChild(array->ElementAt(i));
- }
-
- return PL_DHASH_NEXT;
-}
-
-static PLDHashOperator
-MemoryElementTraverser(const uint32_t& key,
- nsCOMArray* array,
- void* userArg)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(userArg);
-
- int32_t i, count = array->Count();
- for (i = 0; i < count; ++i) {
- cb->NoteXPCOMChild(array->ObjectAt(i));
- }
-
- return PL_DHASH_NEXT;
-}
-
-static PLDHashOperator
-RuleToBindingTraverser(nsISupports* key, RDFBindingSet* binding, void* userArg)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(userArg);
-
- cb->NoteXPCOMChild(key);
-
- return PL_DHASH_NEXT;
-}
-
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXULTemplateQueryProcessorRDF)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDB)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLastRef)
- tmp->mBindingDependencies.EnumerateRead(BindingDependenciesTraverser,
- &cb);
- tmp->mMemoryElementToResultMap.EnumerateRead(MemoryElementTraverser,
- &cb);
- tmp->mRuleToBindingsMap.EnumerateRead(RuleToBindingTraverser, &cb);
+
+ for (auto it = tmp->mBindingDependencies.Iter(); !it.Done(); it.Next()) {
+ nsXULTemplateQueryProcessorRDF::ResultArray* array = it.UserData();
+ int32_t count = array->Length();
+ for (int32_t i = 0; i < count; ++i) {
+ cb.NoteXPCOMChild(array->ElementAt(i));
+ }
+ }
+
+ for (auto it = tmp->mMemoryElementToResultMap.Iter();
+ !it.Done();
+ it.Next()) {
+ nsCOMArray* array = it.UserData();
+ int32_t count = array->Count();
+ for (int32_t i = 0; i < count; ++i) {
+ cb.NoteXPCOMChild(array->ObjectAt(i));
+ }
+ }
+
+ for (auto it = tmp->mRuleToBindingsMap.Iter(); !it.Done(); it.Next()) {
+ cb.NoteXPCOMChild(it.Key());
+ }
+
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mQueries)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
diff --git a/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp b/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
index 9846f7ad38..88fe0f97d9 100644
--- a/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
+++ b/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
@@ -73,16 +73,6 @@ nsXULTemplateResultSetXML::GetNext(nsISupports **aResult)
// nsXULTemplateQueryProcessorXML
//
-static PLDHashOperator
-TraverseRuleToBindingsMap(nsISupports* aKey, nsXMLBindingSet* aMatch, void* aContext)
-{
- nsCycleCollectionTraversalCallback *cb =
- static_cast(aContext);
- NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb, "mRuleToBindingsMap key");
- cb->NoteXPCOMChild(aKey);
- return PL_DHASH_NEXT;
-}
-
NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULTemplateQueryProcessorXML)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULTemplateQueryProcessorXML)
@@ -93,7 +83,10 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULTemplateQueryProcessorXML)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mRequest)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXULTemplateQueryProcessorXML)
- tmp->mRuleToBindingsMap.EnumerateRead(TraverseRuleToBindingsMap, &cb);
+ for (auto it = tmp->mRuleToBindingsMap.Iter(); !it.Done(); it.Next()) {
+ NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mRuleToBindingsMap key");
+ cb.NoteXPCOMChild(it.Key());
+ }
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRoot)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEvaluator)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTemplateBuilder)
diff --git a/extensions/spellcheck/hunspell/src/moz.build b/extensions/spellcheck/hunspell/src/moz.build
index 54055ca87a..c5c583c9cb 100644
--- a/extensions/spellcheck/hunspell/src/moz.build
+++ b/extensions/spellcheck/hunspell/src/moz.build
@@ -27,9 +27,7 @@ LOCAL_INCLUDES += [
'../glue',
]
-# XXX: This directory is a mix of Mozilla code and third-party code. We should
-# put the Mozilla code in a separate directory and disallow compiler warnings
-# there (bug 1200065). Until then, allow warnings for all of the code.
+# We allow warnings for third-party code that can be updated from upstream.
ALLOW_COMPILER_WARNINGS = True
include('/ipc/chromium/chromium-config.mozbuild')
diff --git a/extensions/spellcheck/src/mozPersonalDictionary.cpp b/extensions/spellcheck/src/mozPersonalDictionary.cpp
index 799f879d75..a0e92fa558 100644
--- a/extensions/spellcheck/src/mozPersonalDictionary.cpp
+++ b/extensions/spellcheck/src/mozPersonalDictionary.cpp
@@ -375,9 +375,11 @@ NS_IMETHODIMP mozPersonalDictionary::Save()
return res;
}
- nsTArray array(mDictionaryTable.Count());
+ nsTArray array;
+ nsString* elems = array.AppendElements(mDictionaryTable.Count());
for (auto iter = mDictionaryTable.Iter(); !iter.Done(); iter.Next()) {
- array.AppendElement(nsDependentString(iter.Get()->GetKey()));
+ elems->Assign(iter.Get()->GetKey());
+ elems++;
}
nsCOMPtr runnable =
@@ -396,9 +398,11 @@ NS_IMETHODIMP mozPersonalDictionary::GetWordList(nsIStringEnumerator **aWords)
WaitForLoad();
- nsTArray *array = new nsTArray(mDictionaryTable.Count());
+ nsTArray *array = new nsTArray();
+ nsString* elems = array->AppendElements(mDictionaryTable.Count());
for (auto iter = mDictionaryTable.Iter(); !iter.Done(); iter.Next()) {
- array->AppendElement(nsDependentString(iter.Get()->GetKey()));
+ elems->Assign(iter.Get()->GetKey());
+ elems++;
}
array->Sort();
diff --git a/extensions/spellcheck/src/mozSpellChecker.cpp b/extensions/spellcheck/src/mozSpellChecker.cpp
index 7ef1606921..771006be3f 100644
--- a/extensions/spellcheck/src/mozSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozSpellChecker.cpp
@@ -153,9 +153,10 @@ mozSpellChecker::CheckWord(const nsAString &aWord, bool *aIsMisspelled, nsTArray
char16_t **words;
result = mSpellCheckingEngine->Suggest(PromiseFlatString(aWord).get(), &words, &count);
- NS_ENSURE_SUCCESS(result, result);
+ NS_ENSURE_SUCCESS(result, result);
+ nsString* suggestions = aSuggestions->AppendElements(count);
for(i=0;iAppendElement(nsDependentString(words[i]));
+ suggestions[i].Assign(words[i]);
}
if (count)
diff --git a/gfx/2d/DrawTargetSkia.cpp b/gfx/2d/DrawTargetSkia.cpp
index fc2961be78..ab565a2498 100644
--- a/gfx/2d/DrawTargetSkia.cpp
+++ b/gfx/2d/DrawTargetSkia.cpp
@@ -12,11 +12,7 @@
#include "FilterNodeSoftware.h"
#include "HelpersSkia.h"
-#ifdef USE_SKIA_GPU
-#include "skia/include/gpu/SkGpuDevice.h"
-#include "skia/include/gpu/gl/GrGLInterface.h"
-#endif
-
+#include "skia/include/core/SkSurface.h"
#include "skia/include/core/SkTypeface.h"
#include "skia/include/effects/SkGradientShader.h"
#include "skia/include/core/SkColorFilter.h"
@@ -148,29 +144,32 @@ bool
DrawTargetSkia::LockBits(uint8_t** aData, IntSize* aSize,
int32_t* aStride, SurfaceFormat* aFormat)
{
- const SkBitmap &bitmap = mCanvas->getDevice()->accessBitmap(false);
- if (!bitmap.lockPixelsAreWritable()) {
+ /* Test if the canvas' device has accessible pixels first, as actually
+ * accessing the pixels may trigger side-effects, even if it fails.
+ */
+ if (!mCanvas->peekPixels(nullptr, nullptr)) {
+ return false;
+ }
+
+ SkImageInfo info;
+ size_t rowBytes;
+ void* pixels = mCanvas->accessTopLayerPixels(&info, &rowBytes);
+ if (!pixels) {
return false;
}
MarkChanged();
- bitmap.lockPixels();
- *aData = reinterpret_cast(bitmap.getPixels());
- *aSize = IntSize(bitmap.width(), bitmap.height());
- *aStride = int32_t(bitmap.rowBytes());
- *aFormat = SkiaColorTypeToGfxFormat(bitmap.colorType());
+ *aData = reinterpret_cast(pixels);
+ *aSize = IntSize(info.width(), info.height());
+ *aStride = int32_t(rowBytes);
+ *aFormat = SkiaColorTypeToGfxFormat(info.colorType());
return true;
}
void
DrawTargetSkia::ReleaseBits(uint8_t* aData)
{
- const SkBitmap &bitmap = mCanvas->getDevice()->accessBitmap(false);
- MOZ_ASSERT(bitmap.lockPixelsAreWritable());
-
- bitmap.unlockPixels();
- bitmap.notifyPixelsChanged();
}
static void
@@ -265,7 +264,7 @@ SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, TempBitmap& aTmpBitmap
SkSafeUnref(shader);
SkSafeUnref(aPaint.setShader(matrixShader));
if (pat.mFilter == Filter::POINT) {
- aPaint.setFilterLevel(SkPaint::kNone_FilterLevel);
+ aPaint.setFilterQuality(kNone_SkFilterQuality);
}
break;
}
@@ -332,7 +331,7 @@ struct AutoPaintSetup {
mPaint.setAlpha(ColorFloatToByte(aOptions.mAlpha));
mAlpha = aOptions.mAlpha;
}
- mPaint.setFilterLevel(SkPaint::kLow_FilterLevel);
+ mPaint.setFilterQuality(kLow_SkFilterQuality);
}
// TODO: Maybe add an operator overload to access this easier?
@@ -380,10 +379,10 @@ DrawTargetSkia::DrawSurface(SourceSurface *aSurface,
AutoPaintSetup paint(mCanvas.get(), aOptions, &aDest);
if (aSurfOptions.mFilter == Filter::POINT) {
- paint.mPaint.setFilterLevel(SkPaint::kNone_FilterLevel);
+ paint.mPaint.setFilterQuality(kNone_SkFilterQuality);
}
- mCanvas->drawBitmapRectToRect(bitmap.mBitmap, &sourceRect, destRect, &paint.mPaint);
+ mCanvas->drawBitmapRect(bitmap.mBitmap, sourceRect, destRect, &paint.mPaint);
}
DrawTargetType
@@ -791,9 +790,7 @@ DrawTargetSkia::CopySurface(SourceSurface *aSurface,
SkBitmap bm(bitmap.mBitmap);
bm.lockPixels();
if (bm.getPixels()) {
- SkImageInfo info = bm.info();
- info.fWidth = aSourceRect.width;
- info.fHeight = aSourceRect.height;
+ SkImageInfo info = bm.info().makeWH(aSourceRect.width, aSourceRect.height);
uint8_t* pixels = static_cast(bm.getPixels());
// adjust pixels for the source offset
pixels += aSourceRect.x + aSourceRect.y*bm.rowBytes();
@@ -825,7 +822,7 @@ DrawTargetSkia::CopySurface(SourceSurface *aSurface,
clearPaint.setXfermodeMode(SkXfermode::kSrc_Mode);
mCanvas->drawPaint(clearPaint);
}
- mCanvas->drawBitmapRect(bitmap.mBitmap, &source, dest, &paint);
+ mCanvas->drawBitmapRect(bitmap.mBitmap, source, dest, &paint);
mCanvas->restore();
}
@@ -848,7 +845,7 @@ DrawTargetSkia::Init(const IntSize &aSize, SurfaceFormat aFormat)
SkBitmap bitmap;
bitmap.setInfo(skiInfo, stride);
- if (!bitmap.allocPixels()) {
+ if (!bitmap.tryAllocPixels()) {
return false;
}
@@ -877,24 +874,28 @@ DrawTargetSkia::InitWithGrContext(GrContext* aGrContext,
mSize = aSize;
mFormat = aFormat;
- GrTextureDesc targetDescriptor;
+ GrSurfaceDesc targetDescriptor;
- targetDescriptor.fFlags = kRenderTarget_GrTextureFlagBit;
+ targetDescriptor.fFlags = kRenderTarget_GrSurfaceFlag;
targetDescriptor.fWidth = mSize.width;
targetDescriptor.fHeight = mSize.height;
targetDescriptor.fConfig = GfxFormatToGrConfig(mFormat);
targetDescriptor.fOrigin = kBottomLeft_GrSurfaceOrigin;
targetDescriptor.fSampleCnt = 0;
- SkAutoTUnref skiaTexture(mGrContext->createUncachedTexture(targetDescriptor, NULL, 0));
+ SkAutoTUnref skiaTexture(mGrContext->textureProvider()->createTexture(targetDescriptor, SkSurface::kNo_Budgeted, nullptr, 0));
if (!skiaTexture) {
return false;
}
- mTexture = (uint32_t)skiaTexture->getTextureHandle();
+ SkAutoTUnref gpuSurface(SkSurface::NewRenderTargetDirect(skiaTexture->asRenderTarget()));
+ if (!gpuSurface) {
+ return false;
+ }
- SkAutoTUnref device(new SkGpuDevice(mGrContext.get(), skiaTexture->asRenderTarget()));
- mCanvas.adopt(new SkCanvas(device.get()));
+ mTexture = reinterpret_cast(skiaTexture->getTextureHandle())->fID;
+
+ mCanvas = gpuSurface->getCanvas();
return true;
}
diff --git a/gfx/2d/DrawTargetSkia.h b/gfx/2d/DrawTargetSkia.h
index 979559adca..e28a20411b 100644
--- a/gfx/2d/DrawTargetSkia.h
+++ b/gfx/2d/DrawTargetSkia.h
@@ -142,7 +142,7 @@ private:
#ifdef USE_SKIA_GPU
RefPtrSkia mGrContext;
- uint32_t mTexture;
+ GrGLuint mTexture;
#endif
IntSize mSize;
diff --git a/gfx/2d/ScaledFontCairo.cpp b/gfx/2d/ScaledFontCairo.cpp
index d64e02de50..2507877293 100644
--- a/gfx/2d/ScaledFontCairo.cpp
+++ b/gfx/2d/ScaledFontCairo.cpp
@@ -41,20 +41,20 @@ SkTypeface* ScaledFontCairo::GetSkTypeface()
{
if (!mTypeface) {
cairo_font_face_t* fontFace = cairo_scaled_font_get_font_face(mScaledFont);
+ MOZ_ASSERT(cairo_font_face_status(fontFace) == CAIRO_STATUS_SUCCESS);
+
FT_Face face = cairo_ft_scaled_font_lock_face(mScaledFont);
- int style = SkTypeface::kNormal;
-
- if (face->style_flags & FT_STYLE_FLAG_ITALIC)
- style |= SkTypeface::kItalic;
-
- if (face->style_flags & FT_STYLE_FLAG_BOLD)
- style |= SkTypeface::kBold;
+ SkFontStyle style(face->style_flags & FT_STYLE_FLAG_BOLD ?
+ SkFontStyle::kBold_Weight : SkFontStyle::kNormal_Weight,
+ SkFontStyle::kNormal_Width,
+ face->style_flags & FT_STYLE_FLAG_ITALIC ?
+ SkFontStyle::kItalic_Slant : SkFontStyle::kUpright_Slant);
bool isFixedWidth = face->face_flags & FT_FACE_FLAG_FIXED_WIDTH;
cairo_ft_scaled_font_unlock_face(mScaledFont);
- mTypeface = SkCreateTypefaceFromCairoFont(fontFace, (SkTypeface::Style)style, isFixedWidth);
+ mTypeface = SkCreateTypefaceFromCairoFont(fontFace, style, isFixedWidth);
}
return mTypeface;
diff --git a/gfx/2d/SourceSurfaceSkia.cpp b/gfx/2d/SourceSurfaceSkia.cpp
index 2de51f681c..9b905462f2 100644
--- a/gfx/2d/SourceSurfaceSkia.cpp
+++ b/gfx/2d/SourceSurfaceSkia.cpp
@@ -13,6 +13,7 @@
#include "DataSurfaceHelpers.h"
#ifdef USE_SKIA_GPU
+#include "GLDefs.h"
#include "skia/include/gpu/SkGrPixelRef.h"
#endif
@@ -50,13 +51,11 @@ SourceSurfaceSkia::InitFromCanvas(SkCanvas* aCanvas,
SurfaceFormat aFormat,
DrawTargetSkia* aOwner)
{
- SkISize size = aCanvas->getDeviceSize();
-
- mBitmap = (SkBitmap)aCanvas->getDevice()->accessBitmap(false);
+ mBitmap = aCanvas->getDevice()->accessBitmap(false);
mFormat = aFormat;
- mSize = IntSize(size.fWidth, size.fHeight);
+ mSize = IntSize(mBitmap.width(), mBitmap.height());
mStride = mBitmap.rowBytes();
mDrawTarget = aOwner;
@@ -84,10 +83,6 @@ SourceSurfaceSkia::InitFromData(unsigned char* aData,
return false;
}
- if (aFormat == SurfaceFormat::B8G8R8X8) {
- mBitmap.setAlphaType(kIgnore_SkAlphaType);
- }
-
mSize = aSize;
mFormat = aFormat;
mStride = mBitmap.rowBytes();
@@ -109,11 +104,15 @@ SourceSurfaceSkia::InitFromTexture(DrawTargetSkia* aOwner,
skiaTexGlue.fOrigin = kTopLeft_GrSurfaceOrigin;
skiaTexGlue.fConfig = GfxFormatToGrConfig(aFormat);
skiaTexGlue.fSampleCnt = 0;
- skiaTexGlue.fTextureHandle = aTexture;
- GrTexture *skiaTexture = aOwner->mGrContext->wrapBackendTexture(skiaTexGlue);
+ GrGLTextureInfo texInfo;
+ texInfo.fTarget = LOCAL_GL_TEXTURE_2D;
+ texInfo.fID = aTexture;
+ skiaTexGlue.fTextureHandle = reinterpret_cast(&texInfo);
+
+ GrTexture *skiaTexture = aOwner->mGrContext->textureProvider()->wrapBackendTexture(skiaTexGlue);
SkImageInfo imgInfo = SkImageInfo::Make(aSize.width, aSize.height, GfxFormatToSkiaColorType(aFormat), kOpaque_SkAlphaType);
- SkGrPixelRef *texRef = new SkGrPixelRef(imgInfo, skiaTexture, false);
+ SkGrPixelRef *texRef = new SkGrPixelRef(imgInfo, skiaTexture);
mBitmap.setInfo(imgInfo);
mBitmap.setPixelRef(texRef);
mFormat = aFormat;
diff --git a/gfx/angle/moz.build b/gfx/angle/moz.build
index 6947f07107..bad5ab5764 100644
--- a/gfx/angle/moz.build
+++ b/gfx/angle/moz.build
@@ -108,8 +108,7 @@ SOURCES += [
'src/compiler/translator/glslang_tab.cpp',
]
-
-if CONFIG['GNU_CXX']:
+if CONFIG['GNU_CXX'] or CONFIG['CLANG_CL']:
CXXFLAGS += [
'-Wno-attributes',
'-Wno-shadow',
@@ -117,16 +116,16 @@ if CONFIG['GNU_CXX']:
'-Wno-unknown-pragmas',
'-Wno-unreachable-code',
]
- if CONFIG['CLANG_CXX']:
- CXXFLAGS += [
- '-Wno-inconsistent-missing-override',
- '-Wno-unused-private-field',
- ]
- else:
- CXXFLAGS += [
- '-Wno-shadow-compatible-local',
- '-Wno-shadow-local',
- ]
+if CONFIG['GNU_CXX'] and not CONFIG['CLANG_CXX'] and not CONFIG['CLANG_CL']:
+ CXXFLAGS += [
+ '-Wno-shadow-compatible-local',
+ '-Wno-shadow-local',
+ ]
+if CONFIG['CLANG_CXX'] or CONFIG['CLANG_CL']:
+ CXXFLAGS += [
+ '-Wno-inconsistent-missing-override',
+ '-Wno-unused-private-field',
+ ]
if CONFIG['MOZ_DIRECTX_SDK_PATH'] and not CONFIG['MOZ_HAS_WINSDK_WITH_D3D']:
LOCAL_INCLUDES += ['%' + '%s/include/' % CONFIG['MOZ_DIRECTX_SDK_PATH']]
diff --git a/gfx/angle/src/libANGLE/moz.build b/gfx/angle/src/libANGLE/moz.build
index 35478e8b87..16d22ece63 100644
--- a/gfx/angle/src/libANGLE/moz.build
+++ b/gfx/angle/src/libANGLE/moz.build
@@ -328,5 +328,5 @@ if CONFIG['MOZ_HAS_WINSDK_WITH_D3D']:
SOURCES['renderer/d3d/d3d11/SwapChain11.cpp'].flags += ['-DANGLE_RESOURCE_SHARE_TYPE=D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX']
# We allow warnings for third-party code that can be updated from upstream.
-# ALLOW_COMPILER_WARNINGS = True
+ALLOW_COMPILER_WARNINGS = True
diff --git a/gfx/cairo/cairo/src/moz.build b/gfx/cairo/cairo/src/moz.build
index 6cdb12564c..61b8ba671e 100644
--- a/gfx/cairo/cairo/src/moz.build
+++ b/gfx/cairo/cairo/src/moz.build
@@ -185,6 +185,7 @@ UNIFIED_SOURCES += [
'cairo.c',
]
+# We allow warnings for third-party code that can be updated from upstream.
ALLOW_COMPILER_WARNINGS = True
FINAL_LIBRARY = 'gkmedias'
@@ -207,7 +208,7 @@ if CONFIG['MOZ_TREE_FREETYPE']:
DEFINES['FT_LCD_FILTER_H'] = '%s/modules/freetype2/include/freetype/ftlcdfil.h' % TOPSRCDIR
# Suppress warnings in third-party code.
-if CONFIG['GNU_CC']:
+if CONFIG['GNU_CC'] or CONFIG['CLANG_CL']:
CFLAGS += [
'-Wno-enum-compare',
'-Wno-int-to-pointer-cast',
@@ -216,13 +217,19 @@ if CONFIG['GNU_CC']:
'-Wno-missing-field-initializers',
'-Wno-conversion',
]
-if CONFIG['CLANG_CXX']:
+if CONFIG['CLANG_CXX'] or CONFIG['CLANG_CL']:
CFLAGS += [
'-Wno-incompatible-pointer-types',
'-Wno-tautological-compare',
'-Wno-tautological-constant-out-of-range-compare',
'-Wno-error=uninitialized',
]
+if CONFIG['CLANG_CL']:
+ CFLAGS += [
+ '-Wno-deprecated-register',
+ '-Wno-macro-redefined',
+ '-Wno-unused-variable',
+ ]
# See bug 386897.
if CONFIG['GNU_CC'] and CONFIG['OS_TARGET'] == 'Android' and CONFIG['MOZ_OPTIMIZE']:
diff --git a/gfx/gl/SkiaGLGlue.cpp b/gfx/gl/SkiaGLGlue.cpp
index 1868ed4ea3..7ffcab1c73 100755
--- a/gfx/gl/SkiaGLGlue.cpp
+++ b/gfx/gl/SkiaGLGlue.cpp
@@ -89,6 +89,11 @@ GrGLvoid glBlendColor_mozilla(GrGLclampf red, GrGLclampf green, GrGLclampf blue,
return sGLContext.get()->fBlendColor(red, green, blue, alpha);
}
+GrGLvoid glBlendEquation_mozilla(GrGLenum mode)
+{
+ return sGLContext.get()->fBlendEquation(mode);
+}
+
GrGLvoid glBlendFunc_mozilla(GrGLenum sfactor, GrGLenum dfactor)
{
return sGLContext.get()->fBlendFunc(sfactor, dfactor);
@@ -315,6 +320,11 @@ GrGLvoid glGetShaderiv_mozilla(GrGLuint shader, GrGLenum pname, GrGLint* params)
return sGLContext.get()->fGetShaderiv(shader, pname, params);
}
+GrGLvoid glGetShaderPrecisionFormat_mozilla(GrGLenum shadertype, GrGLenum precisiontype, GLint *range, GLint *precision)
+{
+ return sGLContext.get()->fGetShaderPrecisionFormat(shadertype, precisiontype, range, precision);
+}
+
const GLubyte* glGetString_mozilla(GrGLenum name)
{
// GLContext only exposes a OpenGL 2.0 style API, so we have to intercept a bunch
@@ -357,6 +367,12 @@ const GLubyte* glGetString_mozilla(GrGLenum name)
if (sGLContext.get()->IsSupported(GLFeature::standard_derivatives)) {
strcat(extensionsString, "GL_OES_standard_derivatives ");
}
+ } else {
+ if (sGLContext.get()->IsSupported(GLFeature::framebuffer_object)) {
+ strcat(extensionsString, "GL_ARB_framebuffer_object ");
+ } else if (sGLContext.get()->IsExtensionSupported(GLContext::EXT_framebuffer_object)) {
+ strcat(extensionsString, "GL_EXT_framebuffer_object ");
+ }
}
if (sGLContext.get()->IsExtensionSupported(GLContext::EXT_texture_format_BGRA8888)) {
@@ -581,6 +597,21 @@ GrGLvoid glUseProgram_mozilla(GrGLuint program)
return sGLContext.get()->fUseProgram(program);
}
+GrGLvoid glVertexAttrib1f_mozilla(GrGLuint index, GrGLfloat value)
+{
+ return sGLContext.get()->fVertexAttrib1f(index, value);
+}
+
+GrGLvoid glVertexAttrib2fv_mozilla(GrGLuint index, const GrGLfloat* values)
+{
+ return sGLContext.get()->fVertexAttrib2fv(index, values);
+}
+
+GrGLvoid glVertexAttrib3fv_mozilla(GrGLuint index, const GrGLfloat* values)
+{
+ return sGLContext.get()->fVertexAttrib3fv(index, values);
+}
+
GrGLvoid glVertexAttrib4fv_mozilla(GrGLuint index, const GrGLfloat* values)
{
return sGLContext.get()->fVertexAttrib4fv(index, values);
@@ -767,6 +798,7 @@ static GrGLInterface* CreateGrGLInterfaceFromGLContext(GLContext* context)
i->fFunctions.fBindTexture = glBindTexture_mozilla;
i->fFunctions.fBlendFunc = glBlendFunc_mozilla;
i->fFunctions.fBlendColor = glBlendColor_mozilla;
+ i->fFunctions.fBlendEquation = glBlendEquation_mozilla;
i->fFunctions.fBufferData = glBufferData_mozilla;
i->fFunctions.fBufferSubData = glBufferSubData_mozilla;
i->fFunctions.fCheckFramebufferStatus = glCheckFramebufferStatus_mozilla;
@@ -811,6 +843,7 @@ static GrGLInterface* CreateGrGLInterfaceFromGLContext(GLContext* context)
i->fFunctions.fGetRenderbufferParameteriv = glGetRenderbufferParameteriv_mozilla;
i->fFunctions.fGetShaderInfoLog = glGetShaderInfoLog_mozilla;
i->fFunctions.fGetShaderiv = glGetShaderiv_mozilla;
+ i->fFunctions.fGetShaderPrecisionFormat = glGetShaderPrecisionFormat_mozilla;
i->fFunctions.fGetString = glGetString_mozilla;
i->fFunctions.fGetUniformLocation = glGetUniformLocation_mozilla;
i->fFunctions.fLineWidth = glLineWidth_mozilla;
@@ -847,6 +880,9 @@ static GrGLInterface* CreateGrGLInterfaceFromGLContext(GLContext* context)
i->fFunctions.fUniformMatrix3fv = glUniformMatrix3fv_mozilla;
i->fFunctions.fUniformMatrix4fv = glUniformMatrix4fv_mozilla;
i->fFunctions.fUseProgram = glUseProgram_mozilla;
+ i->fFunctions.fVertexAttrib1f = glVertexAttrib1f_mozilla;
+ i->fFunctions.fVertexAttrib2fv = glVertexAttrib2fv_mozilla;
+ i->fFunctions.fVertexAttrib3fv = glVertexAttrib3fv_mozilla;
i->fFunctions.fVertexAttrib4fv = glVertexAttrib4fv_mozilla;
i->fFunctions.fVertexAttribPointer = glVertexAttribPointer_mozilla;
i->fFunctions.fViewport = glViewport_mozilla;
diff --git a/gfx/layers/basic/BasicCompositor.cpp b/gfx/layers/basic/BasicCompositor.cpp
index ae5761e8f5..758c4b79b4 100644
--- a/gfx/layers/basic/BasicCompositor.cpp
+++ b/gfx/layers/basic/BasicCompositor.cpp
@@ -254,9 +254,9 @@ Transform(DataSourceSurface* aDest,
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
paint.setAntiAlias(true);
- paint.setFilterLevel(SkPaint::kLow_FilterLevel);
+ paint.setFilterQuality(kLow_SkFilterQuality);
SkRect destRect = SkRect::MakeXYWH(0, 0, srcSize.width, srcSize.height);
- destCanvas.drawBitmapRectToRect(src, nullptr, destRect, &paint);
+ destCanvas.drawBitmapRect(src, destRect, &paint);
}
#else
static pixman_transform
diff --git a/gfx/layers/basic/BasicLayerManager.cpp b/gfx/layers/basic/BasicLayerManager.cpp
index 937fa47476..d5b8556694 100644
--- a/gfx/layers/basic/BasicLayerManager.cpp
+++ b/gfx/layers/basic/BasicLayerManager.cpp
@@ -742,9 +742,9 @@ Transform(const gfxImageSurface* aDest,
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kSrc_Mode);
paint.setAntiAlias(true);
- paint.setFilterLevel(SkPaint::kLow_FilterLevel);
+ paint.setFilterQuality(kLow_SkFilterQuality);
SkRect destRect = SkRect::MakeXYWH(0, 0, srcSize.width, srcSize.height);
- destCanvas.drawBitmapRectToRect(src, nullptr, destRect, &paint);
+ destCanvas.drawBitmapRect(src, destRect, &paint);
}
#else
static pixman_transform
diff --git a/gfx/skia/README_MOZILLA b/gfx/skia/README_MOZILLA
index 8620b657b9..473e24008d 100644
--- a/gfx/skia/README_MOZILLA
+++ b/gfx/skia/README_MOZILLA
@@ -1,12 +1,9 @@
-The source from this directory was copied from the skia subversion trunk
-using the update.sh script. The changes made were those applied by update.sh,
-the addition/update of Makefile.in files for the Mozilla build system.
-
This is an import of Skia from 2014-07-28 (b1ab5fdd11bb358d738c1bfa63737dc65174a281)
To update to a new version of Skia:
-- Copy the entire trunk/ directory from a Skia clone to mozilla-central/gfx/skia
+- Clone Skia from upstream using the instructions here: https://sites.google.com/site/skiadocs/user-documentation/downloading
+- Copy the entire source tree from a Skia clone to mozilla-central/gfx/skia/skia
- cd gfx/skia && ./gyp_mozbuild
Once that's done, use git status to view the files that have changed. Keep an eye on GrUserConfig.h
diff --git a/gfx/skia/generate_mozbuild.py b/gfx/skia/generate_mozbuild.py
index efbaf7f18d..ee16c67b86 100755
--- a/gfx/skia/generate_mozbuild.py
+++ b/gfx/skia/generate_mozbuild.py
@@ -3,6 +3,7 @@
import os
import locale
+from collections import defaultdict
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
header = """
@@ -24,34 +25,12 @@ header = """
footer = """
-# can we find a better way of dealing with asm sources?
-
-# left out of UNIFIED_SOURCES for now; that's not C++ anyway, nothing else to unify it with
-#XXX: doesn't build with Apple's assembler
-if not CONFIG['INTEL_ARCHITECTURE'] and CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC'] and CONFIG['OS_TARGET'] != 'Darwin':
- SOURCES += [
- 'skia/src/opts/memset.arm.S',
- ]
- if CONFIG['BUILD_ARM_NEON']:
- SOURCES += [
- 'skia/src/opts/memset16_neon.S',
- 'skia/src/opts/memset32_neon.S',
- ]
-
-if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['GNU_CC'] and CONFIG['OS_ARCH'] != 'WINNT':
- if CONFIG['CPU_ARCH'] == 'x86_64':
- SOURCES += [
- 'skia/src/opts/SkBlitRow_opts_SSE4_x64_asm.S',
- ]
- else:
- SOURCES += [
- 'skia/src/opts/SkBlitRow_opts_SSE4_asm.S',
- ]
-
+# We allow warnings for third-party code that can be updated from upstream.
ALLOW_COMPILER_WARNINGS = True
FINAL_LIBRARY = 'gkmedias'
LOCAL_INCLUDES += [
+ 'skia/include/c',
'skia/include/config',
'skia/include/core',
'skia/include/effects',
@@ -60,6 +39,7 @@ LOCAL_INCLUDES += [
'skia/include/pathops',
'skia/include/pipe',
'skia/include/ports',
+ 'skia/include/private',
'skia/include/utils',
'skia/include/utils/mac',
'skia/include/utils/win',
@@ -77,12 +57,6 @@ LOCAL_INCLUDES += [
'skia/src/utils/win',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] in {'android', 'gtk2', 'gtk3', 'qt', 'gonk', 'cocoa', 'uikit'}:
- DEFINES['SK_USE_POSIX_THREADS'] = 1
-
-if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['HAVE_TOOLCHAIN_SUPPORT_MSSSE3']:
- DEFINES['SK_BUILD_SSSE3'] = 1
-
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk'):
DEFINES['SK_FONTHOST_CAIRO_STANDALONE'] = 0
@@ -104,42 +78,34 @@ if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
if CONFIG['_MSC_VER']:
# MSVC doesn't need special compiler flags, but Skia needs to be told that these files should
# be built with the required SSE level or it will simply compile in stubs and cause runtime crashes
- SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=31']
- SOURCES['skia/src/opts/SkBlitRect_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=41']
- SOURCES['skia/src/opts/SkMorphology_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkUtils_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkXfermode_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
-
+ SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=31']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=41']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=31']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=41']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['/arch:AVX -DSK_CPU_SSE_LEVEL=51']
if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['GNU_CC']:
SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
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/SkBlitRect_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-msse4.1']
- SOURCES['skia/src/opts/SkMorphology_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkUtils_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkXfermode_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC'] and CONFIG['BUILD_ARM_NEON']:
- DEFINES['__ARM_HAVE_OPTIONAL_NEON_SUPPORT'] = 1
- DEFINES['USE_ANDROID_NDK_CPU_FEATURES'] = 0
+ DEFINES['SK_ARM_HAS_OPTIONAL_NEON'] = 1
elif CONFIG['CLANG_CL']:
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-mssse3']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-msse4.1']
-
-if CONFIG['GNU_CXX'] and CONFIG['CPU_ARCH'] == 'arm':
- SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += ['-fomit-frame-pointer']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
DEFINES['SKIA_IMPLEMENTATION'] = 1
-DEFINES['GR_IMPLEMENTATION'] = 1
-# Suppress warnings in third-party code.
if CONFIG['GNU_CXX']:
CXXFLAGS += [
'-Wno-deprecated-declarations',
@@ -147,18 +113,22 @@ if CONFIG['GNU_CXX']:
'-Wno-sign-compare',
'-Wno-unused-function',
]
-if CONFIG['GNU_CXX'] and not CONFIG['CLANG_CXX']:
- CXXFLAGS += [
- '-Wno-logical-op',
- '-Wno-maybe-uninitialized',
- ]
-if CONFIG['CLANG_CXX']:
+ if CONFIG['CLANG_CXX']:
CXXFLAGS += [
'-Wno-implicit-fallthrough',
'-Wno-inconsistent-missing-override',
'-Wno-macro-redefined',
'-Wno-unused-private-field',
]
+ # work around inline function linking bug with template arguments
+ SOURCES['skia/src/gpu/GrResourceCache.cpp'].flags += ['-fkeep-inline-functions']
+ else:
+ CXXFLAGS += [
+ '-Wno-logical-op',
+ '-Wno-maybe-uninitialized',
+ ]
+ if CONFIG['CPU_ARCH'] == 'arm':
+ SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += ['-fomit-frame-pointer']
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3', 'android', 'gonk', 'qt'):
CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
@@ -185,7 +155,7 @@ def generate_platform_sources():
sources = {}
for plat in platforms:
- if os.system("cd skia && GYP_GENERATORS=dump_mozbuild ./gyp_skia -D OS=%s gyp/skia_lib.gyp" % plat) != 0:
+ if os.system("cd skia && GYP_GENERATORS=dump_mozbuild ./gyp_skia -D OS=%s -D host_os=linux gyp/skia_lib.gyp" % plat) != 0:
print 'Failed to generate sources for ' + plat
continue
@@ -200,31 +170,26 @@ def generate_platform_sources():
def generate_separated_sources(platform_sources):
blacklist = [
'ChromeUtils',
- 'SkImageDecoder_',
- '_gif',
- 'SkFontConfigParser_android',
'SkJpeg',
'SkXML',
- 'SkCity',
'GrGLCreateNativeInterface',
+ 'SkCreatePlatformGLContext',
'fontconfig',
- 'SkCondVar',
'SkThreadUtils_pthread_',
- 'SkImage_Codec',
- 'SkBitmapChecksummer',
- 'SkNativeGLContext',
'SkFontConfig',
- 'SkFontHost_win_dw',
'SkFontMgr_android',
+ 'SkFontMgr_custom',
+ 'SkFontHost_FreeType.cpp',
'SkForceLinking',
'SkMovie',
'SkImageDecoder',
'SkImageEncoder',
'SkBitmapHasher',
+ 'SkBitmapRegion',
+ 'codec',
'SkWGL',
- 'SkImages',
- 'SkDiscardableMemory_ashmem',
'SkMemory_malloc',
+ 'SkOpts_',
'opts_check_x86',
'third_party',
]
@@ -238,30 +203,18 @@ def generate_separated_sources(platform_sources):
separated = defaultdict(set, {
'common': {
- #'skia/src/effects/gradients/SkGradientTileProc.cpp',
'skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkImageDecoder_empty.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
- # 'skia/src/images/SkImages.cpp',
- # 'skia/src/images/SkImageRef.cpp',
- # 'skia/src/images/SkImageRef_GlobalPool.cpp',
- # 'skia/src/images/SkImageRefPool.cpp',
- # 'skia/src/images/SkImageDecoder.cpp',
- # 'skia/src/images/SkImageDecoder_Factory.cpp',
},
'android': {
# 'skia/src/ports/SkDebug_android.cpp',
- 'skia/src/ports/SkFontHost_android_old.cpp',
'skia/src/ports/SkFontHost_cairo.cpp',
# 'skia/src/ports/SkFontHost_FreeType.cpp',
# 'skia/src/ports/SkFontHost_FreeType_common.cpp',
- # 'skia/src/ports/SkThread_pthread.cpp',
- # 'skia/src/ports/SkPurgeableMemoryBlock_android.cpp',
# 'skia/src/ports/SkTime_Unix.cpp',
# 'skia/src/utils/SkThreadUtils_pthread.cpp',
- # 'skia/src/images/SkImageRef_ashmem.cpp',
- # 'skia/src/utils/android/ashmem.cpp',
},
'linux': {
'skia/src/ports/SkFontHost_cairo.cpp',
@@ -269,57 +222,43 @@ def generate_separated_sources(platform_sources):
'intel': {
# There is currently no x86-specific opt for SkTextureCompression
'skia/src/opts/opts_check_x86.cpp',
- 'skia/src/opts/SkTextureCompression_opts_none.cpp',
+ 'skia/src/opts/SkOpts_ssse3.cpp',
+ 'skia/src/opts/SkOpts_sse41.cpp',
+ 'skia/src/opts/SkOpts_avx.cpp',
},
'arm': {
- 'skia/src/opts/SkUtils_opts_arm.cpp',
'skia/src/core/SkUtilsArm.cpp',
},
'neon': {
+ 'skia/src/opts/SkOpts_neon.cpp',
'skia/src/opts/SkBitmapProcState_arm_neon.cpp',
},
- 'none': {
- 'skia/src/opts/SkUtils_opts_none.cpp',
- }
+ 'none': set()
})
for plat in platform_sources.keys():
- if not separated.has_key(plat):
- separated[plat] = set()
-
for value in platform_sources[plat]:
if isblacklisted(value):
continue
- if value.find('_SSE') > 0 or value.find('_SSSE') > 0 or value.find('_SSE4') > 0 : #lol
- separated['intel'].add(value)
+ if value in separated['common']:
continue
- if value.find('_neon') > 0:
- separated['neon'].add(value)
- continue
+ key = plat
- if value.find('_arm') > 0:
- separated['arm'].add(value)
- continue
+ if '_SSE' in value or '_SSSE' in value:
+ key = 'intel'
+ elif '_neon' in value:
+ key = 'neon'
+ elif '_arm' in value:
+ key = 'arm'
+ elif '_none' in value:
+ key = 'none'
+ elif all(value in platform_sources.get(p, {})
+ for p in platforms if p != plat):
+ key = 'common'
- if value.find('_none') > 0:
- separated['none'].add(value)
- continue
-
- found = True
- for other in platforms:
- if other == plat or not platform_sources.has_key(other):
- continue
-
- if not value in platform_sources[other]:
- found = False
- break;
-
- if found:
- separated['common'].add(value)
- else:
- separated[plat].add(value)
+ separated[key].add(value)
return separated
@@ -333,7 +272,7 @@ def write_cflags(f, values, subsearch, cflag, indent):
for _ in range(indent):
f.write(' ')
- val_list = uniq(sorted(map(lambda val: val.replace('../', 'trunk/'), values), key=lambda x: x.lower()))
+ val_list = uniq(sorted(values, key=lambda x: x.lower()))
if len(val_list) == 0:
return
@@ -360,15 +299,22 @@ def write_sources(f, values, indent):
'SkBlitter_Sprite.cpp',
'SkBlitRow_opts_arm.cpp',
'SkScan_Antihair.cpp',
- 'SkCondVar.cpp',
'SkParse.cpp',
- 'GrAddPathRenderers_default.cpp',
- 'GrDistanceFieldTextContext.cpp',
'SkSHA1.cpp',
'SkMD5.cpp',
'SkPictureData.cpp',
- 'SkScaledImageCache.cpp',
'opts_check_x86.cpp',
+ 'GrDrawContext',
+ 'GrResourceCache',
+ 'GrAA',
+ 'GrGL',
+ 'GrBatchAtlas.cpp',
+ 'SkArithmeticMode_gpu.cpp',
+ 'SkImage_Gpu.cpp',
+ 'SkPathOpsDebug.cpp',
+ 'SkParsePath.cpp',
+ 'SkOpts',
+ 'SkRecorder.cpp',
]
def isblacklisted(value):
@@ -396,7 +342,7 @@ def write_list(f, name, values, indent):
for _ in range(indent):
f.write(' ')
- val_list = uniq(sorted(map(lambda val: val.replace('../', 'trunk/'), values), key=lambda x: x.lower()))
+ val_list = uniq(sorted(values, key=lambda x: x.lower()))
if len(val_list) == 0:
return
diff --git a/gfx/skia/gyp_mozbuild b/gfx/skia/gyp_mozbuild
index c5e53b69e8..0cec5f9a6c 100755
--- a/gfx/skia/gyp_mozbuild
+++ b/gfx/skia/gyp_mozbuild
@@ -1,9 +1,9 @@
#!/bin/bash
# Install our generator
-cp dump_mozbuild.py trunk/third_party/externals/gyp/pylib/gyp/generator
+cp dump_mozbuild.py skia/third_party/externals/gyp/pylib/gyp/generator
-# pushd trunk
+# pushd skia
# for OS in win linux mac; do
# GYP_GENERATORS=dump_mozbuild ./gyp_skia -D OS=$OS -D arm_neon=0 gyp/effects.gyp
# done
diff --git a/gfx/skia/moz.build b/gfx/skia/moz.build
index 341293e9e7..a2cb943f0a 100644
--- a/gfx/skia/moz.build
+++ b/gfx/skia/moz.build
@@ -14,26 +14,31 @@
# DO NOT MODIFY THIS FILE IT IS AUTOGENERATED.
#
UNIFIED_SOURCES += [
+ 'skia/src/c/sk_paint.cpp',
+ 'skia/src/c/sk_surface.cpp',
'skia/src/core/SkAAClip.cpp',
'skia/src/core/SkAlphaRuns.cpp',
'skia/src/core/SkAnnotation.cpp',
'skia/src/core/SkBBHFactory.cpp',
- 'skia/src/core/SkBBoxHierarchyRecord.cpp',
- 'skia/src/core/SkBBoxRecord.cpp',
+ 'skia/src/core/SkBigPicture.cpp',
'skia/src/core/SkBitmap.cpp',
- 'skia/src/core/SkBitmap_scroll.cpp',
+ 'skia/src/core/SkBitmapCache.cpp',
+ 'skia/src/core/SkBitmapController.cpp',
'skia/src/core/SkBitmapDevice.cpp',
'skia/src/core/SkBitmapFilter.cpp',
'skia/src/core/SkBitmapHeap.cpp',
'skia/src/core/SkBitmapProcShader.cpp',
'skia/src/core/SkBitmapProcState.cpp',
+ 'skia/src/core/SkBitmapProvider.cpp',
'skia/src/core/SkBitmapScaler.cpp',
'skia/src/core/SkBlitMask_D32.cpp',
'skia/src/core/SkBlitRow_D16.cpp',
'skia/src/core/SkBlitRow_D32.cpp',
'skia/src/core/SkBlitter.cpp',
'skia/src/core/SkBuffer.cpp',
+ 'skia/src/core/SkCachedData.cpp',
'skia/src/core/SkCanvas.cpp',
+ 'skia/src/core/SkChecksum.cpp',
'skia/src/core/SkChunkAlloc.cpp',
'skia/src/core/SkClipStack.cpp',
'skia/src/core/SkColor.cpp',
@@ -53,6 +58,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkDistanceFieldGen.cpp',
'skia/src/core/SkDither.cpp',
'skia/src/core/SkDraw.cpp',
+ 'skia/src/core/SkDrawable.cpp',
'skia/src/core/SkDrawLooper.cpp',
'skia/src/core/SkEdge.cpp',
'skia/src/core/SkEdgeBuilder.cpp',
@@ -62,75 +68,85 @@ UNIFIED_SOURCES += [
'skia/src/core/SkFilterShader.cpp',
'skia/src/core/SkFlattenable.cpp',
'skia/src/core/SkFlattenableSerialization.cpp',
- 'skia/src/core/SkFloat.cpp',
'skia/src/core/SkFloatBits.cpp',
'skia/src/core/SkFont.cpp',
'skia/src/core/SkFontDescriptor.cpp',
+ 'skia/src/core/SkFontMgr.cpp',
'skia/src/core/SkFontStream.cpp',
+ 'skia/src/core/SkFontStyle.cpp',
+ 'skia/src/core/SkForceCPlusPlusLinking.cpp',
'skia/src/core/SkGeometry.cpp',
'skia/src/core/SkGlyphCache.cpp',
'skia/src/core/SkGraphics.cpp',
+ 'skia/src/core/SkHalf.cpp',
+ 'skia/src/core/SkImageCacherator.cpp',
'skia/src/core/SkImageFilter.cpp',
'skia/src/core/SkImageGenerator.cpp',
'skia/src/core/SkImageInfo.cpp',
- 'skia/src/core/SkInstCnt.cpp',
+ 'skia/src/core/SkLightingShader.cpp',
'skia/src/core/SkLineClipper.cpp',
+ 'skia/src/core/SkLocalMatrixImageFilter.cpp',
'skia/src/core/SkLocalMatrixShader.cpp',
'skia/src/core/SkMallocPixelRef.cpp',
'skia/src/core/SkMask.cpp',
+ 'skia/src/core/SkMaskCache.cpp',
'skia/src/core/SkMaskFilter.cpp',
'skia/src/core/SkMaskGamma.cpp',
'skia/src/core/SkMath.cpp',
'skia/src/core/SkMatrix.cpp',
- 'skia/src/core/SkMatrixClipStateMgr.cpp',
+ 'skia/src/core/SkMatrixImageFilter.cpp',
'skia/src/core/SkMetaData.cpp',
+ 'skia/src/core/SkMiniRecorder.cpp',
'skia/src/core/SkMipMap.cpp',
+ 'skia/src/core/SkMultiPictureDraw.cpp',
+ 'skia/src/core/SkNinePatchIter.cpp',
'skia/src/core/SkPackBits.cpp',
'skia/src/core/SkPaint.cpp',
- 'skia/src/core/SkPaintOptionsAndroid.cpp',
'skia/src/core/SkPaintPriv.cpp',
- 'skia/src/core/SkPatch.cpp',
'skia/src/core/SkPath.cpp',
'skia/src/core/SkPathEffect.cpp',
- 'skia/src/core/SkPathHeap.cpp',
'skia/src/core/SkPathMeasure.cpp',
'skia/src/core/SkPathRef.cpp',
'skia/src/core/SkPicture.cpp',
+ 'skia/src/core/SkPictureContentInfo.cpp',
'skia/src/core/SkPictureFlat.cpp',
+ 'skia/src/core/SkPictureImageGenerator.cpp',
'skia/src/core/SkPicturePlayback.cpp',
- 'skia/src/core/SkPictureRangePlayback.cpp',
'skia/src/core/SkPictureRecord.cpp',
'skia/src/core/SkPictureRecorder.cpp',
- 'skia/src/core/SkPictureReplacementPlayback.cpp',
'skia/src/core/SkPictureShader.cpp',
- 'skia/src/core/SkPictureStateTree.cpp',
'skia/src/core/SkPixelRef.cpp',
+ 'skia/src/core/SkPixmap.cpp',
'skia/src/core/SkPoint.cpp',
- 'skia/src/core/SkProcSpriteBlitter.cpp',
+ 'skia/src/core/SkPoint3.cpp',
'skia/src/core/SkPtrRecorder.cpp',
'skia/src/core/SkQuadClipper.cpp',
- 'skia/src/core/SkQuadTree.cpp',
'skia/src/core/SkRasterClip.cpp',
'skia/src/core/SkRasterizer.cpp',
'skia/src/core/SkReadBuffer.cpp',
- 'skia/src/core/SkRecordAnalysis.cpp',
+ 'skia/src/core/SkRecord.cpp',
'skia/src/core/SkRecordDraw.cpp',
- 'skia/src/core/SkRecorder.cpp',
- 'skia/src/core/SkRecording.cpp',
'skia/src/core/SkRecordOpts.cpp',
+ 'skia/src/core/SkRecords.cpp',
'skia/src/core/SkRect.cpp',
'skia/src/core/SkRefDict.cpp',
'skia/src/core/SkRegion.cpp',
'skia/src/core/SkRegion_path.cpp',
+ 'skia/src/core/SkRemote.cpp',
+ 'skia/src/core/SkResourceCache.cpp',
'skia/src/core/SkRRect.cpp',
'skia/src/core/SkRTree.cpp',
+ 'skia/src/core/SkRWBuffer.cpp',
'skia/src/core/SkScalar.cpp',
'skia/src/core/SkScalerContext.cpp',
'skia/src/core/SkScan.cpp',
'skia/src/core/SkScan_AntiPath.cpp',
'skia/src/core/SkScan_Hairline.cpp',
'skia/src/core/SkScan_Path.cpp',
+ 'skia/src/core/SkSemaphore.cpp',
'skia/src/core/SkShader.cpp',
+ 'skia/src/core/SkSharedMutex.cpp',
+ 'skia/src/core/SkSpinlock.cpp',
'skia/src/core/SkSpriteBlitter_ARGB32.cpp',
'skia/src/core/SkSpriteBlitter_RGB16.cpp',
'skia/src/core/SkStream.cpp',
@@ -139,7 +155,10 @@ UNIFIED_SOURCES += [
'skia/src/core/SkStroke.cpp',
'skia/src/core/SkStrokeRec.cpp',
'skia/src/core/SkStrokerPriv.cpp',
- 'skia/src/core/SkTileGrid.cpp',
+ 'skia/src/core/SkTaskGroup.cpp',
+ 'skia/src/core/SkTextBlob.cpp',
+ 'skia/src/core/SkThreadID.cpp',
+ 'skia/src/core/SkTime.cpp',
'skia/src/core/SkTLS.cpp',
'skia/src/core/SkTSearch.cpp',
'skia/src/core/SkTypeface.cpp',
@@ -147,30 +166,33 @@ UNIFIED_SOURCES += [
'skia/src/core/SkUnPreMultiply.cpp',
'skia/src/core/SkUtils.cpp',
'skia/src/core/SkValidatingReadBuffer.cpp',
+ 'skia/src/core/SkVarAlloc.cpp',
'skia/src/core/SkVertState.cpp',
'skia/src/core/SkWriteBuffer.cpp',
'skia/src/core/SkWriter32.cpp',
'skia/src/core/SkXfermode.cpp',
+ 'skia/src/core/SkXfermodeInterpretation.cpp',
+ 'skia/src/core/SkYUVPlanesCache.cpp',
'skia/src/doc/SkDocument.cpp',
- 'skia/src/effects/gradients/SkBitmapCache.cpp',
'skia/src/effects/gradients/SkClampRange.cpp',
+ 'skia/src/effects/gradients/SkGradientBitmapCache.cpp',
'skia/src/effects/gradients/SkGradientShader.cpp',
'skia/src/effects/gradients/SkLinearGradient.cpp',
'skia/src/effects/gradients/SkRadialGradient.cpp',
'skia/src/effects/gradients/SkSweepGradient.cpp',
'skia/src/effects/gradients/SkTwoPointConicalGradient.cpp',
'skia/src/effects/gradients/SkTwoPointConicalGradient_gpu.cpp',
- 'skia/src/effects/gradients/SkTwoPointRadialGradient.cpp',
+ 'skia/src/effects/GrCircleBlurFragmentProcessor.cpp',
'skia/src/effects/Sk1DPathEffect.cpp',
'skia/src/effects/Sk2DPathEffect.cpp',
'skia/src/effects/SkAlphaThresholdFilter.cpp',
+ 'skia/src/effects/SkArcToPathEffect.cpp',
'skia/src/effects/SkArithmeticMode.cpp',
- 'skia/src/effects/SkAvoidXfermode.cpp',
- 'skia/src/effects/SkBitmapSource.cpp',
'skia/src/effects/SkBlurDrawLooper.cpp',
'skia/src/effects/SkBlurImageFilter.cpp',
'skia/src/effects/SkBlurMask.cpp',
'skia/src/effects/SkBlurMaskFilter.cpp',
+ 'skia/src/effects/SkColorCubeFilter.cpp',
'skia/src/effects/SkColorFilterImageFilter.cpp',
'skia/src/effects/SkColorFilters.cpp',
'skia/src/effects/SkColorMatrix.cpp',
@@ -184,6 +206,7 @@ UNIFIED_SOURCES += [
'skia/src/effects/SkEmbossMask.cpp',
'skia/src/effects/SkEmbossMaskFilter.cpp',
'skia/src/effects/SkGpuBlurUtils.cpp',
+ 'skia/src/effects/SkImageSource.cpp',
'skia/src/effects/SkLayerDrawLooper.cpp',
'skia/src/effects/SkLayerRasterizer.cpp',
'skia/src/effects/SkLerpXfermode.cpp',
@@ -191,7 +214,6 @@ UNIFIED_SOURCES += [
'skia/src/effects/SkLumaColorFilter.cpp',
'skia/src/effects/SkMagnifierImageFilter.cpp',
'skia/src/effects/SkMatrixConvolutionImageFilter.cpp',
- 'skia/src/effects/SkMatrixImageFilter.cpp',
'skia/src/effects/SkMergeImageFilter.cpp',
'skia/src/effects/SkMorphologyImageFilter.cpp',
'skia/src/effects/SkOffsetImageFilter.cpp',
@@ -199,131 +221,142 @@ UNIFIED_SOURCES += [
'skia/src/effects/SkPerlinNoiseShader.cpp',
'skia/src/effects/SkPictureImageFilter.cpp',
'skia/src/effects/SkPixelXorXfermode.cpp',
- 'skia/src/effects/SkPorterDuff.cpp',
'skia/src/effects/SkRectShaderImageFilter.cpp',
- 'skia/src/effects/SkStippleMaskFilter.cpp',
'skia/src/effects/SkTableColorFilter.cpp',
'skia/src/effects/SkTableMaskFilter.cpp',
'skia/src/effects/SkTestImageFilters.cpp',
'skia/src/effects/SkTileImageFilter.cpp',
- 'skia/src/effects/SkTransparentShader.cpp',
'skia/src/effects/SkXfermodeImageFilter.cpp',
'skia/src/fonts/SkFontMgr_indirect.cpp',
'skia/src/fonts/SkGScalerContext.cpp',
+ 'skia/src/fonts/SkRandomScalerContext.cpp',
'skia/src/fonts/SkRemotableFontMgr.cpp',
'skia/src/fonts/SkTestScalerContext.cpp',
+ 'skia/src/gpu/batches/GrAtlasTextBatch.cpp',
+ 'skia/src/gpu/batches/GrBatch.cpp',
+ 'skia/src/gpu/batches/GrCopySurfaceBatch.cpp',
+ 'skia/src/gpu/batches/GrDashLinePathRenderer.cpp',
+ 'skia/src/gpu/batches/GrDefaultPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrDrawAtlasBatch.cpp',
+ 'skia/src/gpu/batches/GrDrawBatch.cpp',
+ 'skia/src/gpu/batches/GrDrawPathBatch.cpp',
+ 'skia/src/gpu/batches/GrDrawVerticesBatch.cpp',
+ 'skia/src/gpu/batches/GrNinePatch.cpp',
+ 'skia/src/gpu/batches/GrNonAAFillRectBatch.cpp',
+ 'skia/src/gpu/batches/GrNonAAStrokeRectBatch.cpp',
+ 'skia/src/gpu/batches/GrRectBatchFactory.cpp',
+ 'skia/src/gpu/batches/GrStencilAndCoverPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrTessellatingPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrVertexBatch.cpp',
'skia/src/gpu/effects/GrBezierEffect.cpp',
'skia/src/gpu/effects/GrBicubicEffect.cpp',
+ 'skia/src/gpu/effects/GrBitmapTextGeoProc.cpp',
'skia/src/gpu/effects/GrConfigConversionEffect.cpp',
+ 'skia/src/gpu/effects/GrConstColorProcessor.cpp',
'skia/src/gpu/effects/GrConvexPolyEffect.cpp',
'skia/src/gpu/effects/GrConvolutionEffect.cpp',
- 'skia/src/gpu/effects/GrCustomCoordsTextureEffect.cpp',
+ 'skia/src/gpu/effects/GrCoverageSetOpXP.cpp',
+ 'skia/src/gpu/effects/GrCustomXfermode.cpp',
'skia/src/gpu/effects/GrDashingEffect.cpp',
- 'skia/src/gpu/effects/GrDistanceFieldTextureEffect.cpp',
+ 'skia/src/gpu/effects/GrDisableColorXP.cpp',
+ 'skia/src/gpu/effects/GrDistanceFieldGeoProc.cpp',
'skia/src/gpu/effects/GrDitherEffect.cpp',
'skia/src/gpu/effects/GrMatrixConvolutionEffect.cpp',
'skia/src/gpu/effects/GrOvalEffect.cpp',
+ 'skia/src/gpu/effects/GrPorterDuffXferProcessor.cpp',
'skia/src/gpu/effects/GrRRectEffect.cpp',
'skia/src/gpu/effects/GrSimpleTextureEffect.cpp',
'skia/src/gpu/effects/GrSingleTextureEffect.cpp',
'skia/src/gpu/effects/GrTextureDomain.cpp',
'skia/src/gpu/effects/GrTextureStripAtlas.cpp',
+ 'skia/src/gpu/effects/GrXfermodeFragmentProcessor.cpp',
'skia/src/gpu/effects/GrYUVtoRGBEffect.cpp',
'skia/src/gpu/gl/debug/GrBufferObj.cpp',
'skia/src/gpu/gl/debug/GrDebugGL.cpp',
'skia/src/gpu/gl/debug/GrFrameBufferObj.cpp',
- 'skia/src/gpu/gl/debug/GrGLCreateDebugInterface.cpp',
'skia/src/gpu/gl/debug/GrProgramObj.cpp',
'skia/src/gpu/gl/debug/GrShaderObj.cpp',
'skia/src/gpu/gl/debug/GrTextureObj.cpp',
'skia/src/gpu/gl/debug/GrTextureUnitObj.cpp',
'skia/src/gpu/gl/debug/SkDebugGLContext.cpp',
- 'skia/src/gpu/gl/GrGLAssembleInterface.cpp',
- 'skia/src/gpu/gl/GrGLBufferImpl.cpp',
- 'skia/src/gpu/gl/GrGLCaps.cpp',
- 'skia/src/gpu/gl/GrGLContext.cpp',
- 'skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
- 'skia/src/gpu/gl/GrGLCreateNullInterface.cpp',
- 'skia/src/gpu/gl/GrGLDefaultInterface_native.cpp',
- 'skia/src/gpu/gl/GrGLExtensions.cpp',
- 'skia/src/gpu/gl/GrGLIndexBuffer.cpp',
- 'skia/src/gpu/gl/GrGLInterface.cpp',
- 'skia/src/gpu/gl/GrGLNameAllocator.cpp',
- 'skia/src/gpu/gl/GrGLNoOpInterface.cpp',
- 'skia/src/gpu/gl/GrGLPath.cpp',
- 'skia/src/gpu/gl/GrGLPathRange.cpp',
- 'skia/src/gpu/gl/GrGLProgram.cpp',
- 'skia/src/gpu/gl/GrGLProgramDesc.cpp',
- 'skia/src/gpu/gl/GrGLProgramEffects.cpp',
- 'skia/src/gpu/gl/GrGLRenderTarget.cpp',
- 'skia/src/gpu/gl/GrGLShaderBuilder.cpp',
- 'skia/src/gpu/gl/GrGLSL.cpp',
- 'skia/src/gpu/gl/GrGLStencilBuffer.cpp',
- 'skia/src/gpu/gl/GrGLTexture.cpp',
- 'skia/src/gpu/gl/GrGLUniformManager.cpp',
- 'skia/src/gpu/gl/GrGLUtil.cpp',
- 'skia/src/gpu/gl/GrGLVertexArray.cpp',
- 'skia/src/gpu/gl/GrGLVertexBuffer.cpp',
- 'skia/src/gpu/gl/GrGpuGL.cpp',
- 'skia/src/gpu/gl/GrGpuGL_program.cpp',
- 'skia/src/gpu/gl/SkGLContextHelper.cpp',
+ 'skia/src/gpu/gl/SkGLContext.cpp',
'skia/src/gpu/gl/SkNullGLContext.cpp',
- 'skia/src/gpu/GrAAConvexPathRenderer.cpp',
- 'skia/src/gpu/GrAAHairLinePathRenderer.cpp',
- 'skia/src/gpu/GrAARectRenderer.cpp',
- 'skia/src/gpu/GrAllocPool.cpp',
- 'skia/src/gpu/GrAtlas.cpp',
- 'skia/src/gpu/GrBitmapTextContext.cpp',
+ 'skia/src/gpu/GrAtlasTextBlob.cpp',
+ 'skia/src/gpu/GrAtlasTextContext.cpp',
+ 'skia/src/gpu/GrBatchFlushState.cpp',
+ 'skia/src/gpu/GrBatchFontCache.cpp',
+ 'skia/src/gpu/GrBatchTest.cpp',
'skia/src/gpu/GrBlend.cpp',
+ 'skia/src/gpu/GrBlurUtils.cpp',
'skia/src/gpu/GrBufferAllocPool.cpp',
- 'skia/src/gpu/GrCacheID.cpp',
- 'skia/src/gpu/GrClipData.cpp',
- 'skia/src/gpu/GrClipMaskCache.cpp',
+ 'skia/src/gpu/GrCaps.cpp',
+ 'skia/src/gpu/GrClip.cpp',
'skia/src/gpu/GrClipMaskManager.cpp',
'skia/src/gpu/GrContext.cpp',
- 'skia/src/gpu/GrDefaultPathRenderer.cpp',
- 'skia/src/gpu/GrDrawState.cpp',
+ 'skia/src/gpu/GrCoordTransform.cpp',
+ 'skia/src/gpu/GrDefaultGeoProcFactory.cpp',
+ 'skia/src/gpu/GrDrawingManager.cpp',
'skia/src/gpu/GrDrawTarget.cpp',
- 'skia/src/gpu/GrEffect.cpp',
'skia/src/gpu/GrFontScaler.cpp',
+ 'skia/src/gpu/GrFragmentProcessor.cpp',
'skia/src/gpu/GrGpu.cpp',
'skia/src/gpu/GrGpuFactory.cpp',
'skia/src/gpu/GrGpuResource.cpp',
- 'skia/src/gpu/GrInOrderDrawBuffer.cpp',
+ 'skia/src/gpu/GrGpuResourceRef.cpp',
+ 'skia/src/gpu/GrImageIDTextureAdjuster.cpp',
+ 'skia/src/gpu/GrInvariantOutput.cpp',
+ 'skia/src/gpu/GrLayerAtlas.cpp',
'skia/src/gpu/GrLayerCache.cpp',
+ 'skia/src/gpu/GrLayerHoister.cpp',
'skia/src/gpu/GrMemoryPool.cpp',
'skia/src/gpu/GrOvalRenderer.cpp',
'skia/src/gpu/GrPaint.cpp',
'skia/src/gpu/GrPath.cpp',
+ 'skia/src/gpu/GrPathProcessor.cpp',
+ 'skia/src/gpu/GrPathRange.cpp',
'skia/src/gpu/GrPathRenderer.cpp',
'skia/src/gpu/GrPathRendererChain.cpp',
+ 'skia/src/gpu/GrPathRendering.cpp',
'skia/src/gpu/GrPathUtils.cpp',
- 'skia/src/gpu/GrPictureUtils.cpp',
+ 'skia/src/gpu/GrPipeline.cpp',
+ 'skia/src/gpu/GrPipelineBuilder.cpp',
+ 'skia/src/gpu/GrPrimitiveProcessor.cpp',
+ 'skia/src/gpu/GrProcessor.cpp',
+ 'skia/src/gpu/GrProcessorUnitTest.cpp',
+ 'skia/src/gpu/GrProcOptInfo.cpp',
+ 'skia/src/gpu/GrProgramElement.cpp',
+ 'skia/src/gpu/GrRecordReplaceDraw.cpp',
'skia/src/gpu/GrRectanizer_pow2.cpp',
'skia/src/gpu/GrRectanizer_skyline.cpp',
'skia/src/gpu/GrReducedClip.cpp',
'skia/src/gpu/GrRenderTarget.cpp',
- 'skia/src/gpu/GrResourceCache.cpp',
+ 'skia/src/gpu/GrResourceProvider.cpp',
'skia/src/gpu/GrSoftwarePathRenderer.cpp',
'skia/src/gpu/GrStencil.cpp',
- 'skia/src/gpu/GrStencilAndCoverPathRenderer.cpp',
'skia/src/gpu/GrStencilAndCoverTextContext.cpp',
- 'skia/src/gpu/GrStencilBuffer.cpp',
+ 'skia/src/gpu/GrStencilAttachment.cpp',
+ 'skia/src/gpu/GrStrokeInfo.cpp',
'skia/src/gpu/GrSurface.cpp',
'skia/src/gpu/GrSWMaskHelper.cpp',
+ 'skia/src/gpu/GrTestUtils.cpp',
+ 'skia/src/gpu/GrTextBlobCache.cpp',
'skia/src/gpu/GrTextContext.cpp',
- 'skia/src/gpu/GrTextStrike.cpp',
'skia/src/gpu/GrTexture.cpp',
'skia/src/gpu/GrTextureAccess.cpp',
+ 'skia/src/gpu/GrTextureParamsAdjuster.cpp',
+ 'skia/src/gpu/GrTextureProvider.cpp',
'skia/src/gpu/GrTraceMarker.cpp',
+ 'skia/src/gpu/GrXferProcessor.cpp',
+ 'skia/src/gpu/GrYUVProvider.cpp',
'skia/src/gpu/SkGpuDevice.cpp',
+ 'skia/src/gpu/SkGpuDevice_drawTexture.cpp',
'skia/src/gpu/SkGr.cpp',
'skia/src/gpu/SkGrPixelRef.cpp',
'skia/src/gpu/SkGrTexturePixelRef.cpp',
'skia/src/image/SkImage.cpp',
- 'skia/src/image/SkImage_Gpu.cpp',
+ 'skia/src/image/SkImage_Generator.cpp',
'skia/src/image/SkImage_Raster.cpp',
- 'skia/src/image/SkImagePriv.cpp',
+ 'skia/src/image/SkImageShader.cpp',
'skia/src/image/SkSurface.cpp',
'skia/src/image/SkSurface_Gpu.cpp',
'skia/src/image/SkSurface_Raster.cpp',
@@ -331,26 +364,27 @@ UNIFIED_SOURCES += [
'skia/src/images/SkDecodingImageGenerator.cpp',
'skia/src/images/SkPageFlipper.cpp',
'skia/src/images/SkScaledBitmapSampler.cpp',
- 'skia/src/lazy/SkCachingPixelRef.cpp',
'skia/src/lazy/SkDiscardableMemoryPool.cpp',
'skia/src/lazy/SkDiscardablePixelRef.cpp',
'skia/src/pathops/SkAddIntersections.cpp',
- 'skia/src/pathops/SkDCubicIntersection.cpp',
+ 'skia/src/pathops/SkDConicLineIntersection.cpp',
'skia/src/pathops/SkDCubicLineIntersection.cpp',
'skia/src/pathops/SkDCubicToQuads.cpp',
'skia/src/pathops/SkDLineIntersection.cpp',
- 'skia/src/pathops/SkDQuadImplicit.cpp',
- 'skia/src/pathops/SkDQuadIntersection.cpp',
'skia/src/pathops/SkDQuadLineIntersection.cpp',
'skia/src/pathops/SkIntersections.cpp',
'skia/src/pathops/SkOpAngle.cpp',
+ 'skia/src/pathops/SkOpBuilder.cpp',
+ 'skia/src/pathops/SkOpCoincidence.cpp',
'skia/src/pathops/SkOpContour.cpp',
+ 'skia/src/pathops/SkOpCubicHull.cpp',
'skia/src/pathops/SkOpEdgeBuilder.cpp',
'skia/src/pathops/SkOpSegment.cpp',
- 'skia/src/pathops/SkPathOpsBounds.cpp',
+ 'skia/src/pathops/SkOpSpan.cpp',
'skia/src/pathops/SkPathOpsCommon.cpp',
+ 'skia/src/pathops/SkPathOpsConic.cpp',
'skia/src/pathops/SkPathOpsCubic.cpp',
- 'skia/src/pathops/SkPathOpsDebug.cpp',
+ 'skia/src/pathops/SkPathOpsCurve.cpp',
'skia/src/pathops/SkPathOpsLine.cpp',
'skia/src/pathops/SkPathOpsOp.cpp',
'skia/src/pathops/SkPathOpsPoint.cpp',
@@ -358,21 +392,24 @@ UNIFIED_SOURCES += [
'skia/src/pathops/SkPathOpsRect.cpp',
'skia/src/pathops/SkPathOpsSimplify.cpp',
'skia/src/pathops/SkPathOpsTightBounds.cpp',
- 'skia/src/pathops/SkPathOpsTriangle.cpp',
+ 'skia/src/pathops/SkPathOpsTSect.cpp',
'skia/src/pathops/SkPathOpsTypes.cpp',
+ 'skia/src/pathops/SkPathOpsWinding.cpp',
'skia/src/pathops/SkPathWriter.cpp',
- 'skia/src/pathops/SkQuarticRoot.cpp',
'skia/src/pathops/SkReduceOrder.cpp',
'skia/src/pipe/SkGPipeRead.cpp',
'skia/src/pipe/SkGPipeWrite.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkGlobalInitialization_default.cpp',
'skia/src/ports/SkImageDecoder_empty.cpp',
+ 'skia/src/ports/SkImageGenerator_skia.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
'skia/src/ports/SkOSFile_stdio.cpp',
'skia/src/sfnt/SkOTTable_name.cpp',
'skia/src/sfnt/SkOTUtils.cpp',
+ 'skia/src/utils/android/SkAndroidSDKCanvas.cpp',
'skia/src/utils/SkBase64.cpp',
+ 'skia/src/utils/SkBitmapSourceDeserializer.cpp',
'skia/src/utils/SkBitSet.cpp',
'skia/src/utils/SkBoundaryPatch.cpp',
'skia/src/utils/SkCamera.cpp',
@@ -381,11 +418,10 @@ UNIFIED_SOURCES += [
'skia/src/utils/SkCubicInterval.cpp',
'skia/src/utils/SkCullPoints.cpp',
'skia/src/utils/SkDashPath.cpp',
- 'skia/src/utils/SkDeferredCanvas.cpp',
'skia/src/utils/SkDumpCanvas.cpp',
'skia/src/utils/SkEventTracer.cpp',
'skia/src/utils/SkFrontBufferedStream.cpp',
- 'skia/src/utils/SkGatherPixelRefsAndRects.cpp',
+ 'skia/src/utils/SkImageGeneratorUtils.cpp',
'skia/src/utils/SkInterpolator.cpp',
'skia/src/utils/SkLayer.cpp',
'skia/src/utils/SkMatrix22.cpp',
@@ -395,16 +431,17 @@ UNIFIED_SOURCES += [
'skia/src/utils/SkNullCanvas.cpp',
'skia/src/utils/SkNWayCanvas.cpp',
'skia/src/utils/SkOSFile.cpp',
+ 'skia/src/utils/SkPaintFilterCanvas.cpp',
'skia/src/utils/SkParseColor.cpp',
- 'skia/src/utils/SkParsePath.cpp',
- 'skia/src/utils/SkPathUtils.cpp',
- 'skia/src/utils/SkPictureUtils.cpp',
- 'skia/src/utils/SkProxyCanvas.cpp',
+ 'skia/src/utils/SkPatchGrid.cpp',
+ 'skia/src/utils/SkPatchUtils.cpp',
'skia/src/utils/SkRTConf.cpp',
+ 'skia/src/utils/SkTextBox.cpp',
'skia/src/utils/SkTextureCompressor.cpp',
'skia/src/utils/SkTextureCompressor_ASTC.cpp',
'skia/src/utils/SkTextureCompressor_LATC.cpp',
'skia/src/utils/SkTextureCompressor_R11EAC.cpp',
+ 'skia/src/utils/SkWhitelistTypefaces.cpp',
]
SOURCES += [
'skia/src/core/SkAdvancedTypefaceMetrics.cpp',
@@ -414,33 +451,93 @@ SOURCES += [
'skia/src/core/SkBlitter_RGB16.cpp',
'skia/src/core/SkBlitter_Sprite.cpp',
'skia/src/core/SkFontHost.cpp',
+ 'skia/src/core/SkOpts.cpp',
'skia/src/core/SkPictureData.cpp',
- 'skia/src/core/SkScaledImageCache.cpp',
+ 'skia/src/core/SkRecorder.cpp',
'skia/src/core/SkScan_Antihair.cpp',
- 'skia/src/gpu/GrAddPathRenderers_default.cpp',
- 'skia/src/gpu/GrDistanceFieldTextContext.cpp',
+ 'skia/src/effects/SkArithmeticMode_gpu.cpp',
+ 'skia/src/gpu/batches/GrAAConvexPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrAAConvexTessellator.cpp',
+ 'skia/src/gpu/batches/GrAADistanceFieldPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrAAFillRectBatch.cpp',
+ 'skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp',
+ 'skia/src/gpu/batches/GrAALinearizingConvexPathRenderer.cpp',
+ 'skia/src/gpu/batches/GrAAStrokeRectBatch.cpp',
+ 'skia/src/gpu/gl/builders/GrGLProgramBuilder.cpp',
+ 'skia/src/gpu/gl/builders/GrGLShaderStringBuilder.cpp',
+ 'skia/src/gpu/gl/builders/GrGLSLPrettyPrint.cpp',
+ 'skia/src/gpu/gl/debug/GrGLCreateDebugInterface.cpp',
+ 'skia/src/gpu/gl/GrGLAssembleInterface.cpp',
+ 'skia/src/gpu/gl/GrGLBufferImpl.cpp',
+ 'skia/src/gpu/gl/GrGLCaps.cpp',
+ 'skia/src/gpu/gl/GrGLContext.cpp',
+ 'skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
+ 'skia/src/gpu/gl/GrGLCreateNullInterface.cpp',
+ 'skia/src/gpu/gl/GrGLDefaultInterface_native.cpp',
+ 'skia/src/gpu/gl/GrGLExtensions.cpp',
+ 'skia/src/gpu/gl/GrGLGLSL.cpp',
+ 'skia/src/gpu/gl/GrGLGpu.cpp',
+ 'skia/src/gpu/gl/GrGLGpuProgramCache.cpp',
+ 'skia/src/gpu/gl/GrGLIndexBuffer.cpp',
+ 'skia/src/gpu/gl/GrGLInterface.cpp',
+ 'skia/src/gpu/gl/GrGLNameAllocator.cpp',
+ 'skia/src/gpu/gl/GrGLNoOpInterface.cpp',
+ 'skia/src/gpu/gl/GrGLPath.cpp',
+ 'skia/src/gpu/gl/GrGLPathRange.cpp',
+ 'skia/src/gpu/gl/GrGLPathRendering.cpp',
+ 'skia/src/gpu/gl/GrGLProgram.cpp',
+ 'skia/src/gpu/gl/GrGLProgramDataManager.cpp',
+ 'skia/src/gpu/gl/GrGLProgramDesc.cpp',
+ 'skia/src/gpu/gl/GrGLRenderTarget.cpp',
+ 'skia/src/gpu/gl/GrGLStencilAttachment.cpp',
+ 'skia/src/gpu/gl/GrGLTexture.cpp',
+ 'skia/src/gpu/gl/GrGLTextureRenderTarget.cpp',
+ 'skia/src/gpu/gl/GrGLUtil.cpp',
+ 'skia/src/gpu/gl/GrGLVaryingHandler.cpp',
+ 'skia/src/gpu/gl/GrGLVertexArray.cpp',
+ 'skia/src/gpu/gl/GrGLVertexBuffer.cpp',
+ 'skia/src/gpu/glsl/GrGLSL.cpp',
+ 'skia/src/gpu/glsl/GrGLSLBlend.cpp',
+ 'skia/src/gpu/glsl/GrGLSLCaps.cpp',
+ 'skia/src/gpu/glsl/GrGLSLFragmentProcessor.cpp',
+ 'skia/src/gpu/glsl/GrGLSLFragmentShaderBuilder.cpp',
+ 'skia/src/gpu/glsl/GrGLSLGeometryProcessor.cpp',
+ 'skia/src/gpu/glsl/GrGLSLGeometryShaderBuilder.cpp',
+ 'skia/src/gpu/glsl/GrGLSLPrimitiveProcessor.cpp',
+ 'skia/src/gpu/glsl/GrGLSLProgramBuilder.cpp',
+ 'skia/src/gpu/glsl/GrGLSLShaderBuilder.cpp',
+ 'skia/src/gpu/glsl/GrGLSLUtil.cpp',
+ 'skia/src/gpu/glsl/GrGLSLVarying.cpp',
+ 'skia/src/gpu/glsl/GrGLSLVertexShaderBuilder.cpp',
+ 'skia/src/gpu/glsl/GrGLSLXferProcessor.cpp',
+ 'skia/src/gpu/GrBatchAtlas.cpp',
+ 'skia/src/gpu/GrDrawContext.cpp',
+ 'skia/src/gpu/GrResourceCache.cpp',
+ 'skia/src/image/SkImage_Gpu.cpp',
+ 'skia/src/pathops/SkPathOpsDebug.cpp',
'skia/src/utils/SkMD5.cpp',
'skia/src/utils/SkParse.cpp',
+ 'skia/src/utils/SkParsePath.cpp',
'skia/src/utils/SkSHA1.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk'):
UNIFIED_SOURCES += [
'skia/src/ports/SkDebug_android.cpp',
'skia/src/ports/SkOSFile_posix.cpp',
+ 'skia/src/ports/SkOSLibrary_posix.cpp',
'skia/src/ports/SkTime_Unix.cpp',
'skia/src/ports/SkTLS_pthread.cpp',
'skia/src/utils/SkThreadUtils_pthread.cpp',
]
SOURCES += [
- 'skia/src/ports/SkFontHost_android_old.cpp',
'skia/src/ports/SkFontHost_cairo.cpp',
- 'skia/src/ports/SkFontHost_FreeType.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] in {'cocoa', 'uikit'}:
UNIFIED_SOURCES += [
'skia/src/ports/SkDebug_stdio.cpp',
'skia/src/ports/SkOSFile_posix.cpp',
+ 'skia/src/ports/SkOSLibrary_posix.cpp',
'skia/src/ports/SkTime_Unix.cpp',
'skia/src/ports/SkTLS_pthread.cpp',
'skia/src/utils/mac/SkCreateCGImageRef.cpp',
@@ -454,35 +551,36 @@ if CONFIG['MOZ_WIDGET_GTK']:
UNIFIED_SOURCES += [
'skia/src/ports/SkDebug_stdio.cpp',
'skia/src/ports/SkOSFile_posix.cpp',
+ 'skia/src/ports/SkOSLibrary_posix.cpp',
'skia/src/ports/SkTime_Unix.cpp',
'skia/src/ports/SkTLS_pthread.cpp',
'skia/src/utils/SkThreadUtils_pthread.cpp',
]
SOURCES += [
'skia/src/ports/SkFontHost_cairo.cpp',
- 'skia/src/ports/SkFontHost_FreeType.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'qt':
UNIFIED_SOURCES += [
'skia/src/ports/SkDebug_stdio.cpp',
'skia/src/ports/SkOSFile_posix.cpp',
+ 'skia/src/ports/SkOSLibrary_posix.cpp',
'skia/src/ports/SkTime_Unix.cpp',
'skia/src/ports/SkTLS_pthread.cpp',
'skia/src/utils/SkThreadUtils_pthread.cpp',
]
SOURCES += [
'skia/src/ports/SkFontHost_cairo.cpp',
- 'skia/src/ports/SkFontHost_FreeType.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
SOURCES += [
'skia/src/ports/SkDebug_win.cpp',
'skia/src/ports/SkFontHost_win.cpp',
- 'skia/src/ports/SkFontMgr_default_dw.cpp',
'skia/src/ports/SkFontMgr_win_dw.cpp',
+ 'skia/src/ports/SkFontMgr_win_dw_factory.cpp',
'skia/src/ports/SkOSFile_win.cpp',
+ 'skia/src/ports/SkOSLibrary_win.cpp',
'skia/src/ports/SkRemotableFontMgr_win_dw.cpp',
'skia/src/ports/SkScalerContext_win_dw.cpp',
'skia/src/ports/SkTime_win.cpp',
@@ -497,32 +595,22 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
'skia/src/utils/win/SkIStream.cpp',
]
if CONFIG['INTEL_ARCHITECTURE']:
- UNIFIED_SOURCES += [
- 'skia/src/opts/SkTextureCompression_opts_none.cpp',
- ]
SOURCES += [
'skia/src/opts/opts_check_x86.cpp',
'skia/src/opts/SkBitmapFilter_opts_SSE2.cpp',
'skia/src/opts/SkBitmapProcState_opts_SSE2.cpp',
'skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp',
- 'skia/src/opts/SkBlitRect_opts_SSE2.cpp',
'skia/src/opts/SkBlitRow_opts_SSE2.cpp',
- 'skia/src/opts/SkBlurImage_opts_SSE2.cpp',
- 'skia/src/opts/SkBlurImage_opts_SSE4.cpp',
- 'skia/src/opts/SkMorphology_opts_SSE2.cpp',
- 'skia/src/opts/SkUtils_opts_SSE2.cpp',
- 'skia/src/opts/SkXfermode_opts_SSE2.cpp',
+ 'skia/src/opts/SkBlitRow_opts_SSE4.cpp',
+ 'skia/src/opts/SkOpts_avx.cpp',
+ 'skia/src/opts/SkOpts_sse41.cpp',
+ 'skia/src/opts/SkOpts_ssse3.cpp',
]
elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC']:
UNIFIED_SOURCES += [
'skia/src/core/SkUtilsArm.cpp',
'skia/src/opts/SkBitmapProcState_opts_arm.cpp',
'skia/src/opts/SkBlitMask_opts_arm.cpp',
- 'skia/src/opts/SkBlurImage_opts_arm.cpp',
- 'skia/src/opts/SkMorphology_opts_arm.cpp',
- 'skia/src/opts/SkTextureCompression_opts_arm.cpp',
- 'skia/src/opts/SkUtils_opts_arm.cpp',
- 'skia/src/opts/SkXfermode_opts_arm.cpp',
]
SOURCES += [
'skia/src/opts/SkBlitRow_opts_arm.cpp',
@@ -533,61 +621,27 @@ elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC']:
'skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp',
'skia/src/opts/SkBlitMask_opts_arm_neon.cpp',
'skia/src/opts/SkBlitRow_opts_arm_neon.cpp',
- 'skia/src/opts/SkBlurImage_opts_neon.cpp',
- 'skia/src/opts/SkMorphology_opts_neon.cpp',
- 'skia/src/opts/SkTextureCompression_opts_neon.cpp',
- 'skia/src/opts/SkXfermode_opts_arm_neon.cpp',
+ 'skia/src/opts/SkOpts_neon.cpp',
]
SOURCES['skia/src/opts/SkBitmapProcState_arm_neon.cpp'].flags += ['-mfpu=neon']
SOURCES['skia/src/opts/SkBitmapProcState_matrixProcs_neon.cpp'].flags += ['-mfpu=neon']
SOURCES['skia/src/opts/SkBlitMask_opts_arm_neon.cpp'].flags += ['-mfpu=neon']
SOURCES['skia/src/opts/SkBlitRow_opts_arm_neon.cpp'].flags += ['-mfpu=neon']
- SOURCES['skia/src/opts/SkBlurImage_opts_neon.cpp'].flags += ['-mfpu=neon']
- SOURCES['skia/src/opts/SkMorphology_opts_neon.cpp'].flags += ['-mfpu=neon']
- SOURCES['skia/src/opts/SkTextureCompression_opts_neon.cpp'].flags += ['-mfpu=neon']
- SOURCES['skia/src/opts/SkXfermode_opts_arm_neon.cpp'].flags += ['-mfpu=neon']
+ SOURCES['skia/src/opts/SkOpts_neon.cpp'].flags += ['-mfpu=neon']
else:
UNIFIED_SOURCES += [
'skia/src/opts/SkBitmapProcState_opts_none.cpp',
'skia/src/opts/SkBlitMask_opts_none.cpp',
'skia/src/opts/SkBlitRow_opts_none.cpp',
- 'skia/src/opts/SkBlurImage_opts_none.cpp',
- 'skia/src/opts/SkMorphology_opts_none.cpp',
- 'skia/src/opts/SkTextureCompression_opts_none.cpp',
- 'skia/src/opts/SkUtils_opts_none.cpp',
- 'skia/src/opts/SkXfermode_opts_none.cpp',
- 'skia/src/ports/SkDiscardableMemory_none.cpp',
]
-# can we find a better way of dealing with asm sources?
-
-# left out of UNIFIED_SOURCES for now; that's not C++ anyway, nothing else to unify it with
-#XXX: doesn't build with Apple's assembler
-if not CONFIG['INTEL_ARCHITECTURE'] and CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC'] and CONFIG['OS_TARGET'] != 'Darwin':
- SOURCES += [
- 'skia/src/opts/memset.arm.S',
- ]
- if CONFIG['BUILD_ARM_NEON']:
- SOURCES += [
- 'skia/src/opts/memset16_neon.S',
- 'skia/src/opts/memset32_neon.S',
- ]
-
-if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['GNU_CC'] and CONFIG['OS_ARCH'] != 'WINNT':
- if CONFIG['CPU_ARCH'] == 'x86_64':
- SOURCES += [
- 'skia/src/opts/SkBlitRow_opts_SSE4_x64_asm.S',
- ]
- else:
- SOURCES += [
- 'skia/src/opts/SkBlitRow_opts_SSE4_asm.S',
- ]
-
+# We allow warnings for third-party code that can be updated from upstream.
ALLOW_COMPILER_WARNINGS = True
FINAL_LIBRARY = 'gkmedias'
LOCAL_INCLUDES += [
+ 'skia/include/c',
'skia/include/config',
'skia/include/core',
'skia/include/effects',
@@ -596,6 +650,7 @@ LOCAL_INCLUDES += [
'skia/include/pathops',
'skia/include/pipe',
'skia/include/ports',
+ 'skia/include/private',
'skia/include/utils',
'skia/include/utils/mac',
'skia/include/utils/win',
@@ -622,7 +677,13 @@ if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['HAVE_TOOLCHAIN_SUPPORT_MSSSE3']:
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk'):
DEFINES['SK_FONTHOST_CAIRO_STANDALONE'] = 0
-if (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android') or (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa') or (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'uikit') or (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk') or (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'qt') or CONFIG['MOZ_WIDGET_GTK']:
+if CONFIG['MOZ_WIDGET_TOOLKIT'] in {
+ 'android',
+ 'cocoa',
+ 'uikit',
+ 'gonk',
+ 'qt',
+ } or CONFIG['MOZ_WIDGET_GTK']:
DEFINES['SK_FONTHOST_DOES_NOT_USE_FONTMGR'] = 1
if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
@@ -634,42 +695,34 @@ if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
if CONFIG['_MSC_VER']:
# MSVC doesn't need special compiler flags, but Skia needs to be told that these files should
# be built with the required SSE level or it will simply compile in stubs and cause runtime crashes
- SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=31']
- SOURCES['skia/src/opts/SkBlitRect_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=41']
- SOURCES['skia/src/opts/SkMorphology_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkUtils_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
- SOURCES['skia/src/opts/SkXfermode_opts_SSE2.cpp'].flags += ['-DSK_CPU_SSE_LEVEL=20']
-
+ SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBitmapProcState_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=31']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=20']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=41']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=31']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['/arch:SSE2 -DSK_CPU_SSE_LEVEL=41']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['/arch:AVX -DSK_CPU_SSE_LEVEL=51']
if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['GNU_CC']:
SOURCES['skia/src/opts/SkBitmapFilter_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
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/SkBlitRect_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
SOURCES['skia/src/opts/SkBlitRow_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-msse4.1']
- SOURCES['skia/src/opts/SkMorphology_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkUtils_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
- SOURCES['skia/src/opts/SkXfermode_opts_SSE2.cpp'].flags += CONFIG['SSE2_FLAGS']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
elif CONFIG['CPU_ARCH'] == 'arm' and CONFIG['GNU_CC'] and CONFIG['BUILD_ARM_NEON']:
- DEFINES['__ARM_HAVE_OPTIONAL_NEON_SUPPORT'] = 1
- DEFINES['USE_ANDROID_NDK_CPU_FEATURES'] = 0
+ DEFINES['SK_ARM_HAS_OPTIONAL_NEON'] = 1
elif CONFIG['CLANG_CL']:
SOURCES['skia/src/opts/SkBitmapProcState_opts_SSSE3.cpp'].flags += ['-mssse3']
- SOURCES['skia/src/opts/SkBlurImage_opts_SSE4.cpp'].flags += ['-msse4.1']
-
-if CONFIG['GNU_CXX'] and CONFIG['CPU_ARCH'] == 'arm':
- SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += ['-fomit-frame-pointer']
+ SOURCES['skia/src/opts/SkBlitRow_opts_SSE4.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_ssse3.cpp'].flags += ['-mssse3']
+ SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
+ SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
DEFINES['SKIA_IMPLEMENTATION'] = 1
-DEFINES['GR_IMPLEMENTATION'] = 1
-# Suppress warnings in third-party code.
if CONFIG['GNU_CXX']:
CXXFLAGS += [
'-Wno-deprecated-declarations',
@@ -677,18 +730,22 @@ if CONFIG['GNU_CXX']:
'-Wno-sign-compare',
'-Wno-unused-function',
]
-if CONFIG['GNU_CXX'] and not CONFIG['CLANG_CXX']:
- CXXFLAGS += [
- '-Wno-logical-op',
- '-Wno-maybe-uninitialized',
- ]
-if CONFIG['CLANG_CXX']:
- CXXFLAGS += [
- '-Wno-implicit-fallthrough',
- '-Wno-inconsistent-missing-override',
- '-Wno-macro-redefined',
- '-Wno-unused-private-field',
- ]
+ if CONFIG['CLANG_CXX']:
+ CXXFLAGS += [
+ '-Wno-implicit-fallthrough',
+ '-Wno-inconsistent-missing-override',
+ '-Wno-macro-redefined',
+ '-Wno-unused-private-field',
+ ]
+ # work around inline function linking bug with template arguments
+ SOURCES['skia/src/gpu/GrResourceCache.cpp'].flags += ['-fkeep-inline-functions']
+ else:
+ CXXFLAGS += [
+ '-Wno-logical-op',
+ '-Wno-maybe-uninitialized',
+ ]
+ if CONFIG['CPU_ARCH'] == 'arm':
+ SOURCES['skia/src/opts/SkBlitRow_opts_arm.cpp'].flags += ['-fomit-frame-pointer']
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3', 'android', 'gonk', 'qt'):
CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
diff --git a/gfx/skia/skia/include/android/SkBRDAllocator.h b/gfx/skia/skia/include/android/SkBRDAllocator.h
new file mode 100644
index 0000000000..3ca30c9b41
--- /dev/null
+++ b/gfx/skia/skia/include/android/SkBRDAllocator.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkBRDAllocator_DEFINED
+#define SkBRDAllocator_DEFINED
+
+#include "SkBitmap.h"
+#include "SkCodec.h"
+
+/**
+ * Abstract subclass of SkBitmap's allocator.
+ * Allows the allocator to indicate if the memory it allocates
+ * is zero initialized.
+ */
+class SkBRDAllocator : public SkBitmap::Allocator {
+public:
+
+ /**
+ * Indicates if the memory allocated by this allocator is
+ * zero initialized.
+ */
+ virtual SkCodec::ZeroInitialized zeroInit() const = 0;
+};
+
+#endif // SkBRDAllocator_DEFINED
diff --git a/gfx/skia/skia/include/android/SkBitmapRegionDecoder.h b/gfx/skia/skia/include/android/SkBitmapRegionDecoder.h
new file mode 100644
index 0000000000..575ad9dc01
--- /dev/null
+++ b/gfx/skia/skia/include/android/SkBitmapRegionDecoder.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkBitmapRegionDecoder_DEFINED
+#define SkBitmapRegionDecoder_DEFINED
+
+#include "SkBitmap.h"
+#include "SkBRDAllocator.h"
+#include "SkEncodedFormat.h"
+#include "SkStream.h"
+
+/*
+ * This class aims to provide an interface to test multiple implementations of
+ * SkBitmapRegionDecoder.
+ */
+class SkBitmapRegionDecoder {
+public:
+
+ enum Strategy {
+ kCanvas_Strategy, // Draw to the canvas, uses SkCodec
+ kAndroidCodec_Strategy, // Uses SkAndroidCodec for scaling and subsetting
+ };
+
+ /*
+ * @param data Refs the data while this object exists, unrefs on destruction
+ * @param strategy Strategy used for scaling and subsetting
+ * @return Tries to create an SkBitmapRegionDecoder, returns NULL on failure
+ */
+ static SkBitmapRegionDecoder* Create(
+ SkData* data, Strategy strategy);
+
+ /*
+ * @param stream Takes ownership of the stream
+ * @param strategy Strategy used for scaling and subsetting
+ * @return Tries to create an SkBitmapRegionDecoder, returns NULL on failure
+ */
+ static SkBitmapRegionDecoder* Create(
+ SkStreamRewindable* stream, Strategy strategy);
+
+ /*
+ * Decode a scaled region of the encoded image stream
+ *
+ * @param bitmap Container for decoded pixels. It is assumed that the pixels
+ * are initially unallocated and will be allocated by this function.
+ * @param allocator Allocator for the pixels. If this is NULL, the default
+ * allocator (HeapAllocator) will be used.
+ * @param desiredSubset Subset of the original image to decode.
+ * @param sampleSize An integer downscaling factor for the decode.
+ * @param colorType Preferred output colorType.
+ * New implementations should return NULL if they do not support
+ * decoding to this color type.
+ * The old kOriginal_Strategy will decode to a default color type
+ * if this color type is unsupported.
+ * @param requireUnpremul If the image is not opaque, we will use this to determine the
+ * alpha type to use.
+ *
+ */
+ virtual bool decodeRegion(SkBitmap* bitmap, SkBRDAllocator* allocator,
+ const SkIRect& desiredSubset, int sampleSize,
+ SkColorType colorType, bool requireUnpremul) = 0;
+ /*
+ * @param Requested destination color type
+ * @return true if we support the requested color type and false otherwise
+ */
+ virtual bool conversionSupported(SkColorType colorType) = 0;
+
+ virtual SkEncodedFormat getEncodedFormat() = 0;
+
+ int width() const { return fWidth; }
+ int height() const { return fHeight; }
+
+ virtual ~SkBitmapRegionDecoder() {}
+
+protected:
+
+ SkBitmapRegionDecoder(int width, int height)
+ : fWidth(width)
+ , fHeight(height)
+ {}
+
+private:
+ const int fWidth;
+ const int fHeight;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_canvas.h b/gfx/skia/skia/include/c/sk_canvas.h
new file mode 100644
index 0000000000..f6c0d4e1c1
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_canvas.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_canvas_DEFINED
+#define sk_canvas_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Save the current matrix and clip on the canvas. When the
+ balancing call to sk_canvas_restore() is made, the previous matrix
+ and clip are restored.
+*/
+SK_API void sk_canvas_save(sk_canvas_t*);
+/**
+ This behaves the same as sk_canvas_save(), but in addition it
+ allocates an offscreen surface. All drawing calls are directed
+ there, and only when the balancing call to sk_canvas_restore() is
+ made is that offscreen transfered to the canvas (or the previous
+ layer).
+
+ @param sk_rect_t* (may be null) This rect, if non-null, is used as
+ a hint to limit the size of the offscreen, and
+ thus drawing may be clipped to it, though that
+ clipping is not guaranteed to happen. If exact
+ clipping is desired, use sk_canvas_clip_rect().
+ @param sk_paint_t* (may be null) The paint is copied, and is applied
+ to the offscreen when sk_canvas_restore() is
+ called.
+*/
+SK_API void sk_canvas_save_layer(sk_canvas_t*, const sk_rect_t*, const sk_paint_t*);
+/**
+ This call balances a previous call to sk_canvas_save() or
+ sk_canvas_save_layer(), and is used to remove all modifications to
+ the matrix and clip state since the last save call. It is an
+ error to call sk_canvas_restore() more times than save and
+ save_layer were called.
+*/
+SK_API void sk_canvas_restore(sk_canvas_t*);
+
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified translation.
+*/
+SK_API void sk_canvas_translate(sk_canvas_t*, float dx, float dy);
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified scale.
+*/
+SK_API void sk_canvas_scale(sk_canvas_t*, float sx, float sy);
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified rotation in degrees.
+*/
+SK_API void sk_canvas_rotate_degrees(sk_canvas_t*, float degrees);
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified rotation in radians.
+*/
+SK_API void sk_canvas_rotate_radians(sk_canvas_t*, float radians);
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified skew.
+*/
+SK_API void sk_canvas_skew(sk_canvas_t*, float sx, float sy);
+/**
+ Preconcat the current coordinate transformation matrix with the
+ specified matrix.
+*/
+SK_API void sk_canvas_concat(sk_canvas_t*, const sk_matrix_t*);
+
+/**
+ Modify the current clip with the specified rectangle. The new
+ current clip will be the intersection of the old clip and the
+ rectange.
+*/
+SK_API void sk_canvas_clip_rect(sk_canvas_t*, const sk_rect_t*);
+/**
+ Modify the current clip with the specified path. The new
+ current clip will be the intersection of the old clip and the
+ path.
+*/
+SK_API void sk_canvas_clip_path(sk_canvas_t*, const sk_path_t*);
+
+/**
+ Fill the entire canvas (restricted to the current clip) with the
+ specified paint.
+*/
+SK_API void sk_canvas_draw_paint(sk_canvas_t*, const sk_paint_t*);
+/**
+ Draw the specified rectangle using the specified paint. The
+ rectangle will be filled or stroked based on the style in the
+ paint.
+*/
+SK_API void sk_canvas_draw_rect(sk_canvas_t*, const sk_rect_t*, const sk_paint_t*);
+/**
+ Draw the specified oval using the specified paint. The oval will be
+ filled or framed based on the style in the paint
+*/
+SK_API void sk_canvas_draw_oval(sk_canvas_t*, const sk_rect_t*, const sk_paint_t*);
+/**
+ Draw the specified path using the specified paint. The path will be
+ filled or framed based on the style in the paint
+*/
+SK_API void sk_canvas_draw_path(sk_canvas_t*, const sk_path_t*, const sk_paint_t*);
+/**
+ Draw the specified image, with its top/left corner at (x,y), using
+ the specified paint, transformed by the current matrix.
+
+ @param sk_paint_t* (may be NULL) the paint used to draw the image.
+*/
+SK_API void sk_canvas_draw_image(sk_canvas_t*, const sk_image_t*,
+ float x, float y, const sk_paint_t*);
+/**
+ Draw the specified image, scaling and translating so that it fills
+ the specified dst rect. If the src rect is non-null, only that
+ subset of the image is transformed and drawn.
+
+ @param sk_paint_t* (may be NULL) The paint used to draw the image.
+*/
+SK_API void sk_canvas_draw_image_rect(sk_canvas_t*, const sk_image_t*,
+ const sk_rect_t* src,
+ const sk_rect_t* dst, const sk_paint_t*);
+
+/**
+ Draw the picture into this canvas (replay the pciture's drawing commands).
+
+ @param sk_matrix_t* If non-null, apply that matrix to the CTM when
+ drawing this picture. This is logically
+ equivalent to: save, concat, draw_picture,
+ restore.
+
+ @param sk_paint_t* If non-null, draw the picture into a temporary
+ buffer, and then apply the paint's alpha,
+ colorfilter, imagefilter, and xfermode to that
+ buffer as it is drawn to the canvas. This is
+ logically equivalent to save_layer(paint),
+ draw_picture, restore.
+*/
+SK_API void sk_canvas_draw_picture(sk_canvas_t*, const sk_picture_t*,
+ const sk_matrix_t*, const sk_paint_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_data.h b/gfx/skia/skia/include/c/sk_data.h
new file mode 100644
index 0000000000..90333bba5f
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_data.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_data_DEFINED
+#define sk_data_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Returns a new empty sk_data_t. This call must be balanced with a call to
+ sk_data_unref().
+*/
+SK_API sk_data_t* sk_data_new_empty();
+/**
+ Returns a new sk_data_t by copying the specified source data.
+ This call must be balanced with a call to sk_data_unref().
+*/
+SK_API sk_data_t* sk_data_new_with_copy(const void* src, size_t length);
+/**
+ Pass ownership of the given memory to a new sk_data_t, which will
+ call free() when the refernce count of the data goes to zero. For
+ example:
+ size_t length = 1024;
+ void* buffer = malloc(length);
+ memset(buffer, 'X', length);
+ sk_data_t* data = sk_data_new_from_malloc(buffer, length);
+ This call must be balanced with a call to sk_data_unref().
+*/
+SK_API sk_data_t* sk_data_new_from_malloc(const void* memory, size_t length);
+/**
+ Returns a new sk_data_t using a subset of the data in the
+ specified source sk_data_t. This call must be balanced with a
+ call to sk_data_unref().
+*/
+SK_API sk_data_t* sk_data_new_subset(const sk_data_t* src, size_t offset, size_t length);
+
+/**
+ Increment the reference count on the given sk_data_t. Must be
+ balanced by a call to sk_data_unref().
+*/
+SK_API void sk_data_ref(const sk_data_t*);
+/**
+ Decrement the reference count. If the reference count is 1 before
+ the decrement, then release both the memory holding the sk_data_t
+ and the memory it is managing. New sk_data_t are created with a
+ reference count of 1.
+*/
+SK_API void sk_data_unref(const sk_data_t*);
+
+/**
+ Returns the number of bytes stored.
+*/
+SK_API size_t sk_data_get_size(const sk_data_t*);
+/**
+ Returns the pointer to the data.
+ */
+SK_API const void* sk_data_get_data(const sk_data_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_image.h b/gfx/skia/skia/include/c/sk_image.h
new file mode 100644
index 0000000000..e90649d75d
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_image.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_image_DEFINED
+#define sk_image_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ * Return a new image that has made a copy of the provided pixels, or NULL on failure.
+ * Balance with a call to sk_image_unref().
+ */
+SK_API sk_image_t* sk_image_new_raster_copy(const sk_imageinfo_t*, const void* pixels, size_t rowBytes);
+
+/**
+ * If the specified data can be interpreted as a compressed image (e.g. PNG or JPEG) then this
+ * returns an image. If the encoded data is not supported, returns NULL.
+ *
+ * On success, the encoded data may be processed immediately, or it may be ref()'d for later
+ * use.
+ */
+SK_API sk_image_t* sk_image_new_from_encoded(const sk_data_t* encoded, const sk_irect_t* subset);
+
+/**
+ * Encode the image's pixels and return the result as a new PNG in a
+ * sk_data_t, which the caller must manage: call sk_data_unref() when
+ * they are done.
+ *
+ * If the image type cannot be encoded, this will return NULL.
+ */
+SK_API sk_data_t* sk_image_encode(const sk_image_t*);
+
+/**
+ * Increment the reference count on the given sk_image_t. Must be
+ * balanced by a call to sk_image_unref().
+*/
+SK_API void sk_image_ref(const sk_image_t*);
+/**
+ * Decrement the reference count. If the reference count is 1 before
+ * the decrement, then release both the memory holding the sk_image_t
+ * and the memory it is managing. New sk_image_t are created with a
+ reference count of 1.
+*/
+SK_API void sk_image_unref(const sk_image_t*);
+
+/**
+ * Return the width of the sk_image_t/
+ */
+SK_API int sk_image_get_width(const sk_image_t*);
+/**
+ * Return the height of the sk_image_t/
+ */
+SK_API int sk_image_get_height(const sk_image_t*);
+
+/**
+ * Returns a non-zero value unique among all images.
+ */
+SK_API uint32_t sk_image_get_unique_id(const sk_image_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_maskfilter.h b/gfx/skia/skia/include/c/sk_maskfilter.h
new file mode 100644
index 0000000000..5c22a06391
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_maskfilter.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_maskfilter_DEFINED
+#define sk_maskfilter_DEFINED
+
+#include "sk_types.h"
+
+typedef enum {
+ NORMAL_SK_BLUR_STYLE, //!< fuzzy inside and outside
+ SOLID_SK_BLUR_STYLE, //!< solid inside, fuzzy outside
+ OUTER_SK_BLUR_STYLE, //!< nothing inside, fuzzy outside
+ INNER_SK_BLUR_STYLE, //!< fuzzy inside, nothing outside
+} sk_blurstyle_t;
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Increment the reference count on the given sk_maskfilter_t. Must be
+ balanced by a call to sk_maskfilter_unref().
+*/
+void sk_maskfilter_ref(sk_maskfilter_t*);
+/**
+ Decrement the reference count. If the reference count is 1 before
+ the decrement, then release both the memory holding the
+ sk_maskfilter_t and any other associated resources. New
+ sk_maskfilter_t are created with a reference count of 1.
+*/
+void sk_maskfilter_unref(sk_maskfilter_t*);
+
+/**
+ Create a blur maskfilter.
+ @param sk_blurstyle_t The SkBlurStyle to use
+ @param sigma Standard deviation of the Gaussian blur to apply. Must be > 0.
+*/
+sk_maskfilter_t* sk_maskfilter_new_blur(sk_blurstyle_t, float sigma);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_matrix.h b/gfx/skia/skia/include/c/sk_matrix.h
new file mode 100644
index 0000000000..83f0122b00
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_matrix.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_matrix_DEFINED
+#define sk_matrix_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/** Set the matrix to identity */
+void sk_matrix_set_identity(sk_matrix_t*);
+
+/** Set the matrix to translate by (tx, ty). */
+void sk_matrix_set_translate(sk_matrix_t*, float tx, float ty);
+/**
+ Preconcats the matrix with the specified translation.
+ M' = M * T(dx, dy)
+*/
+void sk_matrix_pre_translate(sk_matrix_t*, float tx, float ty);
+/**
+ Postconcats the matrix with the specified translation.
+ M' = T(dx, dy) * M
+*/
+void sk_matrix_post_translate(sk_matrix_t*, float tx, float ty);
+
+/** Set the matrix to scale by sx and sy. */
+void sk_matrix_set_scale(sk_matrix_t*, float sx, float sy);
+/**
+ Preconcats the matrix with the specified scale.
+ M' = M * S(sx, sy)
+*/
+void sk_matrix_pre_scale(sk_matrix_t*, float sx, float sy);
+/**
+ Postconcats the matrix with the specified scale.
+ M' = S(sx, sy) * M
+*/
+void sk_matrix_post_scale(sk_matrix_t*, float sx, float sy);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_paint.h b/gfx/skia/skia/include/c/sk_paint.h
new file mode 100644
index 0000000000..e0886ad349
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_paint.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_paint_DEFINED
+#define sk_paint_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Create a new paint with default settings:
+ antialias : false
+ stroke : false
+ stroke width : 0.0f (hairline)
+ stroke miter : 4.0f
+ stroke cap : BUTT_SK_STROKE_CAP
+ stroke join : MITER_SK_STROKE_JOIN
+ color : opaque black
+ shader : NULL
+ maskfilter : NULL
+ xfermode_mode : SRCOVER_SK_XFERMODE_MODE
+*/
+SK_API sk_paint_t* sk_paint_new();
+/**
+ Release the memory storing the sk_paint_t and unref() all
+ associated objects.
+*/
+SK_API void sk_paint_delete(sk_paint_t*);
+
+/**
+ Return true iff the paint has antialiasing enabled.
+*/
+SK_API bool sk_paint_is_antialias(const sk_paint_t*);
+/**
+ Set to true to enable antialiasing, false to disable it on this
+ sk_paint_t.
+*/
+SK_API void sk_paint_set_antialias(sk_paint_t*, bool);
+
+/**
+ Return the paint's curent drawing color.
+*/
+SK_API sk_color_t sk_paint_get_color(const sk_paint_t*);
+/**
+ Set the paint's curent drawing color.
+*/
+SK_API void sk_paint_set_color(sk_paint_t*, sk_color_t);
+
+/* stroke settings */
+
+/**
+ Return true iff stroking is enabled rather than filling on this
+ sk_paint_t.
+*/
+SK_API bool sk_paint_is_stroke(const sk_paint_t*);
+/**
+ Set to true to enable stroking rather than filling with this
+ sk_paint_t.
+*/
+SK_API void sk_paint_set_stroke(sk_paint_t*, bool);
+
+/**
+ Return the width for stroking. A value of 0 strokes in hairline mode.
+ */
+SK_API float sk_paint_get_stroke_width(const sk_paint_t*);
+/**
+ Set the width for stroking. A value of 0 strokes in hairline mode
+ (always draw 1-pixel wide, regardless of the matrix).
+ */
+SK_API void sk_paint_set_stroke_width(sk_paint_t*, float width);
+
+/**
+ Return the paint's stroke miter value. This is used to control the
+ behavior of miter joins when the joins angle is sharp.
+*/
+SK_API float sk_paint_get_stroke_miter(const sk_paint_t*);
+/**
+ Set the paint's stroke miter value. This is used to control the
+ behavior of miter joins when the joins angle is sharp. This value
+ must be >= 0.
+*/
+SK_API void sk_paint_set_stroke_miter(sk_paint_t*, float miter);
+
+typedef enum {
+ BUTT_SK_STROKE_CAP,
+ ROUND_SK_STROKE_CAP,
+ SQUARE_SK_STROKE_CAP
+} sk_stroke_cap_t;
+
+/**
+ Return the paint's stroke cap type, controlling how the start and
+ end of stroked lines and paths are treated.
+*/
+SK_API sk_stroke_cap_t sk_paint_get_stroke_cap(const sk_paint_t*);
+/**
+ Set the paint's stroke cap type, controlling how the start and
+ end of stroked lines and paths are treated.
+*/
+SK_API void sk_paint_set_stroke_cap(sk_paint_t*, sk_stroke_cap_t);
+
+typedef enum {
+ MITER_SK_STROKE_JOIN,
+ ROUND_SK_STROKE_JOIN,
+ BEVEL_SK_STROKE_JOIN
+} sk_stroke_join_t;
+
+/**
+ Return the paint's stroke join type, specifies the treatment that
+ is applied to corners in paths and rectangles
+ */
+SK_API sk_stroke_join_t sk_paint_get_stroke_join(const sk_paint_t*);
+/**
+ Set the paint's stroke join type, specifies the treatment that
+ is applied to corners in paths and rectangles
+ */
+SK_API void sk_paint_set_stroke_join(sk_paint_t*, sk_stroke_join_t);
+
+/**
+ * Set the paint's shader to the specified parameter. This will automatically call unref() on
+ * any previous value, and call ref() on the new value.
+ */
+SK_API void sk_paint_set_shader(sk_paint_t*, sk_shader_t*);
+
+/**
+ * Set the paint's maskfilter to the specified parameter. This will automatically call unref() on
+ * any previous value, and call ref() on the new value.
+ */
+SK_API void sk_paint_set_maskfilter(sk_paint_t*, sk_maskfilter_t*);
+
+/**
+ * Set the paint's xfermode to the specified parameter.
+ */
+SK_API void sk_paint_set_xfermode_mode(sk_paint_t*, sk_xfermode_mode_t);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_path.h b/gfx/skia/skia/include/c/sk_path.h
new file mode 100644
index 0000000000..6b4e83d3b2
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_path.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_path_DEFINED
+#define sk_path_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+typedef enum {
+ CW_SK_PATH_DIRECTION,
+ CCW_SK_PATH_DIRECTION,
+} sk_path_direction_t;
+
+/** Create a new, empty path. */
+SK_API sk_path_t* sk_path_new();
+/** Release the memory used by a sk_path_t. */
+SK_API void sk_path_delete(sk_path_t*);
+
+/** Set the beginning of the next contour to the point (x,y). */
+SK_API void sk_path_move_to(sk_path_t*, float x, float y);
+/**
+ Add a line from the last point to the specified point (x,y). If no
+ sk_path_move_to() call has been made for this contour, the first
+ point is automatically set to (0,0).
+*/
+SK_API void sk_path_line_to(sk_path_t*, float x, float y);
+/**
+ Add a quadratic bezier from the last point, approaching control
+ point (x0,y0), and ending at (x1,y1). If no sk_path_move_to() call
+ has been made for this contour, the first point is automatically
+ set to (0,0).
+*/
+SK_API void sk_path_quad_to(sk_path_t*, float x0, float y0, float x1, float y1);
+/**
+ Add a conic curve from the last point, approaching control point
+ (x0,y01), and ending at (x1,y1) with weight w. If no
+ sk_path_move_to() call has been made for this contour, the first
+ point is automatically set to (0,0).
+*/
+SK_API void sk_path_conic_to(sk_path_t*, float x0, float y0, float x1, float y1, float w);
+/**
+ Add a cubic bezier from the last point, approaching control points
+ (x0,y0) and (x1,y1), and ending at (x2,y2). If no
+ sk_path_move_to() call has been made for this contour, the first
+ point is automatically set to (0,0).
+*/
+SK_API void sk_path_cubic_to(sk_path_t*,
+ float x0, float y0,
+ float x1, float y1,
+ float x2, float y2);
+/**
+ Close the current contour. If the current point is not equal to the
+ first point of the contour, a line segment is automatically added.
+*/
+SK_API void sk_path_close(sk_path_t*);
+
+/**
+ Add a closed rectangle contour to the path.
+*/
+SK_API void sk_path_add_rect(sk_path_t*, const sk_rect_t*, sk_path_direction_t);
+/**
+ Add a closed oval contour to the path
+*/
+SK_API void sk_path_add_oval(sk_path_t*, const sk_rect_t*, sk_path_direction_t);
+
+/**
+ * If the path is empty, return false and set the rect parameter to [0, 0, 0, 0].
+ * else return true and set the rect parameter to the bounds of the control-points
+ * of the path.
+ */
+SK_API bool sk_path_get_bounds(const sk_path_t*, sk_rect_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_picture.h b/gfx/skia/skia/include/c/sk_picture.h
new file mode 100644
index 0000000000..338b7d906a
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_picture.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_picture_DEFINED
+#define sk_picture_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Create a new sk_picture_recorder_t. Its resources should be
+ released with a call to sk_picture_recorder_delete().
+*/
+sk_picture_recorder_t* sk_picture_recorder_new();
+/**
+ Release the memory and other resources used by this
+ sk_picture_recorder_t.
+*/
+void sk_picture_recorder_delete(sk_picture_recorder_t*);
+
+/**
+ Returns the canvas that records the drawing commands
+
+ @param sk_rect_t* the cull rect used when recording this
+ picture. Any drawing the falls outside of this
+ rect is undefined, and may be drawn or it may not.
+*/
+sk_canvas_t* sk_picture_recorder_begin_recording(sk_picture_recorder_t*, const sk_rect_t*);
+/**
+ Signal that the caller is done recording. This invalidates the
+ canvas returned by begin_recording. Ownership of the sk_picture_t
+ is passed to the caller, who must call sk_picture_unref() when
+ they are done using it. The returned picture is immutable.
+*/
+sk_picture_t* sk_picture_recorder_end_recording(sk_picture_recorder_t*);
+
+/**
+ Increment the reference count on the given sk_picture_t. Must be
+ balanced by a call to sk_picture_unref().
+*/
+void sk_picture_ref(sk_picture_t*);
+/**
+ Decrement the reference count. If the reference count is 1 before
+ the decrement, then release both the memory holding the
+ sk_picture_t and any resouces it may be managing. New
+ sk_picture_t are created with a reference count of 1.
+*/
+void sk_picture_unref(sk_picture_t*);
+
+/**
+ Returns a non-zero value unique among all pictures.
+ */
+uint32_t sk_picture_get_unique_id(sk_picture_t*);
+
+/**
+ Return the cull rect specified when this picture was recorded.
+*/
+sk_rect_t sk_picture_get_bounds(sk_picture_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_shader.h b/gfx/skia/skia/include/c/sk_shader.h
new file mode 100644
index 0000000000..702cda7fd4
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_shader.h
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_shader_DEFINED
+#define sk_shader_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+void sk_shader_ref(sk_shader_t*);
+void sk_shader_unref(sk_shader_t*);
+
+typedef enum {
+ CLAMP_SK_SHADER_TILEMODE,
+ REPEAT_SK_SHADER_TILEMODE,
+ MIRROR_SK_SHADER_TILEMODE,
+} sk_shader_tilemode_t;
+
+/**
+ Returns a shader that generates a linear gradient between the two
+ specified points.
+
+ @param points The start and end points for the gradient.
+ @param colors The array[count] of colors, to be distributed between
+ the two points
+ @param colorPos May be NULL. array[count] of SkScalars, or NULL, of
+ the relative position of each corresponding color
+ in the colors array. If this is NULL, the the
+ colors are distributed evenly between the start
+ and end point. If this is not null, the values
+ must begin with 0, end with 1.0, and intermediate
+ values must be strictly increasing.
+ @param colorCount Must be >=2. The number of colors (and pos if not
+ NULL) entries.
+ @param mode The tiling mode
+*/
+sk_shader_t* sk_shader_new_linear_gradient(const sk_point_t points[2],
+ const sk_color_t colors[],
+ const float colorPos[],
+ int colorCount,
+ sk_shader_tilemode_t tileMode,
+ const sk_matrix_t* localMatrix);
+
+
+/**
+ Returns a shader that generates a radial gradient given the center
+ and radius.
+
+ @param center The center of the circle for this gradient
+ @param radius Must be positive. The radius of the circle for this
+ gradient
+ @param colors The array[count] of colors, to be distributed
+ between the center and edge of the circle
+ @param colorPos May be NULL. The array[count] of the relative
+ position of each corresponding color in the colors
+ array. If this is NULL, the the colors are
+ distributed evenly between the center and edge of
+ the circle. If this is not null, the values must
+ begin with 0, end with 1.0, and intermediate
+ values must be strictly increasing.
+ @param count Must be >= 2. The number of colors (and pos if not
+ NULL) entries
+ @param tileMode The tiling mode
+ @param localMatrix May be NULL
+*/
+sk_shader_t* sk_shader_new_radial_gradient(const sk_point_t* center,
+ float radius,
+ const sk_color_t colors[],
+ const float colorPos[],
+ int colorCount,
+ sk_shader_tilemode_t tileMode,
+ const sk_matrix_t* localMatrix);
+
+/**
+ Returns a shader that generates a sweep gradient given a center.
+
+ @param center The coordinates of the center of the sweep
+ @param colors The array[count] of colors, to be distributed around
+ the center.
+ @param colorPos May be NULL. The array[count] of the relative
+ position of each corresponding color in the colors
+ array. If this is NULL, the the colors are
+ distributed evenly between the center and edge of
+ the circle. If this is not null, the values must
+ begin with 0, end with 1.0, and intermediate
+ values must be strictly increasing.
+ @param colorCount Must be >= 2. The number of colors (and pos if
+ not NULL) entries
+ @param localMatrix May be NULL
+*/
+sk_shader_t* sk_shader_new_sweep_gradient(const sk_point_t* center,
+ const sk_color_t colors[],
+ const float colorPos[],
+ int colorCount,
+ const sk_matrix_t* localMatrix);
+
+/**
+ Returns a shader that generates a conical gradient given two circles, or
+ returns NULL if the inputs are invalid. The gradient interprets the
+ two circles according to the following HTML spec.
+ http://dev.w3.org/html5/2dcontext/#dom-context-2d-createradialgradient
+
+ Returns a shader that generates a sweep gradient given a center.
+
+ @param start, startRadius Defines the first circle.
+ @param end, endRadius Defines the first circle.
+ @param colors The array[count] of colors, to be distributed between
+ the two circles.
+ @param colorPos May be NULL. The array[count] of the relative
+ position of each corresponding color in the colors
+ array. If this is NULL, the the colors are
+ distributed evenly between the two circles. If
+ this is not null, the values must begin with 0,
+ end with 1.0, and intermediate values must be
+ strictly increasing.
+ @param colorCount Must be >= 2. The number of colors (and pos if
+ not NULL) entries
+ @param tileMode The tiling mode
+ @param localMatrix May be NULL
+
+*/
+sk_shader_t* sk_shader_new_two_point_conical_gradient(
+ const sk_point_t* start,
+ float startRadius,
+ const sk_point_t* end,
+ float endRadius,
+ const sk_color_t colors[],
+ const float colorPos[],
+ int colorCount,
+ sk_shader_tilemode_t tileMode,
+ const sk_matrix_t* localMatrix);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_surface.h b/gfx/skia/skia/include/c/sk_surface.h
new file mode 100644
index 0000000000..d634185eec
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_surface.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_surface_DEFINED
+#define sk_surface_DEFINED
+
+#include "sk_types.h"
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+/**
+ Return a new surface, with the memory for the pixels automatically
+ allocated. If the requested surface cannot be created, or the
+ request is not a supported configuration, NULL will be returned.
+
+ @param sk_imageinfo_t* Specify the width, height, color type, and
+ alpha type for the surface.
+
+ @param sk_surfaceprops_t* If not NULL, specify additional non-default
+ properties of the surface.
+*/
+SK_API sk_surface_t* sk_surface_new_raster(const sk_imageinfo_t*, const sk_surfaceprops_t*);
+
+/**
+ Create a new surface which will draw into the specified pixels
+ with the specified rowbytes. If the requested surface cannot be
+ created, or the request is not a supported configuration, NULL
+ will be returned.
+
+ @param sk_imageinfo_t* Specify the width, height, color type, and
+ alpha type for the surface.
+ @param void* pixels Specify the location in memory where the
+ destination pixels are. This memory must
+ outlast this surface.
+ @param size_t rowBytes Specify the difference, in bytes, between
+ each adjacent row. Should be at least
+ (width * sizeof(one pixel)).
+ @param sk_surfaceprops_t* If not NULL, specify additional non-default
+ properties of the surface.
+*/
+SK_API sk_surface_t* sk_surface_new_raster_direct(const sk_imageinfo_t*,
+ void* pixels, size_t rowBytes,
+ const sk_surfaceprops_t* props);
+
+/**
+ Decrement the reference count. If the reference count is 1 before
+ the decrement, then release both the memory holding the
+ sk_surface_t and any pixel memory it may be managing. New
+ sk_surface_t are created with a reference count of 1.
+*/
+SK_API void sk_surface_unref(sk_surface_t*);
+
+/**
+ * Return the canvas associated with this surface. Note: the canvas is owned by the surface,
+ * so the returned object is only valid while the owning surface is valid.
+ */
+SK_API sk_canvas_t* sk_surface_get_canvas(sk_surface_t*);
+
+/**
+ * Call sk_image_unref() when the returned image is no longer used.
+ */
+SK_API sk_image_t* sk_surface_new_image_snapshot(sk_surface_t*);
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/c/sk_types.h b/gfx/skia/skia/include/c/sk_types.h
new file mode 100644
index 0000000000..41dd2715b0
--- /dev/null
+++ b/gfx/skia/skia/include/c/sk_types.h
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
+// DO NOT USE -- FOR INTERNAL TESTING ONLY
+
+#ifndef sk_types_DEFINED
+#define sk_types_DEFINED
+
+#include
+#include
+
+#ifdef __cplusplus
+ #define SK_C_PLUS_PLUS_BEGIN_GUARD extern "C" {
+ #define SK_C_PLUS_PLUS_END_GUARD }
+#else
+ #include
+ #define SK_C_PLUS_PLUS_BEGIN_GUARD
+ #define SK_C_PLUS_PLUS_END_GUARD
+#endif
+
+#ifndef SK_API
+#define SK_API
+#endif
+
+///////////////////////////////////////////////////////////////////////////////////////
+
+SK_C_PLUS_PLUS_BEGIN_GUARD
+
+typedef uint32_t sk_color_t;
+
+/* This macro assumes all arguments are >=0 and <=255. */
+#define sk_color_set_argb(a, r, g, b) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
+#define sk_color_get_a(c) (((c) >> 24) & 0xFF)
+#define sk_color_get_r(c) (((c) >> 16) & 0xFF)
+#define sk_color_get_g(c) (((c) >> 8) & 0xFF)
+#define sk_color_get_b(c) (((c) >> 0) & 0xFF)
+
+typedef enum {
+ UNKNOWN_SK_COLORTYPE,
+ RGBA_8888_SK_COLORTYPE,
+ BGRA_8888_SK_COLORTYPE,
+ ALPHA_8_SK_COLORTYPE,
+} sk_colortype_t;
+
+typedef enum {
+ OPAQUE_SK_ALPHATYPE,
+ PREMUL_SK_ALPHATYPE,
+ UNPREMUL_SK_ALPHATYPE,
+} sk_alphatype_t;
+
+typedef enum {
+ INTERSECT_SK_CLIPTYPE,
+ DIFFERENCE_SK_CLIPTYPE,
+} sk_cliptype_t;
+
+typedef enum {
+ UNKNOWN_SK_PIXELGEOMETRY,
+ RGB_H_SK_PIXELGEOMETRY,
+ BGR_H_SK_PIXELGEOMETRY,
+ RGB_V_SK_PIXELGEOMETRY,
+ BGR_V_SK_PIXELGEOMETRY,
+} sk_pixelgeometry_t;
+
+/**
+ Return the default sk_colortype_t; this is operating-system dependent.
+*/
+SK_API sk_colortype_t sk_colortype_get_default_8888();
+
+typedef struct {
+ int32_t width;
+ int32_t height;
+ sk_colortype_t colorType;
+ sk_alphatype_t alphaType;
+} sk_imageinfo_t;
+
+typedef struct {
+ sk_pixelgeometry_t pixelGeometry;
+} sk_surfaceprops_t;
+
+typedef struct {
+ float x;
+ float y;
+} sk_point_t;
+
+typedef struct {
+ int32_t left;
+ int32_t top;
+ int32_t right;
+ int32_t bottom;
+} sk_irect_t;
+
+typedef struct {
+ float left;
+ float top;
+ float right;
+ float bottom;
+} sk_rect_t;
+
+typedef struct {
+ float mat[9];
+} sk_matrix_t;
+
+/**
+ A sk_canvas_t encapsulates all of the state about drawing into a
+ destination This includes a reference to the destination itself,
+ and a stack of matrix/clip values.
+*/
+typedef struct sk_canvas_t sk_canvas_t;
+/**
+ A sk_data_ holds an immutable data buffer.
+*/
+typedef struct sk_data_t sk_data_t;
+/**
+ A sk_image_t is an abstraction for drawing a rectagle of pixels.
+ The content of the image is always immutable, though the actual
+ storage may change, if for example that image can be re-created via
+ encoded data or other means.
+*/
+typedef struct sk_image_t sk_image_t;
+/**
+ A sk_maskfilter_t is an object that perform transformations on an
+ alpha-channel mask before drawing it; it may be installed into a
+ sk_paint_t. Each time a primitive is drawn, it is first
+ scan-converted into a alpha mask, which os handed to the
+ maskfilter, which may create a new mask is to render into the
+ destination.
+ */
+typedef struct sk_maskfilter_t sk_maskfilter_t;
+/**
+ A sk_paint_t holds the style and color information about how to
+ draw geometries, text and bitmaps.
+*/
+typedef struct sk_paint_t sk_paint_t;
+/**
+ A sk_path_t encapsulates compound (multiple contour) geometric
+ paths consisting of straight line segments, quadratic curves, and
+ cubic curves.
+*/
+typedef struct sk_path_t sk_path_t;
+/**
+ A sk_picture_t holds recorded canvas drawing commands to be played
+ back at a later time.
+*/
+typedef struct sk_picture_t sk_picture_t;
+/**
+ A sk_picture_recorder_t holds a sk_canvas_t that records commands
+ to create a sk_picture_t.
+*/
+typedef struct sk_picture_recorder_t sk_picture_recorder_t;
+/**
+ A sk_shader_t specifies the source color(s) for what is being drawn. If a
+ paint has no shader, then the paint's color is used. If the paint
+ has a shader, then the shader's color(s) are use instead, but they
+ are modulated by the paint's alpha.
+*/
+typedef struct sk_shader_t sk_shader_t;
+/**
+ A sk_surface_t holds the destination for drawing to a canvas. For
+ raster drawing, the destination is an array of pixels in memory.
+ For GPU drawing, the destination is a texture or a framebuffer.
+*/
+typedef struct sk_surface_t sk_surface_t;
+
+typedef enum {
+ CLEAR_SK_XFERMODE_MODE,
+ SRC_SK_XFERMODE_MODE,
+ DST_SK_XFERMODE_MODE,
+ SRCOVER_SK_XFERMODE_MODE,
+ DSTOVER_SK_XFERMODE_MODE,
+ SRCIN_SK_XFERMODE_MODE,
+ DSTIN_SK_XFERMODE_MODE,
+ SRCOUT_SK_XFERMODE_MODE,
+ DSTOUT_SK_XFERMODE_MODE,
+ SRCATOP_SK_XFERMODE_MODE,
+ DSTATOP_SK_XFERMODE_MODE,
+ XOR_SK_XFERMODE_MODE,
+ PLUS_SK_XFERMODE_MODE,
+ MODULATE_SK_XFERMODE_MODE,
+ SCREEN_SK_XFERMODE_MODE,
+ OVERLAY_SK_XFERMODE_MODE,
+ DARKEN_SK_XFERMODE_MODE,
+ LIGHTEN_SK_XFERMODE_MODE,
+ COLORDODGE_SK_XFERMODE_MODE,
+ COLORBURN_SK_XFERMODE_MODE,
+ HARDLIGHT_SK_XFERMODE_MODE,
+ SOFTLIGHT_SK_XFERMODE_MODE,
+ DIFFERENCE_SK_XFERMODE_MODE,
+ EXCLUSION_SK_XFERMODE_MODE,
+ MULTIPLY_SK_XFERMODE_MODE,
+ HUE_SK_XFERMODE_MODE,
+ SATURATION_SK_XFERMODE_MODE,
+ COLOR_SK_XFERMODE_MODE,
+ LUMINOSITY_SK_XFERMODE_MODE,
+} sk_xfermode_mode_t;
+
+//////////////////////////////////////////////////////////////////////////////////////////
+
+SK_C_PLUS_PLUS_END_GUARD
+
+#endif
diff --git a/gfx/skia/skia/include/codec/SkAndroidCodec.h b/gfx/skia/skia/include/codec/SkAndroidCodec.h
new file mode 100644
index 0000000000..f979886a43
--- /dev/null
+++ b/gfx/skia/skia/include/codec/SkAndroidCodec.h
@@ -0,0 +1,230 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkAndroidCodec_DEFINED
+#define SkAndroidCodec_DEFINED
+
+#include "SkCodec.h"
+#include "SkEncodedFormat.h"
+#include "SkStream.h"
+#include "SkTypes.h"
+
+/**
+ * Abstract interface defining image codec functionality that is necessary for
+ * Android.
+ */
+class SkAndroidCodec : SkNoncopyable {
+public:
+ /**
+ * If this stream represents an encoded image that we know how to decode,
+ * return an SkAndroidCodec that can decode it. Otherwise return NULL.
+ *
+ * The SkPngChunkReader handles unknown chunks in PNGs.
+ * See SkCodec.h for more details.
+ *
+ * If NULL is returned, the stream is deleted immediately. Otherwise, the
+ * SkCodec takes ownership of it, and will delete it when done with it.
+ */
+ static SkAndroidCodec* NewFromStream(SkStream*, SkPngChunkReader* = NULL);
+
+ /**
+ * If this data represents an encoded image that we know how to decode,
+ * return an SkAndroidCodec that can decode it. Otherwise return NULL.
+ *
+ * The SkPngChunkReader handles unknown chunks in PNGs.
+ * See SkCodec.h for more details.
+ *
+ * Will take a ref if it returns a codec, else will not affect the data.
+ */
+ static SkAndroidCodec* NewFromData(SkData*, SkPngChunkReader* = NULL);
+
+ virtual ~SkAndroidCodec() {}
+
+
+ const SkImageInfo& getInfo() const { return fInfo; }
+
+ /**
+ * Format of the encoded data.
+ */
+ SkEncodedFormat getEncodedFormat() const { return this->onGetEncodedFormat(); }
+
+ /**
+ * Returns the dimensions of the scaled output image, for an input
+ * sampleSize.
+ *
+ * When the sample size divides evenly into the original dimensions, the
+ * scaled output dimensions will simply be equal to the original
+ * dimensions divided by the sample size.
+ *
+ * When the sample size does not divide even into the original
+ * dimensions, the codec may round up or down, depending on what is most
+ * efficient to decode.
+ *
+ * Finally, the codec will always recommend a non-zero output, so the output
+ * dimension will always be one if the sampleSize is greater than the
+ * original dimension.
+ */
+ SkISize getSampledDimensions(int sampleSize) const;
+
+ /**
+ * Return (via desiredSubset) a subset which can decoded from this codec,
+ * or false if the input subset is invalid.
+ *
+ * @param desiredSubset in/out parameter
+ * As input, a desired subset of the original bounds
+ * (as specified by getInfo).
+ * As output, if true is returned, desiredSubset may
+ * have been modified to a subset which is
+ * supported. Although a particular change may have
+ * been made to desiredSubset to create something
+ * supported, it is possible other changes could
+ * result in a valid subset. If false is returned,
+ * desiredSubset's value is undefined.
+ * @return true If the input desiredSubset is valid.
+ * desiredSubset may be modified to a subset
+ * supported by the codec.
+ * false If desiredSubset is invalid (NULL or not fully
+ * contained within the image).
+ */
+ bool getSupportedSubset(SkIRect* desiredSubset) const;
+ // TODO: Rename SkCodec::getValidSubset() to getSupportedSubset()
+
+ /**
+ * Returns the dimensions of the scaled, partial output image, for an
+ * input sampleSize and subset.
+ *
+ * @param sampleSize Factor to scale down by.
+ * @param subset Must be a valid subset of the original image
+ * dimensions and a subset supported by SkAndroidCodec.
+ * getSubset() can be used to obtain a subset supported
+ * by SkAndroidCodec.
+ * @return Size of the scaled partial image. Or zero size
+ * if either of the inputs is invalid.
+ */
+ SkISize getSampledSubsetDimensions(int sampleSize, const SkIRect& subset) const;
+
+ /**
+ * Additional options to pass to getAndroidPixels().
+ */
+ // FIXME: It's a bit redundant to name these AndroidOptions when this class is already
+ // called SkAndroidCodec. On the other hand, it's may be a bit confusing to call
+ // these Options when SkCodec has a slightly different set of Options. Maybe these
+ // should be DecodeOptions or SamplingOptions?
+ struct AndroidOptions {
+ AndroidOptions()
+ : fZeroInitialized(SkCodec::kNo_ZeroInitialized)
+ , fSubset(nullptr)
+ , fColorPtr(nullptr)
+ , fColorCount(nullptr)
+ , fSampleSize(1)
+ {}
+
+ /**
+ * Indicates is destination pixel memory is zero initialized.
+ */
+ SkCodec::ZeroInitialized fZeroInitialized;
+
+ /**
+ * If not NULL, represents a subset of the original image to decode.
+ *
+ * Must be within the bounds returned by getInfo().
+ *
+ * If the EncodedFormat is kWEBP_SkEncodedFormat, the top and left
+ * values must be even.
+ */
+ SkIRect* fSubset;
+
+ /**
+ * If the client has requested a decode to kIndex8_SkColorType
+ * (specified in the SkImageInfo), then the caller must provide
+ * storage for up to 256 SkPMColor values in fColorPtr. On success,
+ * the codec must copy N colors into that storage, (where N is the
+ * logical number of table entries) and set fColorCount to N.
+ *
+ * If the client does not request kIndex8_SkColorType, then the last
+ * two parameters may be NULL. If fColorCount is not null, it will be
+ * set to 0.
+ */
+ SkPMColor* fColorPtr;
+ int* fColorCount;
+
+ /**
+ * The client may provide an integer downscale factor for the decode.
+ * The codec may implement this downscaling by sampling or another
+ * method if it is more efficient.
+ */
+ int fSampleSize;
+ };
+
+ /**
+ * Decode into the given pixels, a block of memory of size at
+ * least (info.fHeight - 1) * rowBytes + (info.fWidth *
+ * bytesPerPixel)
+ *
+ * Repeated calls to this function should give the same results,
+ * allowing the PixelRef to be immutable.
+ *
+ * @param info A description of the format (config, size)
+ * expected by the caller. This can simply be identical
+ * to the info returned by getInfo().
+ *
+ * This contract also allows the caller to specify
+ * different output-configs, which the implementation can
+ * decide to support or not.
+ *
+ * A size that does not match getInfo() implies a request
+ * to scale or subset. If the codec cannot perform this
+ * scaling or subsetting, it will return an error code.
+ *
+ * If info is kIndex8_SkColorType, then the caller must provide storage for up to 256
+ * SkPMColor values in options->fColorPtr. On success the codec must copy N colors into
+ * that storage, (where N is the logical number of table entries) and set
+ * options->fColorCount to N.
+ *
+ * If info is not kIndex8_SkColorType, options->fColorPtr and options->fColorCount may
+ * be nullptr.
+ *
+ * The AndroidOptions object is also used to specify any requested scaling or subsetting
+ * using options->fSampleSize and options->fSubset.
+ *
+ * @return Result kSuccess, or another value explaining the type of failure.
+ */
+ // FIXME: It's a bit redundant to name this getAndroidPixels() when this class is already
+ // called SkAndroidCodec. On the other hand, it's may be a bit confusing to call
+ // this getPixels() when it is a slightly different API than SkCodec's getPixels().
+ // Maybe this should be decode() or decodeSubset()?
+ SkCodec::Result getAndroidPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
+ const AndroidOptions* options);
+
+ /**
+ * Simplified version of getAndroidPixels() where we supply the default AndroidOptions.
+ *
+ * This will return an error if the info is kIndex_8_SkColorType and also will not perform
+ * any scaling or subsetting.
+ */
+ SkCodec::Result getAndroidPixels(const SkImageInfo& info, void* pixels, size_t rowBytes);
+
+protected:
+
+ SkAndroidCodec(const SkImageInfo&);
+
+ virtual SkEncodedFormat onGetEncodedFormat() const = 0;
+
+ virtual SkISize onGetSampledDimensions(int sampleSize) const = 0;
+
+ virtual bool onGetSupportedSubset(SkIRect* desiredSubset) const = 0;
+
+ virtual SkCodec::Result onGetAndroidPixels(const SkImageInfo& info, void* pixels,
+ size_t rowBytes, const AndroidOptions& options) = 0;
+
+private:
+
+ // This will always be a reference to the info that is contained by the
+ // embedded SkCodec.
+ const SkImageInfo& fInfo;
+};
+#endif // SkAndroidCodec_DEFINED
diff --git a/gfx/skia/skia/include/codec/SkCodec.h b/gfx/skia/skia/include/codec/SkCodec.h
new file mode 100644
index 0000000000..9f28af010e
--- /dev/null
+++ b/gfx/skia/skia/include/codec/SkCodec.h
@@ -0,0 +1,614 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkCodec_DEFINED
+#define SkCodec_DEFINED
+
+#include "../private/SkTemplates.h"
+#include "SkColor.h"
+#include "SkEncodedFormat.h"
+#include "SkImageInfo.h"
+#include "SkSize.h"
+#include "SkStream.h"
+#include "SkTypes.h"
+
+class SkData;
+class SkPngChunkReader;
+class SkSampler;
+
+/**
+ * Abstraction layer directly on top of an image codec.
+ */
+class SkCodec : SkNoncopyable {
+public:
+ /**
+ * If this stream represents an encoded image that we know how to decode,
+ * return an SkCodec that can decode it. Otherwise return NULL.
+ *
+ * If the SkPngChunkReader is not NULL then:
+ * If the image is not a PNG, the SkPngChunkReader will be ignored.
+ * If the image is a PNG, the SkPngChunkReader will be reffed.
+ * If the PNG has unknown chunks, the SkPngChunkReader will be used
+ * to handle these chunks. SkPngChunkReader will be called to read
+ * any unknown chunk at any point during the creation of the codec
+ * or the decode. Note that if SkPngChunkReader fails to read a
+ * chunk, this could result in a failure to create the codec or a
+ * failure to decode the image.
+ * If the PNG does not contain unknown chunks, the SkPngChunkReader
+ * will not be used or modified.
+ *
+ * If NULL is returned, the stream is deleted immediately. Otherwise, the
+ * SkCodec takes ownership of it, and will delete it when done with it.
+ */
+ static SkCodec* NewFromStream(SkStream*, SkPngChunkReader* = NULL);
+
+ /**
+ * If this data represents an encoded image that we know how to decode,
+ * return an SkCodec that can decode it. Otherwise return NULL.
+ *
+ * If the SkPngChunkReader is not NULL then:
+ * If the image is not a PNG, the SkPngChunkReader will be ignored.
+ * If the image is a PNG, the SkPngChunkReader will be reffed.
+ * If the PNG has unknown chunks, the SkPngChunkReader will be used
+ * to handle these chunks. SkPngChunkReader will be called to read
+ * any unknown chunk at any point during the creation of the codec
+ * or the decode. Note that if SkPngChunkReader fails to read a
+ * chunk, this could result in a failure to create the codec or a
+ * failure to decode the image.
+ * If the PNG does not contain unknown chunks, the SkPngChunkReader
+ * will not be used or modified.
+ *
+ * Will take a ref if it returns a codec, else will not affect the data.
+ */
+ static SkCodec* NewFromData(SkData*, SkPngChunkReader* = NULL);
+
+ virtual ~SkCodec();
+
+ /**
+ * Return the ImageInfo associated with this codec.
+ */
+ const SkImageInfo& getInfo() const { return fSrcInfo; }
+
+ /**
+ * Return a size that approximately supports the desired scale factor.
+ * The codec may not be able to scale efficiently to the exact scale
+ * factor requested, so return a size that approximates that scale.
+ * The returned value is the codec's suggestion for the closest valid
+ * scale that it can natively support
+ */
+ SkISize getScaledDimensions(float desiredScale) const {
+ // Negative and zero scales are errors.
+ SkASSERT(desiredScale > 0.0f);
+ if (desiredScale <= 0.0f) {
+ return SkISize::Make(0, 0);
+ }
+
+ // Upscaling is not supported. Return the original size if the client
+ // requests an upscale.
+ if (desiredScale >= 1.0f) {
+ return this->getInfo().dimensions();
+ }
+ return this->onGetScaledDimensions(desiredScale);
+ }
+
+ /**
+ * Return (via desiredSubset) a subset which can decoded from this codec,
+ * or false if this codec cannot decode subsets or anything similar to
+ * desiredSubset.
+ *
+ * @param desiredSubset In/out parameter. As input, a desired subset of
+ * the original bounds (as specified by getInfo). If true is returned,
+ * desiredSubset may have been modified to a subset which is
+ * supported. Although a particular change may have been made to
+ * desiredSubset to create something supported, it is possible other
+ * changes could result in a valid subset.
+ * If false is returned, desiredSubset's value is undefined.
+ * @return true if this codec supports decoding desiredSubset (as
+ * returned, potentially modified)
+ */
+ bool getValidSubset(SkIRect* desiredSubset) const {
+ return this->onGetValidSubset(desiredSubset);
+ }
+
+ /**
+ * Format of the encoded data.
+ */
+ SkEncodedFormat getEncodedFormat() const { return this->onGetEncodedFormat(); }
+
+ /**
+ * Used to describe the result of a call to getPixels().
+ *
+ * Result is the union of possible results from subclasses.
+ */
+ enum Result {
+ /**
+ * General return value for success.
+ */
+ kSuccess,
+ /**
+ * The input is incomplete. A partial image was generated.
+ */
+ kIncompleteInput,
+ /**
+ * The generator cannot convert to match the request, ignoring
+ * dimensions.
+ */
+ kInvalidConversion,
+ /**
+ * The generator cannot scale to requested size.
+ */
+ kInvalidScale,
+ /**
+ * Parameters (besides info) are invalid. e.g. NULL pixels, rowBytes
+ * too small, etc.
+ */
+ kInvalidParameters,
+ /**
+ * The input did not contain a valid image.
+ */
+ kInvalidInput,
+ /**
+ * Fulfilling this request requires rewinding the input, which is not
+ * supported for this input.
+ */
+ kCouldNotRewind,
+ /**
+ * This method is not implemented by this codec.
+ * FIXME: Perhaps this should be kUnsupported?
+ */
+ kUnimplemented,
+ };
+
+ /**
+ * Whether or not the memory passed to getPixels is zero initialized.
+ */
+ enum ZeroInitialized {
+ /**
+ * The memory passed to getPixels is zero initialized. The SkCodec
+ * may take advantage of this by skipping writing zeroes.
+ */
+ kYes_ZeroInitialized,
+ /**
+ * The memory passed to getPixels has not been initialized to zero,
+ * so the SkCodec must write all zeroes to memory.
+ *
+ * This is the default. It will be used if no Options struct is used.
+ */
+ kNo_ZeroInitialized,
+ };
+
+ /**
+ * Additional options to pass to getPixels.
+ */
+ struct Options {
+ Options()
+ : fZeroInitialized(kNo_ZeroInitialized)
+ , fSubset(NULL)
+ {}
+
+ ZeroInitialized fZeroInitialized;
+ /**
+ * If not NULL, represents a subset of the original image to decode.
+ * Must be within the bounds returned by getInfo().
+ * If the EncodedFormat is kWEBP_SkEncodedFormat (the only one which
+ * currently supports subsets), the top and left values must be even.
+ *
+ * In getPixels, we will attempt to decode the exact rectangular
+ * subset specified by fSubset.
+ *
+ * In a scanline decode, it does not make sense to specify a subset
+ * top or subset height, since the client already controls which rows
+ * to get and which rows to skip. During scanline decodes, we will
+ * require that the subset top be zero and the subset height be equal
+ * to the full height. We will, however, use the values of
+ * subset left and subset width to decode partial scanlines on calls
+ * to getScanlines().
+ */
+ SkIRect* fSubset;
+ };
+
+ /**
+ * Decode into the given pixels, a block of memory of size at
+ * least (info.fHeight - 1) * rowBytes + (info.fWidth *
+ * bytesPerPixel)
+ *
+ * Repeated calls to this function should give the same results,
+ * allowing the PixelRef to be immutable.
+ *
+ * @param info A description of the format (config, size)
+ * expected by the caller. This can simply be identical
+ * to the info returned by getInfo().
+ *
+ * This contract also allows the caller to specify
+ * different output-configs, which the implementation can
+ * decide to support or not.
+ *
+ * A size that does not match getInfo() implies a request
+ * to scale. If the generator cannot perform this scale,
+ * it will return kInvalidScale.
+ *
+ * If info is kIndex8_SkColorType, then the caller must provide storage for up to 256
+ * SkPMColor values in ctable. On success the generator must copy N colors into that storage,
+ * (where N is the logical number of table entries) and set ctableCount to N.
+ *
+ * If info is not kIndex8_SkColorType, then the last two parameters may be NULL. If ctableCount
+ * is not null, it will be set to 0.
+ *
+ * If a scanline decode is in progress, scanline mode will end, requiring the client to call
+ * startScanlineDecode() in order to return to decoding scanlines.
+ *
+ * @return Result kSuccess, or another value explaining the type of failure.
+ */
+ Result getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options*,
+ SkPMColor ctable[], int* ctableCount);
+
+ /**
+ * Simplified version of getPixels() that asserts that info is NOT kIndex8_SkColorType and
+ * uses the default Options.
+ */
+ Result getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes);
+
+ /**
+ * Some images may initially report that they have alpha due to the format
+ * of the encoded data, but then never use any colors which have alpha
+ * less than 100%. This function can be called *after* decoding to
+ * determine if such an image truly had alpha. Calling it before decoding
+ * is undefined.
+ * FIXME: see skbug.com/3582.
+ */
+ bool reallyHasAlpha() const {
+ return this->onReallyHasAlpha();
+ }
+
+ /**
+ * The remaining functions revolve around decoding scanlines.
+ */
+
+ /**
+ * Prepare for a scanline decode with the specified options.
+ *
+ * After this call, this class will be ready to decode the first scanline.
+ *
+ * This must be called in order to call getScanlines or skipScanlines.
+ *
+ * This may require rewinding the stream.
+ *
+ * Not all SkCodecs support this.
+ *
+ * @param dstInfo Info of the destination. If the dimensions do not match
+ * those of getInfo, this implies a scale.
+ * @param options Contains decoding options, including if memory is zero
+ * initialized.
+ * @param ctable A pointer to a color table. When dstInfo.colorType() is
+ * kIndex8, this should be non-NULL and have enough storage for 256
+ * colors. The color table will be populated after decoding the palette.
+ * @param ctableCount A pointer to the size of the color table. When
+ * dstInfo.colorType() is kIndex8, this should be non-NULL. It will
+ * be modified to the true size of the color table (<= 256) after
+ * decoding the palette.
+ * @return Enum representing success or reason for failure.
+ */
+ Result startScanlineDecode(const SkImageInfo& dstInfo, const SkCodec::Options* options,
+ SkPMColor ctable[], int* ctableCount);
+
+ /**
+ * Simplified version of startScanlineDecode() that asserts that info is NOT
+ * kIndex8_SkColorType and uses the default Options.
+ */
+ Result startScanlineDecode(const SkImageInfo& dstInfo);
+
+ /**
+ * Write the next countLines scanlines into dst.
+ *
+ * Not valid to call before calling startScanlineDecode().
+ *
+ * @param dst Must be non-null, and large enough to hold countLines
+ * scanlines of size rowBytes.
+ * @param countLines Number of lines to write.
+ * @param rowBytes Number of bytes per row. Must be large enough to hold
+ * a scanline based on the SkImageInfo used to create this object.
+ * @return the number of lines successfully decoded. If this value is
+ * less than countLines, this will fill the remaining lines with a
+ * default value.
+ */
+ int getScanlines(void* dst, int countLines, size_t rowBytes);
+
+ /**
+ * Skip count scanlines.
+ *
+ * Not valid to call before calling startScanlineDecode().
+ *
+ * The default version just calls onGetScanlines and discards the dst.
+ * NOTE: If skipped lines are the only lines with alpha, this default
+ * will make reallyHasAlpha return true, when it could have returned
+ * false.
+ *
+ * @return true if the scanlines were successfully skipped
+ * false on failure, possible reasons for failure include:
+ * An incomplete input image stream.
+ * Calling this function before calling startScanlineDecode().
+ * If countLines is less than zero or so large that it moves
+ * the current scanline past the end of the image.
+ */
+ bool skipScanlines(int countLines);
+
+ /**
+ * The order in which rows are output from the scanline decoder is not the
+ * same for all variations of all image types. This explains the possible
+ * output row orderings.
+ */
+ enum SkScanlineOrder {
+ /*
+ * By far the most common, this indicates that the image can be decoded
+ * reliably using the scanline decoder, and that rows will be output in
+ * the logical order.
+ */
+ kTopDown_SkScanlineOrder,
+
+ /*
+ * This indicates that the scanline decoder reliably outputs rows, but
+ * they will be returned in reverse order. If the scanline format is
+ * kBottomUp, the nextScanline() API can be used to determine the actual
+ * y-coordinate of the next output row, but the client is not forced
+ * to take advantage of this, given that it's not too tough to keep
+ * track independently.
+ *
+ * For full image decodes, it is safe to get all of the scanlines at
+ * once, since the decoder will handle inverting the rows as it
+ * decodes.
+ *
+ * For subset decodes and sampling, it is simplest to get and skip
+ * scanlines one at a time, using the nextScanline() API. It is
+ * possible to ask for larger chunks at a time, but this should be used
+ * with caution. As with full image decodes, the decoder will handle
+ * inverting the requested rows, but rows will still be delivered
+ * starting from the bottom of the image.
+ *
+ * Upside down bmps are an example.
+ */
+ kBottomUp_SkScanlineOrder,
+
+ /*
+ * This indicates that the scanline decoder reliably outputs rows, but
+ * they will not be in logical order. If the scanline format is
+ * kOutOfOrder, the nextScanline() API should be used to determine the
+ * actual y-coordinate of the next output row.
+ *
+ * For this scanline ordering, it is advisable to get and skip
+ * scanlines one at a time.
+ *
+ * Interlaced gifs are an example.
+ */
+ kOutOfOrder_SkScanlineOrder,
+
+ /*
+ * Indicates that the entire image must be decoded in order to output
+ * any amount of scanlines. In this case, it is a REALLY BAD IDEA to
+ * request scanlines 1-by-1 or in small chunks. The client should
+ * determine which scanlines are needed and ask for all of them in
+ * a single call to getScanlines().
+ *
+ * Interlaced pngs are an example.
+ */
+ kNone_SkScanlineOrder,
+ };
+
+ /**
+ * An enum representing the order in which scanlines will be returned by
+ * the scanline decoder.
+ */
+ SkScanlineOrder getScanlineOrder() const { return this->onGetScanlineOrder(); }
+
+ /**
+ * Returns the y-coordinate of the next row to be returned by the scanline
+ * decoder.
+ *
+ * This will equal fCurrScanline, except in the case of strangely
+ * encoded image types (bottom-up bmps, interlaced gifs).
+ *
+ * Results are undefined when not in scanline decoding mode.
+ */
+ int nextScanline() const { return this->outputScanline(fCurrScanline); }
+
+ /**
+ * Returns the output y-coordinate of the row that corresponds to an input
+ * y-coordinate. The input y-coordinate represents where the scanline
+ * is located in the encoded data.
+ *
+ * This will equal inputScanline, except in the case of strangely
+ * encoded image types (bottom-up bmps, interlaced gifs).
+ */
+ int outputScanline(int inputScanline) const;
+
+protected:
+ SkCodec(const SkImageInfo&, SkStream*);
+
+ virtual SkISize onGetScaledDimensions(float /* desiredScale */) const {
+ // By default, scaling is not supported.
+ return this->getInfo().dimensions();
+ }
+
+ // FIXME: What to do about subsets??
+ /**
+ * Subclasses should override if they support dimensions other than the
+ * srcInfo's.
+ */
+ virtual bool onDimensionsSupported(const SkISize&) {
+ return false;
+ }
+
+ virtual SkEncodedFormat onGetEncodedFormat() const = 0;
+
+ /**
+ * @param rowsDecoded When the encoded image stream is incomplete, this function
+ * will return kIncompleteInput and rowsDecoded will be set to
+ * the number of scanlines that were successfully decoded.
+ * This will allow getPixels() to fill the uninitialized memory.
+ */
+ virtual Result onGetPixels(const SkImageInfo& info,
+ void* pixels, size_t rowBytes, const Options&,
+ SkPMColor ctable[], int* ctableCount,
+ int* rowsDecoded) = 0;
+
+ virtual bool onGetValidSubset(SkIRect* /* desiredSubset */) const {
+ // By default, subsets are not supported.
+ return false;
+ }
+
+ virtual bool onReallyHasAlpha() const { return false; }
+
+ /**
+ * If the stream was previously read, attempt to rewind.
+ *
+ * If the stream needed to be rewound, call onRewind.
+ * @returns true if the codec is at the right position and can be used.
+ * false if there was a failure to rewind.
+ *
+ * This is called by getPixels() and start(). Subclasses may call if they
+ * need to rewind at another time.
+ */
+ bool SK_WARN_UNUSED_RESULT rewindIfNeeded();
+
+ /**
+ * Called by rewindIfNeeded, if the stream needed to be rewound.
+ *
+ * Subclasses should do any set up needed after a rewind.
+ */
+ virtual bool onRewind() {
+ return true;
+ }
+
+ /**
+ * On an incomplete input, getPixels() and getScanlines() will fill any uninitialized
+ * scanlines. This allows the subclass to indicate what value to fill with.
+ *
+ * @param colorType Destination color type.
+ * @param alphaType Destination alpha type.
+ * @return The value with which to fill uninitialized pixels.
+ *
+ * Note that we can interpret the return value as an SkPMColor, a 16-bit 565 color,
+ * an 8-bit gray color, or an 8-bit index into a color table, depending on the color
+ * type.
+ */
+ uint32_t getFillValue(SkColorType colorType, SkAlphaType alphaType) const {
+ return this->onGetFillValue(colorType, alphaType);
+ }
+
+ /**
+ * Some subclasses will override this function, but this is a useful default for the color
+ * types that we support. Note that for color types that do not use the full 32-bits,
+ * we will simply take the low bits of the fill value.
+ *
+ * kN32_SkColorType: Transparent or Black
+ * kRGB_565_SkColorType: Black
+ * kGray_8_SkColorType: Black
+ * kIndex_8_SkColorType: First color in color table
+ */
+ virtual uint32_t onGetFillValue(SkColorType /*colorType*/, SkAlphaType alphaType) const {
+ return kOpaque_SkAlphaType == alphaType ? SK_ColorBLACK : SK_ColorTRANSPARENT;
+ }
+
+ /**
+ * Get method for the input stream
+ */
+ SkStream* stream() {
+ return fStream.get();
+ }
+
+ /**
+ * The remaining functions revolve around decoding scanlines.
+ */
+
+ /**
+ * Most images types will be kTopDown and will not need to override this function.
+ */
+ virtual SkScanlineOrder onGetScanlineOrder() const { return kTopDown_SkScanlineOrder; }
+
+ /**
+ * Update the next scanline. Used by interlaced png.
+ */
+ void updateNextScanline(int newY) { fCurrScanline = newY; }
+
+ const SkImageInfo& dstInfo() const { return fDstInfo; }
+
+ const SkCodec::Options& options() const { return fOptions; }
+
+ virtual int onOutputScanline(int inputScanline) const;
+
+private:
+ const SkImageInfo fSrcInfo;
+ SkAutoTDelete fStream;
+ bool fNeedsRewind;
+ // These fields are only meaningful during scanline decodes.
+ SkImageInfo fDstInfo;
+ SkCodec::Options fOptions;
+ int fCurrScanline;
+
+ /**
+ * Return whether these dimensions are supported as a scale.
+ *
+ * The codec may choose to cache the information about scale and subset.
+ * Either way, the same information will be passed to onGetPixels/onStart
+ * on success.
+ *
+ * This must return true for a size returned from getScaledDimensions.
+ */
+ bool dimensionsSupported(const SkISize& dim) {
+ return dim == fSrcInfo.dimensions() || this->onDimensionsSupported(dim);
+ }
+
+ // Methods for scanline decoding.
+ virtual SkCodec::Result onStartScanlineDecode(const SkImageInfo& /*dstInfo*/,
+ const SkCodec::Options& /*options*/, SkPMColor* /*ctable*/, int* /*ctableCount*/) {
+ return kUnimplemented;
+ }
+
+ // Naive default version just calls onGetScanlines on temp memory.
+ virtual bool onSkipScanlines(int countLines) {
+ // FIXME (msarett): Make this a pure virtual and always override this.
+ SkAutoMalloc storage(fDstInfo.minRowBytes());
+
+ // Note that we pass 0 to rowBytes so we continue to use the same memory.
+ // Also note that while getScanlines checks that rowBytes is big enough,
+ // onGetScanlines bypasses that check.
+ // Calling the virtual method also means we do not double count
+ // countLines.
+ return countLines == this->onGetScanlines(storage.get(), countLines, 0);
+ }
+
+ virtual int onGetScanlines(void* /*dst*/, int /*countLines*/, size_t /*rowBytes*/) { return 0; }
+
+ /**
+ * On an incomplete decode, getPixels() and getScanlines() will call this function
+ * to fill any uinitialized memory.
+ *
+ * @param dstInfo Contains the destination color type
+ * Contains the destination alpha type
+ * Contains the destination width
+ * The height stored in this info is unused
+ * @param dst Pointer to the start of destination pixel memory
+ * @param rowBytes Stride length in destination pixel memory
+ * @param zeroInit Indicates if memory is zero initialized
+ * @param linesRequested Number of lines that the client requested
+ * @param linesDecoded Number of lines that were successfully decoded
+ */
+ void fillIncompleteImage(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
+ ZeroInitialized zeroInit, int linesRequested, int linesDecoded);
+
+ /**
+ * Return an object which will allow forcing scanline decodes to sample in X.
+ *
+ * May create a sampler, if one is not currently being used. Otherwise, does
+ * not affect ownership.
+ *
+ * Only valid during scanline decoding.
+ */
+ virtual SkSampler* getSampler(bool /*createIfNecessary*/) { return nullptr; }
+
+ friend class SkSampledCodec;
+};
+#endif // SkCodec_DEFINED
diff --git a/gfx/skia/skia/include/codec/SkEncodedFormat.h b/gfx/skia/skia/include/codec/SkEncodedFormat.h
new file mode 100644
index 0000000000..003159a8de
--- /dev/null
+++ b/gfx/skia/skia/include/codec/SkEncodedFormat.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkEncodedFormat_DEFINED
+#define SkEncodedFormat_DEFINED
+
+/**
+ * Enum describing format of encoded data.
+ */
+enum SkEncodedFormat {
+ kUnknown_SkEncodedFormat,
+ kBMP_SkEncodedFormat,
+ kGIF_SkEncodedFormat,
+ kICO_SkEncodedFormat,
+ kJPEG_SkEncodedFormat,
+ kPNG_SkEncodedFormat,
+ kWBMP_SkEncodedFormat,
+ kWEBP_SkEncodedFormat,
+ kPKM_SkEncodedFormat,
+ kKTX_SkEncodedFormat,
+ kASTC_SkEncodedFormat,
+};
+#endif // SkEncodedFormat_DEFINED
diff --git a/gfx/skia/skia/include/config/SkUserConfig.h b/gfx/skia/skia/include/config/SkUserConfig.h
index 3d21b4c689..f1a4959cad 100644
--- a/gfx/skia/skia/include/config/SkUserConfig.h
+++ b/gfx/skia/skia/include/config/SkUserConfig.h
@@ -58,13 +58,6 @@
//#define SK_DEBUG_GLYPH_CACHE
//#define SK_DEBUG_PATH
-/* To assist debugging, Skia provides an instance counting utility in
- include/core/SkInstCount.h. This flag turns on and off that utility to
- allow instance count tracking in either debug or release builds. By
- default it is enabled in debug but disabled in release.
- */
-#define SK_ENABLE_INST_COUNT 0
-
/* If, in debugging mode, Skia needs to stop (presumably to invoke a debugger)
it will call SK_CRASH(). If this is not defined it, it is defined in
SkPostConfig.h to write to an illegal address
@@ -107,14 +100,6 @@
*/
//#define SK_DEFAULT_IMAGE_CACHE_LIMIT (1024 * 1024)
-/* If zlib is available and you want to support the flate compression
- algorithm (used in PDF generation), define SK_ZLIB_INCLUDE to be the
- include path. Alternatively, define SK_SYSTEM_ZLIB to use the system zlib
- library specified as "#include ".
- */
-//#define SK_ZLIB_INCLUDE
-//#define SK_SYSTEM_ZLIB
-
/* Define this to allow PDF scalars above 32k. The PDF/A spec doesn't allow
them, but modern PDF interpreters should handle them just fine.
*/
@@ -139,17 +124,15 @@
//#define SK_SUPPORT_UNITTEST
#endif
-/* If your system embeds skia and has complex event logging, define this
- symbol to name a file that maps the following macros to your system's
- equivalents:
- SK_TRACE_EVENT0(event)
- SK_TRACE_EVENT1(event, name1, value1)
- SK_TRACE_EVENT2(event, name1, value1, name2, value2)
- src/utils/SkDebugTrace.h has a trivial implementation that writes to
- the debug output stream. If SK_USER_TRACE_INCLUDE_FILE is not defined,
- SkTrace.h will define the above three macros to do nothing.
-*/
-//#undef SK_USER_TRACE_INCLUDE_FILE
+/* Change the ordering to work in X windows.
+ */
+//#ifdef SK_SAMPLES_FOR_X
+// #define SK_R32_SHIFT 16
+// #define SK_G32_SHIFT 8
+// #define SK_B32_SHIFT 0
+// #define SK_A32_SHIFT 24
+//#endif
+
/* Determines whether to build code that supports the GPU backend. Some classes
that are not GPU-specific, such as SkShader subclasses, have optional code
@@ -161,40 +144,14 @@
//#define SK_SUPPORT_GPU 1
-/* The PDF generation code uses Path Ops to generate inverse fills and complex
- * clipping paths, but at this time, Path Ops is not release ready yet. So,
- * the code is hidden behind this #define guard. If you are feeling adventurous
- * and want the latest and greatest PDF generation code, uncomment the #define.
+/* The PDF generation code uses Path Ops to handle complex clipping paths,
+ * but at this time, Path Ops is not release ready yet. So, the code is
+ * hidden behind this #define guard. If you are feeling adventurous and
+ * want the latest and greatest PDF generation code, uncomment the #define.
* When Path Ops is release ready, the define guards and this user config
* define should be removed entirely.
*/
-//#define SK_PDF_USE_PATHOPS
-
-/* Skia uses these defines as the target of include preprocessor directives.
- * The header files pointed to by these defines provide declarations and
- * possibly inline implementations of threading primitives.
- *
- * See SkThread.h for documentation on what these includes must contain.
- */
-//#define SK_ATOMICS_PLATFORM_H "SkAtomics_xxx.h"
-//#define SK_MUTEX_PLATFORM_H "SkMutex_xxx.h"
-#if defined(_MSC_VER)
-# define SK_ATOMICS_PLATFORM_H "../../src/ports/SkAtomics_win.h"
-#else
-# define SK_ATOMICS_PLATFORM_H "../../src/ports/SkAtomics_sync.h"
-#endif
-
-#if defined(_WIN32)
-# define SK_MUTEX_PLATFORM_H "../../src/ports/SkMutex_win.h"
-#else
-# define SK_MUTEX_PLATFORM_H "../../src/ports/SkMutex_pthread.h"
-#endif
-
-#if defined(SK_CPU_ARM32) || defined(SK_CPU_ARM64)
-# define SK_BARRIERS_PLATFORM_H "../../src/ports/SkBarriers_arm.h"
-#else
-# define SK_BARRIERS_PLATFORM_H "../../src/ports/SkBarriers_x86.h"
-#endif
+//#define SK_PDF_USE_PATHOPS_CLIPPING
// On all platforms we have this byte order
#define SK_A32_SHIFT 24
@@ -205,8 +162,21 @@
#define SK_ALLOW_STATIC_GLOBAL_INITIALIZERS 0
#define SK_SUPPORT_LEGACY_GETDEVICE
+
#define SK_IGNORE_ETC1_SUPPORT
#define SK_RASTERIZE_EVEN_ROUNDING
+#define GR_GL_PER_GL_FUNC_CALLBACK 1
+
+#define MOZ_SKIA 1
+
+#ifndef MOZ_IMPLICIT
+# ifdef MOZ_CLANG_PLUGIN
+# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit")))
+# else
+# define MOZ_IMPLICIT
+# endif
+#endif
+
#endif
diff --git a/gfx/skia/skia/include/core/SkAdvancedTypefaceMetrics.h b/gfx/skia/skia/include/core/SkAdvancedTypefaceMetrics.h
deleted file mode 100644
index 11926888f5..0000000000
--- a/gfx/skia/skia/include/core/SkAdvancedTypefaceMetrics.h
+++ /dev/null
@@ -1,162 +0,0 @@
-
-/*
- * Copyright 2011 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkAdvancedTypefaceMetrics_DEFINED
-#define SkAdvancedTypefaceMetrics_DEFINED
-
-#include "SkRect.h"
-#include "SkRefCnt.h"
-#include "SkString.h"
-#include "SkTDArray.h"
-#include "SkTemplates.h"
-
-/** \class SkAdvancedTypefaceMetrics
-
- The SkAdvancedTypefaceMetrics class is used by the PDF backend to correctly
- embed typefaces. This class is filled in with information about a given
- typeface by the SkFontHost class.
-*/
-
-class SkAdvancedTypefaceMetrics : public SkRefCnt {
-public:
- SK_DECLARE_INST_COUNT(SkAdvancedTypefaceMetrics)
-
- SkString fFontName;
-
- enum FontType {
- kType1_Font,
- kType1CID_Font,
- kCFF_Font,
- kTrueType_Font,
- kOther_Font,
- };
- // The type of the underlying font program. This field determines which
- // of the following fields are valid. If it is kOther_Font the per glyph
- // information will never be populated.
- FontType fType;
-
- enum FontFlags {
- kEmpty_FontFlag = 0x0, //!
- struct AdvanceMetric {
- enum MetricType {
- kDefault, // Default advance: fAdvance.count = 1
- kRange, // Advances for a range: fAdvance.count = fEndID-fStartID
- kRun // fStartID-fEndID have same advance: fAdvance.count = 1
- };
- MetricType fType;
- uint16_t fStartId;
- uint16_t fEndId;
- SkTDArray fAdvance;
- SkAutoTDelete > fNext;
- };
-
- struct VerticalMetric {
- int16_t fVerticalAdvance;
- int16_t fOriginXDisp; // Horiz. displacement of the secondary origin.
- int16_t fOriginYDisp; // Vert. displacement of the secondary origin.
- };
- typedef AdvanceMetric WidthRange;
- typedef AdvanceMetric VerticalAdvanceRange;
-
- // This is indexed by glyph id.
- SkAutoTDelete fGlyphWidths;
- // Only used for Vertical CID fonts.
- SkAutoTDelete fVerticalMetrics;
-
- // The names of each glyph, only populated for postscript fonts.
- SkAutoTDelete > fGlyphNames;
-
- // The mapping from glyph to Unicode, only populated if
- // kToUnicode_PerGlyphInfo is passed to GetAdvancedTypefaceMetrics.
- SkTDArray fGlyphToUnicode;
-
-private:
- typedef SkRefCnt INHERITED;
-};
-
-namespace skia_advanced_typeface_metrics_utils {
-
-template
-void resetRange(SkAdvancedTypefaceMetrics::AdvanceMetric* range,
- int startId);
-
-template
-SkAdvancedTypefaceMetrics::AdvanceMetric* appendRange(
- SkAutoTDelete >* nextSlot,
- int startId);
-
-template
-void finishRange(
- SkAdvancedTypefaceMetrics::AdvanceMetric* range,
- int endId,
- typename SkAdvancedTypefaceMetrics::AdvanceMetric::MetricType
- type);
-
-/** Retrieve advance data for glyphs. Used by the PDF backend. It calls
- underlying platform dependent API getAdvance to acquire the data.
- @param num_glyphs Total number of glyphs in the given font.
- @param glyphIDs For per-glyph info, specify subset of the font by
- giving glyph ids. Each integer represents a glyph
- id. Passing NULL means all glyphs in the font.
- @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if
- glyphIDs is NULL.
-*/
-template
-SkAdvancedTypefaceMetrics::AdvanceMetric* getAdvanceData(
- FontHandle fontHandle,
- int num_glyphs,
- const uint32_t* glyphIDs,
- uint32_t glyphIDsCount,
- bool (*getAdvance)(FontHandle fontHandle, int gId, Data* data));
-
-} // namespace skia_advanced_typeface_metrics_utils
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkAnnotation.h b/gfx/skia/skia/include/core/SkAnnotation.h
index d7b9b84529..80503c78d2 100644
--- a/gfx/skia/skia/include/core/SkAnnotation.h
+++ b/gfx/skia/skia/include/core/SkAnnotation.h
@@ -10,12 +10,11 @@
#include "SkRefCnt.h"
#include "SkString.h"
+#include "SkTypes.h"
class SkData;
class SkReadBuffer;
class SkWriteBuffer;
-class SkStream;
-class SkWStream;
struct SkPoint;
/**
@@ -27,12 +26,10 @@ public:
virtual ~SkAnnotation();
static SkAnnotation* Create(const char key[], SkData* value) {
- return SkNEW_ARGS(SkAnnotation, (key, value));
+ return new SkAnnotation(key, value);
}
- static SkAnnotation* Create(SkReadBuffer& buffer) {
- return SkNEW_ARGS(SkAnnotation, (buffer));
- }
+ static SkAnnotation* Create(SkReadBuffer& buffer) { return new SkAnnotation(buffer); }
/**
* Return the data for the specified key, or NULL.
diff --git a/gfx/skia/skia/include/core/SkBBHFactory.h b/gfx/skia/skia/include/core/SkBBHFactory.h
index 4c03844221..ca7040409d 100644
--- a/gfx/skia/skia/include/core/SkBBHFactory.h
+++ b/gfx/skia/skia/include/core/SkBBHFactory.h
@@ -8,62 +8,24 @@
#ifndef SkBBHFactory_DEFINED
#define SkBBHFactory_DEFINED
-#include "SkSize.h"
-#include "SkPoint.h"
-
+#include "SkTypes.h"
class SkBBoxHierarchy;
+struct SkRect;
class SK_API SkBBHFactory {
public:
/**
* Allocate a new SkBBoxHierarchy. Return NULL on failure.
*/
- virtual SkBBoxHierarchy* operator()(int width, int height) const = 0;
+ virtual SkBBoxHierarchy* operator()(const SkRect& bounds) const = 0;
virtual ~SkBBHFactory() {};
};
-class SK_API SkQuadTreeFactory : public SkBBHFactory {
-public:
- virtual SkBBoxHierarchy* operator()(int width, int height) const SK_OVERRIDE;
-private:
- typedef SkBBHFactory INHERITED;
-};
-
-
class SK_API SkRTreeFactory : public SkBBHFactory {
public:
- virtual SkBBoxHierarchy* operator()(int width, int height) const SK_OVERRIDE;
+ SkBBoxHierarchy* operator()(const SkRect& bounds) const override;
private:
typedef SkBBHFactory INHERITED;
};
-class SK_API SkTileGridFactory : public SkBBHFactory {
-public:
- struct TileGridInfo {
- /** Tile placement interval */
- SkISize fTileInterval;
-
- /** Pixel coverage overlap between adjacent tiles */
- SkISize fMargin;
-
- /** Offset added to device-space bounding box positions to convert
- * them to tile-grid space. This can be used to adjust the "phase"
- * of the tile grid to match probable query rectangles that will be
- * used to search into the tile grid. As long as the offset is smaller
- * or equal to the margin, there is no need to extend the domain of
- * the tile grid to prevent data loss.
- */
- SkIPoint fOffset;
- };
-
- SkTileGridFactory(const TileGridInfo& info) : fInfo(info) { }
-
- virtual SkBBoxHierarchy* operator()(int width, int height) const SK_OVERRIDE;
-
-private:
- TileGridInfo fInfo;
-
- typedef SkBBHFactory INHERITED;
-};
-
#endif
diff --git a/gfx/skia/skia/include/core/SkBitmap.h b/gfx/skia/skia/include/core/SkBitmap.h
index 0e847f2a4c..eda13b3c52 100644
--- a/gfx/skia/skia/include/core/SkBitmap.h
+++ b/gfx/skia/skia/include/core/SkBitmap.h
@@ -11,6 +11,7 @@
#include "SkColor.h"
#include "SkColorTable.h"
#include "SkImageInfo.h"
+#include "SkPixmap.h"
#include "SkPoint.h"
#include "SkRefCnt.h"
@@ -38,29 +39,6 @@ class SK_API SkBitmap {
public:
class SK_API Allocator;
-#ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
- enum Config {
- kNo_Config, //!< bitmap has not been configured
- kA8_Config, //!< 8-bits per pixel, with only alpha specified (0 is transparent, 0xFF is opaque)
- kIndex8_Config, //!< 8-bits per pixel, using SkColorTable to specify the colors
- kRGB_565_Config, //!< 16-bits per pixel, (see SkColorPriv.h for packing)
- kARGB_4444_Config, //!< 16-bits per pixel, (see SkColorPriv.h for packing)
- kARGB_8888_Config, //!< 32-bits per pixel, (see SkColorPriv.h for packing)
- };
-
- // do not add this to the Config enum, otherwise the compiler will let us
- // pass this as a valid parameter for Config.
- enum {
- kConfigCount = kARGB_8888_Config + 1
- };
-
- /** Return the config for the bitmap. */
- Config config() const;
-
- SK_ATTR_DEPRECATED("use config()")
- Config getConfig() const { return this->config(); }
-#endif
-
/**
* Default construct creates a bitmap with zero width and height, and no pixels.
* Its colortype is set to kUnknown_SkColorType.
@@ -91,10 +69,11 @@ public:
const SkImageInfo& info() const { return fInfo; }
- int width() const { return fInfo.fWidth; }
- int height() const { return fInfo.fHeight; }
- SkColorType colorType() const { return fInfo.fColorType; }
- SkAlphaType alphaType() const { return fInfo.fAlphaType; }
+ int width() const { return fInfo.width(); }
+ int height() const { return fInfo.height(); }
+ SkColorType colorType() const { return fInfo.colorType(); }
+ SkAlphaType alphaType() const { return fInfo.alphaType(); }
+ SkColorProfileType profileType() const { return fInfo.profileType(); }
/**
* Return the number of bytes per pixel based on the colortype. If the colortype is
@@ -155,7 +134,7 @@ public:
Note this truncates the result to 32bits. Call getSize64() to detect
if the real size exceeds 32bits.
*/
- size_t getSize() const { return fInfo.fHeight * fRowBytes; }
+ size_t getSize() const { return fInfo.height() * fRowBytes; }
/** Return the number of bytes from the pointer returned by getPixels()
to the end of the allocated space in the buffer. Required in
@@ -167,7 +146,7 @@ public:
* Return the full size of the bitmap, in bytes.
*/
int64_t computeSize64() const {
- return sk_64_mul(fInfo.fHeight, fRowBytes);
+ return sk_64_mul(fInfo.height(), fRowBytes);
}
/**
@@ -233,6 +212,14 @@ public:
void getBounds(SkRect* bounds) const;
void getBounds(SkIRect* bounds) const;
+ SkIRect bounds() const { return fInfo.bounds(); }
+ SkISize dimensions() const { return fInfo.dimensions(); }
+ // Returns the bounds of this bitmap, offset by its pixelref origin.
+ SkIRect getSubset() const {
+ return SkIRect::MakeXYWH(fPixelRefOrigin.x(), fPixelRefOrigin.y(),
+ fInfo.width(), fInfo.height());
+ }
+
bool setInfo(const SkImageInfo&, size_t rowBytes = 0);
/**
@@ -241,7 +228,13 @@ public:
* a colortable, then ColorTable must be non-null, and will be ref'd.
* On failure, the bitmap will be set to empty and return false.
*/
- bool allocPixels(const SkImageInfo&, SkPixelRefFactory*, SkColorTable*);
+ bool SK_WARN_UNUSED_RESULT tryAllocPixels(const SkImageInfo&, SkPixelRefFactory*, SkColorTable*);
+
+ void allocPixels(const SkImageInfo& info, SkPixelRefFactory* factory, SkColorTable* ctable) {
+ if (!this->tryAllocPixels(info, factory, ctable)) {
+ sk_throw();
+ }
+ }
/**
* Allocate the bitmap's pixels to match the requested image info and
@@ -251,24 +244,32 @@ public:
* the pixel size specified by info.colorType()) then false is returned
* and the bitmap is set to empty.
*/
- bool allocPixels(const SkImageInfo& info, size_t rowBytes);
+ bool SK_WARN_UNUSED_RESULT tryAllocPixels(const SkImageInfo& info, size_t rowBytes);
- /**
- * Allocate a pixelref to match the specified image info, using the default
- * allocator.
- * On success, the bitmap's pixels will be "locked", and return true.
- * On failure, the bitmap will be set to empty and return false.
- */
- bool allocPixels(const SkImageInfo& info) {
- return this->allocPixels(info, info.minRowBytes());
+ void allocPixels(const SkImageInfo& info, size_t rowBytes) {
+ if (!this->tryAllocPixels(info, rowBytes)) {
+ sk_throw();
+ }
}
- bool allocN32Pixels(int width, int height, bool isOpaque = false) {
- SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);
- if (isOpaque) {
- info.fAlphaType = kOpaque_SkAlphaType;
- }
- return this->allocPixels(info);
+ bool SK_WARN_UNUSED_RESULT tryAllocPixels(const SkImageInfo& info) {
+ return this->tryAllocPixels(info, info.minRowBytes());
+ }
+
+ void allocPixels(const SkImageInfo& info) {
+ this->allocPixels(info, info.minRowBytes());
+ }
+
+ 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);
+ }
+
+ void allocN32Pixels(int width, int height, bool isOpaque = false) {
+ SkImageInfo info = SkImageInfo::MakeN32(width, height,
+ isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
+ this->allocPixels(info);
}
/**
@@ -277,6 +278,9 @@ public:
* referenced, if releaseProc is not null, it will be called with the
* pixels and context as parameters.
* On failure, the bitmap will be set to empty and return false.
+ *
+ * If specified, the releaseProc will always be called, even on failure. It is also possible
+ * for success but the releaseProc is immediately called (e.g. valid Info but NULL pixels).
*/
bool installPixels(const SkImageInfo&, void* pixels, size_t rowBytes, SkColorTable*,
void (*releaseProc)(void* addr, void* context), void* context);
@@ -343,8 +347,12 @@ public:
@return true if the allocation succeeds. If not the pixelref field of
the bitmap will be unchanged.
*/
- bool allocPixels(SkColorTable* ctable = NULL) {
- return this->allocPixels(NULL, ctable);
+ bool SK_WARN_UNUSED_RESULT tryAllocPixels(SkColorTable* ctable = NULL) {
+ return this->tryAllocPixels(NULL, ctable);
+ }
+
+ void allocPixels(SkColorTable* ctable = NULL) {
+ this->allocPixels(NULL, ctable);
}
/** Use the specified Allocator to create the pixelref that manages the
@@ -365,7 +373,13 @@ public:
@return true if the allocation succeeds. If not the pixelref field of
the bitmap will be unchanged.
*/
- bool allocPixels(Allocator* allocator, SkColorTable* ctable);
+ bool SK_WARN_UNUSED_RESULT tryAllocPixels(Allocator* allocator, SkColorTable* ctable);
+
+ void allocPixels(Allocator* allocator, SkColorTable* ctable) {
+ if (!this->tryAllocPixels(allocator, ctable)) {
+ sk_throw();
+ }
+ }
/**
* Return the current pixelref object or NULL if there is none. This does
@@ -423,13 +437,15 @@ public:
*/
bool lockPixelsAreWritable() const;
+ bool requestLock(SkAutoPixmapUnlock* result) const;
+
/** Call this to be sure that the bitmap is valid enough to be drawn (i.e.
it has non-null pixels, and if required by its colortype, it has a
non-null colortable. Returns true if all of the above are met.
*/
bool readyToDraw() const {
return this->getPixels() != NULL &&
- (this->colorType() != kIndex_8_SkColorType || NULL != fColorTable);
+ (this->colorType() != kIndex_8_SkColorType || fColorTable);
}
/** Returns the pixelRef's texture, or NULL
@@ -462,10 +478,7 @@ public:
* of the color is ignored (treated as opaque). If the colortype only supports
* alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
*/
- void eraseColor(SkColor c) const {
- this->eraseARGB(SkColorGetA(c), SkColorGetR(c), SkColorGetG(c),
- SkColorGetB(c));
- }
+ void eraseColor(SkColor c) const;
/**
* Fill the entire bitmap with the specified color.
@@ -473,7 +486,9 @@ public:
* of the color is ignored (treated as opaque). If the colortype only supports
* alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
*/
- void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const;
+ void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
+ this->eraseColor(SkColorSetARGB(a, r, g, b));
+ }
SK_ATTR_DEPRECATED("use eraseARGB or eraseColor")
void eraseRGB(U8CPU r, U8CPU g, U8CPU b) const {
@@ -486,29 +501,12 @@ public:
* of the color is ignored (treated as opaque). If the colortype only supports
* alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
*/
- void eraseArea(const SkIRect& area, SkColor c) const;
+ void erase(SkColor c, const SkIRect& area) const;
- /** Scroll (a subset of) the contents of this bitmap by dx/dy. If there are
- no pixels allocated (i.e. getPixels() returns null) the method will
- still update the inval region (if present). If the bitmap is immutable,
- do nothing and return false.
-
- @param subset The subset of the bitmap to scroll/move. To scroll the
- entire contents, specify [0, 0, width, height] or just
- pass null.
- @param dx The amount to scroll in X
- @param dy The amount to scroll in Y
- @param inval Optional (may be null). Returns the area of the bitmap that
- was scrolled away. E.g. if dx = dy = 0, then inval would
- be set to empty. If dx >= width or dy >= height, then
- inval would be set to the entire bounds of the bitmap.
- @return true if the scroll was doable. Will return false if the colortype is kUnkown or
- if the bitmap is immutable.
- If no pixels are present (i.e. getPixels() returns false)
- inval will still be updated, and true will be returned.
- */
- bool scrollRect(const SkIRect* subset, int dx, int dy,
- SkRegion* inval = NULL) const;
+ // DEPRECATED
+ void eraseArea(const SkIRect& area, SkColor c) const {
+ this->erase(c, area);
+ }
/**
* Return the SkColor of the specified pixel. In most cases this will
@@ -665,12 +663,21 @@ public:
bool extractAlpha(SkBitmap* dst, const SkPaint* paint, Allocator* allocator,
SkIPoint* offset) const;
+ /**
+ * If the pixels are available from this bitmap (w/o locking) return true, and fill out the
+ * specified pixmap (if not null). If the pixels are not available (either because there are
+ * none, or becuase accessing them would require locking or other machinary) return false and
+ * ignore the pixmap parameter.
+ *
+ * Note: if this returns true, the results (in the pixmap) are only valid until the bitmap
+ * is changed in anyway, in which case the results are invalid.
+ */
+ bool peekPixels(SkPixmap*) const;
+
SkDEBUGCODE(void validate() const;)
class Allocator : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(Allocator)
-
/** Allocate the pixel memory for the bitmap, given its dimensions and
colortype. Return true on success, where success means either setPixels
or setPixelRef was called. The pixels need not be locked when this
@@ -689,7 +696,7 @@ public:
*/
class HeapAllocator : public Allocator {
public:
- virtual bool allocPixelRef(SkBitmap*, SkColorTable*) SK_OVERRIDE;
+ bool allocPixelRef(SkBitmap*, SkColorTable*) override;
};
class RLEPixels {
@@ -736,24 +743,17 @@ private:
};
SkImageInfo fInfo;
-
uint32_t fRowBytes;
-
uint8_t fFlags;
- void internalErase(const SkIRect&, U8CPU a, U8CPU r, U8CPU g, U8CPU b)const;
-
/* Unreference any pixelrefs or colortables
*/
void freePixels();
void updatePixelsFromRef() const;
- void legacyUnflatten(SkReadBuffer&);
-
static void WriteRawPixels(SkWriteBuffer*, const SkBitmap&);
static bool ReadRawPixels(SkReadBuffer*, SkBitmap*);
- friend class SkBitmapSource; // unflatten
friend class SkReadBuffer; // unflatten, rawpixels
friend class SkWriteBuffer; // rawpixels
friend struct SkBitmapProcState;
@@ -780,60 +780,6 @@ private:
//TODO(mtklein): uncomment when 71713004 lands and Chromium's fixed.
//#define SkAutoLockPixels(...) SK_REQUIRE_LOCAL_VAR(SkAutoLockPixels)
-/** Helper class that performs the lock/unlockColors calls on a colortable.
- The destructor will call unlockColors(false) if it has a bitmap's colortable
-*/
-class SkAutoLockColors : SkNoncopyable {
-public:
- /** Initialize with no bitmap. Call lockColors(bitmap) to lock bitmap's
- colortable
- */
- SkAutoLockColors() : fCTable(NULL), fColors(NULL) {}
- /** Initialize with bitmap, locking its colortable if present
- */
- explicit SkAutoLockColors(const SkBitmap& bm) {
- fCTable = bm.getColorTable();
- fColors = fCTable ? fCTable->lockColors() : NULL;
- }
- /** Initialize with a colortable (may be null)
- */
- explicit SkAutoLockColors(SkColorTable* ctable) {
- fCTable = ctable;
- fColors = ctable ? ctable->lockColors() : NULL;
- }
- ~SkAutoLockColors() {
- if (fCTable) {
- fCTable->unlockColors();
- }
- }
-
- /** Return the currently locked colors, or NULL if no bitmap's colortable
- is currently locked.
- */
- const SkPMColor* colors() const { return fColors; }
-
- /** Locks the table and returns is colors (assuming ctable is not null) and
- unlocks the previous table if one was present
- */
- const SkPMColor* lockColors(SkColorTable* ctable) {
- if (fCTable) {
- fCTable->unlockColors();
- }
- fCTable = ctable;
- fColors = ctable ? ctable->lockColors() : NULL;
- return fColors;
- }
-
- const SkPMColor* lockColors(const SkBitmap& bm) {
- return this->lockColors(bm.getColorTable());
- }
-
-private:
- SkColorTable* fCTable;
- const SkPMColor* fColors;
-};
-#define SkAutoLockColors(...) SK_REQUIRE_LOCAL_VAR(SkAutoLockColors)
-
///////////////////////////////////////////////////////////////////////////////
inline uint32_t* SkBitmap::getAddr32(int x, int y) const {
@@ -865,13 +811,4 @@ inline SkPMColor SkBitmap::getIndex8Color(int x, int y) const {
return (*fColorTable)[*((const uint8_t*)fPixels + y * fRowBytes + x)];
}
-#ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
-///////////////////////////////////////////////////////////////////////////////
-//
-// Helpers until we can fully deprecate SkBitmap::Config
-//
-SK_API SkBitmap::Config SkColorTypeToBitmapConfig(SkColorType);
-SK_API SkColorType SkBitmapConfigToColorType(SkBitmap::Config);
-#endif
-
#endif
diff --git a/gfx/skia/skia/include/core/SkBitmapDevice.h b/gfx/skia/skia/include/core/SkBitmapDevice.h
index e1765e56ab..d1cb9ad0f8 100644
--- a/gfx/skia/skia/include/core/SkBitmapDevice.h
+++ b/gfx/skia/skia/include/core/SkBitmapDevice.h
@@ -9,54 +9,74 @@
#ifndef SkBitmapDevice_DEFINED
#define SkBitmapDevice_DEFINED
+#include "SkBitmap.h"
+#include "SkCanvas.h"
+#include "SkColor.h"
#include "SkDevice.h"
+#include "SkImageFilter.h"
+#include "SkImageInfo.h"
+#include "SkRect.h"
+#include "SkScalar.h"
+#include "SkSize.h"
+#include "SkSurfaceProps.h"
+#include "SkTypes.h"
+
+class SkDraw;
+class SkMatrix;
+class SkPaint;
+class SkPath;
+class SkPixelRef;
+class SkPixmap;
+class SkRRect;
+class SkSurface;
+class SkXfermode;
+struct SkPoint;
///////////////////////////////////////////////////////////////////////////////
class SK_API SkBitmapDevice : public SkBaseDevice {
public:
- SK_DECLARE_INST_COUNT(SkBitmapDevice)
-
/**
* Construct a new device with the specified bitmap as its backend. It is
* valid for the bitmap to have no pixels associated with it. In that case,
* any drawing to this device will have no effect.
- */
+ */
SkBitmapDevice(const SkBitmap& bitmap);
+ /**
+ * Create a new device along with its requisite pixel memory using
+ * default SkSurfaceProps (i.e., kLegacyFontHost_InitType-style).
+ * Note: this entry point is slated for removal - no one should call it.
+ */
+ static SkBitmapDevice* Create(const SkImageInfo& info);
+
/**
* Construct a new device with the specified bitmap as its backend. It is
* valid for the bitmap to have no pixels associated with it. In that case,
* any drawing to this device will have no effect.
- */
- SkBitmapDevice(const SkBitmap& bitmap, const SkDeviceProperties& deviceProperties);
+ */
+ SkBitmapDevice(const SkBitmap& bitmap, const SkSurfaceProps& surfaceProps);
- static SkBitmapDevice* Create(const SkImageInfo&,
- const SkDeviceProperties* = NULL);
+ static SkBitmapDevice* Create(const SkImageInfo&, const SkSurfaceProps&);
- virtual SkImageInfo imageInfo() const SK_OVERRIDE;
+ SkImageInfo imageInfo() const override;
protected:
- virtual bool filterTextFlags(const SkPaint& paint, TextFlags*) SK_OVERRIDE;
-
- /** Clears the entire device to the specified color (including alpha).
- * Ignores the clip.
- */
- virtual void clear(SkColor color) SK_OVERRIDE;
+ bool onShouldDisableLCD(const SkPaint&) const override;
/** These are called inside the per-device-layer loop for each draw call.
When these are called, we have already applied any saveLayer operations,
and are handling any looping from the paint, and any effects from the
DrawFilter.
*/
- virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE;
+ void drawPaint(const SkDraw&, const SkPaint& paint) override;
virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,
- const SkPoint[], const SkPaint& paint) SK_OVERRIDE;
+ const SkPoint[], const SkPaint& paint) override;
virtual void drawRect(const SkDraw&, const SkRect& r,
- const SkPaint& paint) SK_OVERRIDE;
+ const SkPaint& paint) override;
virtual void drawOval(const SkDraw&, const SkRect& oval,
- const SkPaint& paint) SK_OVERRIDE;
+ const SkPaint& paint) override;
virtual void drawRRect(const SkDraw&, const SkRRect& rr,
- const SkPaint& paint) SK_OVERRIDE;
+ const SkPaint& paint) override;
/**
* If pathIsMutable, then the implementation is allowed to cast path to a
@@ -72,43 +92,34 @@ protected:
virtual void drawPath(const SkDraw&, const SkPath& path,
const SkPaint& paint,
const SkMatrix* prePathMatrix = NULL,
- bool pathIsMutable = false) SK_OVERRIDE;
+ bool pathIsMutable = false) override;
virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,
- const SkMatrix& matrix, const SkPaint& paint) SK_OVERRIDE;
+ const SkMatrix& matrix, const SkPaint& paint) override;
virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,
- int x, int y, const SkPaint& paint) SK_OVERRIDE;
+ int x, int y, const SkPaint& paint) override;
/**
* The default impl. will create a bitmap-shader from the bitmap,
* and call drawRect with it.
*/
- virtual void drawBitmapRect(const SkDraw&, const SkBitmap&,
- const SkRect* srcOrNull, const SkRect& dst,
- const SkPaint& paint,
- SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE;
+ void drawBitmapRect(const SkDraw&, const SkBitmap&, const SkRect*, const SkRect&,
+ const SkPaint&, SkCanvas::SrcRectConstraint) override;
/**
* Does not handle text decoration.
* Decorations (underline and stike-thru) will be handled by SkCanvas.
*/
virtual void drawText(const SkDraw&, const void* text, size_t len,
- SkScalar x, SkScalar y, const SkPaint& paint) SK_OVERRIDE;
+ SkScalar x, SkScalar y, const SkPaint& paint) override;
virtual void drawPosText(const SkDraw&, const void* text, size_t len,
- const SkScalar pos[], SkScalar constY,
- int scalarsPerPos, const SkPaint& paint) SK_OVERRIDE;
- virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,
- const SkPath& path, const SkMatrix* matrix,
- const SkPaint& paint) SK_OVERRIDE;
+ const SkScalar pos[], int scalarsPerPos,
+ const SkPoint& offset, const SkPaint& paint) override;
virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,
const SkPoint verts[], const SkPoint texs[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
- const SkPaint& paint) SK_OVERRIDE;
- /** The SkBaseDevice passed will be an SkBaseDevice which was returned by a call to
- onCreateDevice on this device with kSaveLayer_Usage.
- */
- virtual void drawDevice(const SkDraw&, SkBaseDevice*, int x, int y,
- const SkPaint&) SK_OVERRIDE;
+ const SkPaint& paint) override;
+ virtual void drawDevice(const SkDraw&, SkBaseDevice*, int x, int y, const SkPaint&) override;
///////////////////////////////////////////////////////////////////////////
@@ -117,7 +128,7 @@ protected:
altered. The config/width/height/rowbytes must remain unchanged.
@return the device contents as a bitmap
*/
- virtual const SkBitmap& onAccessBitmap() SK_OVERRIDE;
+ const SkBitmap& onAccessBitmap() override;
SkPixelRef* getPixelRef() const { return fBitmap.pixelRef(); }
// just for subclasses, to assign a custom pixelref
@@ -126,15 +137,12 @@ protected:
return pr;
}
- virtual bool onReadPixels(const SkImageInfo&, void*, size_t, int x, int y) SK_OVERRIDE;
- virtual bool onWritePixels(const SkImageInfo&, const void*, size_t, int, int) SK_OVERRIDE;
- virtual void* onAccessPixels(SkImageInfo* info, size_t* rowBytes) SK_OVERRIDE;
-
- /** Called when this device is installed into a Canvas. Balanced by a call
- to unlockPixels() when the device is removed from a Canvas.
- */
- virtual void lockPixels() SK_OVERRIDE;
- virtual void unlockPixels() SK_OVERRIDE;
+ bool onReadPixels(const SkImageInfo&, void*, size_t, int x, int y) override;
+ bool onWritePixels(const SkImageInfo&, const void*, size_t, int, int) override;
+ bool onPeekPixels(SkPixmap*) override;
+ bool onAccessPixels(SkPixmap*) override;
+ void onAttachToCanvas(SkCanvas*) override;
+ void onDetachFromCanvas() override;
private:
friend class SkCanvas;
@@ -142,22 +150,24 @@ private:
friend class SkDraw;
friend class SkDrawIter;
friend class SkDeviceFilteredPaint;
- friend class SkDeviceImageFilterProxy;
friend class SkSurface_Raster;
// used to change the backend's pixels (and possibly config/rowbytes)
// but cannot change the width/height, so there should be no change to
// any clip information.
- virtual void replaceBitmapBackendForRasterSurface(const SkBitmap&) SK_OVERRIDE;
+ void replaceBitmapBackendForRasterSurface(const SkBitmap&) override;
- virtual SkBaseDevice* onCreateDevice(const SkImageInfo&, Usage) SK_OVERRIDE;
+ SkBaseDevice* onCreateDevice(const CreateInfo&, const SkPaint*) override;
- virtual SkSurface* newSurface(const SkImageInfo&) SK_OVERRIDE;
- virtual const void* peekPixels(SkImageInfo*, size_t* rowBytes) SK_OVERRIDE;
+ SkSurface* newSurface(const SkImageInfo&, const SkSurfaceProps&) override;
+
+ SkImageFilter::Cache* getImageFilterCache() override;
SkBitmap fBitmap;
+ void setNewSize(const SkISize&); // Used by SkCanvas for resetForNextPicture().
+
typedef SkBaseDevice INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkBlitRow.h b/gfx/skia/skia/include/core/SkBlitRow.h
index 9393589b82..56121eba78 100644
--- a/gfx/skia/skia/include/core/SkBlitRow.h
+++ b/gfx/skia/skia/include/core/SkBlitRow.h
@@ -26,17 +26,26 @@ public:
a corresponding scanline of 16bit colors (specific format based on the
config passed to the Factory.
- The x,y params are useful just for dithering
+ The x,y params provide the dithering phase for the start of the scanline
@param alpha A global alpha to be applied to all of the src colors
@param x The x coordinate of the beginning of the scanline
@param y THe y coordinate of the scanline
*/
- typedef void (*Proc)(uint16_t* dst,
- const SkPMColor* src,
- int count, U8CPU alpha, int x, int y);
+ typedef void (*Proc16)(uint16_t dst[], const SkPMColor src[], int count,
+ U8CPU alpha, int x, int y);
- static Proc Factory(unsigned flags, SkColorType);
+ static Proc16 Factory16(unsigned flags);
+
+ /**
+ * Function pointer that blends a single src color onto a scaline of dst colors.
+ *
+ * The x,y params provide the dithering phase for the start of the scanline
+ */
+ typedef void (*ColorProc16)(uint16_t dst[], SkPMColor src, int count, int x, int y);
+
+ // Note : we ignore the kGlobalAlpha_Flag setting, but do respect kSrcPixelAlpha_Flag
+ static ColorProc16 ColorFactory16(unsigned flags);
///////////// D32 version
@@ -51,38 +60,15 @@ public:
@param count number of colors to blend
@param alpha global alpha to be applied to all src colors
*/
- typedef void (*Proc32)(uint32_t* dst,
- const SkPMColor* src,
- int count, U8CPU alpha);
+ typedef void (*Proc32)(uint32_t dst[], const SkPMColor src[], int count, U8CPU alpha);
static Proc32 Factory32(unsigned flags32);
- /** Function pointer that blends a single color with a row of 32-bit colors
- onto a 32-bit destination
- */
- typedef void (*ColorProc)(SkPMColor* dst, const SkPMColor* src, int count,
- SkPMColor color);
-
/** Blend a single color onto a row of S32 pixels, writing the result
into a row of D32 pixels. src and dst may be the same memory, but
if they are not, they may not overlap.
*/
- static void Color32(SkPMColor dst[], const SkPMColor src[],
- int count, SkPMColor color);
-
- //! Public entry-point to return a blit function ptr
- static ColorProc ColorProcFactory();
-
- /** Function pointer that blends a single color onto a 32-bit rectangle. */
- typedef void (*ColorRectProc)(SkPMColor* dst, int width, int height,
- size_t rowBytes, SkPMColor color);
-
- /** Blend a single color into a rectangle of D32 pixels. */
- static void ColorRect32(SkPMColor* dst, int width, int height,
- size_t rowBytes, SkPMColor color);
-
- //! Public entry-point to return a blit function ptr
- static ColorRectProc ColorRectProcFactory();
+ static void Color32(SkPMColor dst[], const SkPMColor src[], int count, SkPMColor color);
/** These static functions are called by the Factory and Factory32
functions, and should return either NULL, or a
@@ -91,8 +77,9 @@ public:
*/
static Proc32 PlatformProcs32(unsigned flags);
- static Proc PlatformProcs565(unsigned flags);
- static ColorProc PlatformColorProc();
+
+ static Proc16 PlatformFactory565(unsigned flags);
+ static ColorProc16 PlatformColorFactory565(unsigned flags);
private:
enum {
diff --git a/gfx/skia/skia/include/core/SkCanvas.h b/gfx/skia/skia/include/core/SkCanvas.h
index d68a9c50ab..53f6dda88b 100644
--- a/gfx/skia/skia/include/core/SkCanvas.h
+++ b/gfx/skia/skia/include/core/SkCanvas.h
@@ -11,30 +11,31 @@
#include "SkTypes.h"
#include "SkBitmap.h"
#include "SkDeque.h"
-#include "SkClipStack.h"
#include "SkPaint.h"
#include "SkRefCnt.h"
-#include "SkPath.h"
#include "SkRegion.h"
+#include "SkSurfaceProps.h"
#include "SkXfermode.h"
-#ifdef SK_SUPPORT_LEGACY_DRAWTEXT_VIRTUAL
- #define SK_LEGACY_DRAWTEXT_VIRTUAL virtual
-#else
- #define SK_LEGACY_DRAWTEXT_VIRTUAL
-#endif
-
-class SkCanvasClipVisitor;
-class SkBaseDevice;
-class SkDraw;
-class SkDrawFilter;
-class SkMetaData;
-class SkPicture;
-class SkRRect;
-class SkSurface;
-class SkSurface_Base;
class GrContext;
class GrRenderTarget;
+class SkBaseDevice;
+class SkCanvasClipVisitor;
+class SkClipStack;
+class SkDraw;
+class SkDrawable;
+class SkDrawFilter;
+class SkImage;
+class SkImageFilter;
+class SkMetaData;
+class SkPath;
+class SkPicture;
+class SkPixmap;
+class SkRRect;
+struct SkRSXform;
+class SkSurface;
+class SkSurface_Base;
+class SkTextBlob;
/** \class SkCanvas
@@ -53,37 +54,6 @@ class GrRenderTarget;
*/
class SK_API SkCanvas : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkCanvas)
-
- /**
- * Attempt to allocate an offscreen raster canvas, matching the ImageInfo.
- * On success, return a new canvas that will draw into that offscreen.
- *
- * The caller can access the pixels after drawing into this canvas by
- * calling readPixels() or peekPixels().
- *
- * If the requested ImageInfo is opaque (either the colortype is
- * intrinsically opaque like RGB_565, or the info's alphatype is kOpaque)
- * then the pixel memory may be uninitialized. Otherwise, the pixel memory
- * will be initialized to 0, which is interpreted as transparent.
- *
- * On failure, return NULL. This can fail for several reasons:
- * 1. the memory allocation failed (e.g. request is too large)
- * 2. invalid ImageInfo (e.g. negative dimensions)
- * 3. unsupported ImageInfo for a canvas
- * - kUnknown_SkColorType, kIndex_8_SkColorType
- * - kIgnore_SkAlphaType
- * - this list is not complete, so others may also be unsupported
- *
- * Note: it is valid to request a supported ImageInfo, but with zero
- * dimensions.
- */
- static SkCanvas* NewRaster(const SkImageInfo&);
-
- static SkCanvas* NewRasterN32(int width, int height) {
- return NewRaster(SkImageInfo::MakeN32Premul(width, height));
- }
-
/**
* Attempt to allocate raster canvas, matching the ImageInfo, that will draw directly into the
* specified pixels. To access the pixels after drawing to them, the caller should call
@@ -93,7 +63,7 @@ public:
* 1. invalid ImageInfo (e.g. negative dimensions)
* 2. unsupported ImageInfo for a canvas
* - kUnknown_SkColorType, kIndex_8_SkColorType
- * - kIgnore_SkAlphaType
+ * - kUnknown_SkAlphaType
* - this list is not complete, so others may also be unsupported
*
* Note: it is valid to request a supported ImageInfo, but with zero
@@ -116,7 +86,7 @@ public:
* by any device/pixels. Typically this use used by subclasses who handle
* the draw calls in some other way.
*/
- SkCanvas(int width, int height);
+ SkCanvas(int width, int height, const SkSurfaceProps* = NULL);
/** Construct a canvas with the specified device to draw into.
@@ -129,6 +99,14 @@ public:
structure are copied to the canvas.
*/
explicit SkCanvas(const SkBitmap& bitmap);
+
+ /** Construct a canvas with the specified bitmap to draw into.
+ @param bitmap Specifies a bitmap for the canvas to draw into. Its
+ structure are copied to the canvas.
+ @param props New canvas surface properties.
+ */
+ SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props);
+
virtual ~SkCanvas();
SkMetaData& getMetaData();
@@ -151,7 +129,7 @@ public:
* origin of the base layer is always (0,0). The current drawable area may be
* smaller (due to clipping or saveLayer).
*/
- SkISize getBaseLayerSize() const;
+ virtual SkISize getBaseLayerSize() const;
/**
* DEPRECATED: call getBaseLayerSize
@@ -169,6 +147,9 @@ protected: // Can we make this private?
#endif
SkBaseDevice* getDevice() const;
public:
+ SkBaseDevice* getDevice_just_for_deprecated_compatibility_testing() const {
+ return this->getDevice();
+ }
/**
* saveLayer() can create another device (which is later drawn onto
@@ -193,8 +174,12 @@ public:
* Create a new surface matching the specified info, one that attempts to
* be maximally compatible when used with this canvas. If there is no matching Surface type,
* NULL is returned.
+ *
+ * If surfaceprops is specified, those are passed to the new surface, otherwise the new surface
+ * inherits the properties of the surface that owns this canvas. If this canvas has no parent
+ * surface, then the new surface is created with default properties.
*/
- SkSurface* newSurface(const SkImageInfo&);
+ SkSurface* newSurface(const SkImageInfo&, const SkSurfaceProps* = NULL);
/**
* Return the GPU context of the device that is associated with the canvas.
@@ -347,6 +332,9 @@ public:
@return The value to pass to restoreToCount() to balance this save()
*/
int saveLayer(const SkRect* bounds, const SkPaint* paint);
+ int saveLayer(const SkRect& bounds, const SkPaint* paint) {
+ return this->saveLayer(&bounds, paint);
+ }
/** DEPRECATED - use saveLayer(const SkRect*, const SkPaint*) instead.
@@ -417,11 +405,6 @@ public:
*/
void restoreToCount(int saveCount);
- /** Returns true if drawing is currently going to a layer (from saveLayer)
- * rather than to the root device.
- */
- virtual bool isDrawingToLayer() const;
-
/** Preconcat the current matrix with the specified translation
@param dx The distance to translate in X
@param dy The distance to translate in Y
@@ -609,24 +592,15 @@ public:
@param color the color to draw with
@param mode the mode to apply the color in (defaults to SrcOver)
*/
- void drawColor(SkColor color,
- SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
+ void drawColor(SkColor color, SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
/**
- * This erases the entire drawing surface to the specified color,
- * irrespective of the clip. It does not blend with the previous pixels,
- * but always overwrites them.
- *
- * It is roughly equivalent to the following:
- * canvas.save();
- * canvas.clipRect(hugeRect, kReplace_Op);
- * paint.setColor(color);
- * paint.setXfermodeMode(kSrc_Mode);
- * canvas.drawPaint(paint);
- * canvas.restore();
- * though it is almost always much more efficient.
+ * Helper method for drawing a color in SRC mode, completely replacing all the pixels
+ * in the current clip with this color.
*/
- virtual void clear(SkColor);
+ void clear(SkColor color) {
+ this->drawColor(color, SkXfermode::kSrc_Mode);
+ }
/**
* This makes the contents of the canvas undefined. Subsequent calls that
@@ -647,7 +621,7 @@ public:
* specified paint.
* @param paint The paint used to fill the canvas
*/
- virtual void drawPaint(const SkPaint& paint);
+ void drawPaint(const SkPaint& paint);
enum PointMode {
/** drawPoints draws each point separately */
@@ -679,8 +653,7 @@ public:
@param pts Array of points to draw
@param paint The paint used to draw the points
*/
- virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[],
- const SkPaint& paint);
+ void drawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint);
/** Helper method for drawing a single point. See drawPoints() for a more
details.
@@ -711,7 +684,7 @@ public:
@param rect The rect to be drawn
@param paint The paint used to draw the rect
*/
- virtual void drawRect(const SkRect& rect, const SkPaint& paint);
+ void drawRect(const SkRect& rect, const SkPaint& paint);
/** Draw the specified rectangle using the specified paint. The rectangle
will be filled or framed based on the Style in the paint.
@@ -740,7 +713,7 @@ public:
@param oval The rectangle bounds of the oval to be drawn
@param paint The paint used to draw the oval
*/
- virtual void drawOval(const SkRect& oval, const SkPaint&);
+ void drawOval(const SkRect& oval, const SkPaint&);
/**
* Draw the specified RRect using the specified paint The rrect will be filled or stroked
@@ -749,7 +722,7 @@ public:
* @param rrect The round-rect to draw
* @param paint The paint used to draw the round-rect
*/
- virtual void drawRRect(const SkRRect& rrect, const SkPaint& paint);
+ void drawRRect(const SkRRect& rrect, const SkPaint& paint);
/**
* Draw the annulus formed by the outer and inner rrects. The results
@@ -797,7 +770,84 @@ public:
@param path The path to be drawn
@param paint The paint used to draw the path
*/
- virtual void drawPath(const SkPath& path, const SkPaint& paint);
+ void drawPath(const SkPath& path, const SkPaint& paint);
+
+ /** Draw the specified image, with its top/left corner at (x,y), using the
+ specified paint, transformed by the current matrix.
+
+ @param image The image to be drawn
+ @param left The position of the left side of the image being drawn
+ @param top The position of the top side of the image being drawn
+ @param paint The paint used to draw the image, or NULL
+ */
+ void drawImage(const SkImage* image, SkScalar left, SkScalar top, const SkPaint* paint = NULL);
+
+ /**
+ * Controls the behavior at the edge of the src-rect, when specified in drawImageRect,
+ * trading off speed for exactness.
+ *
+ * When filtering is enabled (in the Paint), skia may need to sample in a neighborhood around
+ * the pixels in the image. If there is a src-rect specified, it is intended to restrict the
+ * pixels that will be read. However, for performance reasons, some implementations may slow
+ * down if they cannot read 1-pixel past the src-rect boundary at times.
+ *
+ * This enum allows the caller to specify if such a 1-pixel "slop" will be visually acceptable.
+ * If it is, the caller should pass kFast, and it may result in a faster draw. If the src-rect
+ * must be strictly respected, the caller should pass kStrict.
+ */
+ enum SrcRectConstraint {
+ /**
+ * If kStrict is specified, the implementation must respect the src-rect
+ * (if specified) strictly, and will never sample outside of those bounds during sampling
+ * even when filtering. This may be slower than kFast.
+ */
+ kStrict_SrcRectConstraint,
+
+ /**
+ * If kFast is specified, the implementation may sample outside of the src-rect
+ * (if specified) by half the width of filter. This allows greater flexibility
+ * to the implementation and can make the draw much faster.
+ */
+ kFast_SrcRectConstraint,
+ };
+
+ /** Draw the specified image, scaling and translating so that it fills the specified
+ * dst rect. If the src rect is non-null, only that subset of the image is transformed
+ * and drawn.
+ *
+ * @param image The image to be drawn
+ * @param src Optional: specify the subset of the image to be drawn
+ * @param dst The destination rectangle where the scaled/translated
+ * image will be drawn
+ * @param paint The paint used to draw the image, or NULL
+ * @param constraint Control the tradeoff between speed and exactness w.r.t. the src-rect.
+ */
+ void drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
+ const SkPaint* paint,
+ SrcRectConstraint constraint = kStrict_SrcRectConstraint);
+ // variant that takes src SkIRect
+ void drawImageRect(const SkImage* image, const SkIRect& isrc, const SkRect& dst,
+ const SkPaint* paint, SrcRectConstraint = kStrict_SrcRectConstraint);
+ // variant that assumes src == image-bounds
+ void drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint,
+ SrcRectConstraint = kStrict_SrcRectConstraint);
+
+ /**
+ * Draw the image stretched differentially to fit into dst.
+ * center is a rect within the image, and logically divides the image
+ * into 9 sections (3x3). For example, if the middle pixel of a [5x5]
+ * image is the "center", then the center-rect should be [2, 2, 3, 3].
+ *
+ * If the dst is >= the image size, then...
+ * - The 4 corners are not stretched at all.
+ * - The sides are stretched in only one axis.
+ * - The center is stretched in both axes.
+ * Else, for each axis where dst < image,
+ * - The corners shrink proportionally
+ * - The sides (along the shrink axis) and center are not drawn
+ */
+ void drawImageNine(const SkImage*, const SkIRect& center, const SkRect& dst,
+ const SkPaint* paint = NULL);
/** Draw the specified bitmap, with its top/left corner at (x,y), using the
specified paint, transformed by the current matrix. Note: if the paint
@@ -815,51 +865,27 @@ public:
@param top The position of the top side of the bitmap being drawn
@param paint The paint used to draw the bitmap, or NULL
*/
- virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
- const SkPaint* paint = NULL);
+ void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
+ const SkPaint* paint = NULL);
- enum DrawBitmapRectFlags {
- kNone_DrawBitmapRectFlag = 0x0,
- /**
- * When filtering is enabled, allow the color samples outside of
- * the src rect (but still in the src bitmap) to bleed into the
- * drawn portion
- */
- kBleed_DrawBitmapRectFlag = 0x1,
- };
-
- /** Draw the specified bitmap, with the specified matrix applied (before the
- canvas' matrix is applied).
- @param bitmap The bitmap to be drawn
- @param src Optional: specify the subset of the bitmap to be drawn
- @param dst The destination rectangle where the scaled/translated
- image will be drawn
- @param paint The paint used to draw the bitmap, or NULL
- */
- virtual void drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
- const SkRect& dst,
- const SkPaint* paint = NULL,
- DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag);
-
- void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
- const SkPaint* paint = NULL) {
- this->drawBitmapRectToRect(bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag);
- }
-
- void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* isrc,
- const SkRect& dst, const SkPaint* paint = NULL,
- DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag) {
- SkRect realSrcStorage;
- SkRect* realSrcPtr = NULL;
- if (isrc) {
- realSrcStorage.set(*isrc);
- realSrcPtr = &realSrcStorage;
- }
- this->drawBitmapRectToRect(bitmap, realSrcPtr, dst, paint, flags);
- }
-
- virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m,
- const SkPaint* paint = NULL);
+ /** Draw the specified bitmap, scaling and translating so that it fills the specified
+ * dst rect. If the src rect is non-null, only that subset of the bitmap is transformed
+ * and drawn.
+ *
+ * @param bitmap The bitmap to be drawn
+ * @param src Optional: specify the subset of the bitmap to be drawn
+ * @param dst The destination rectangle where the scaled/translated
+ * bitmap will be drawn
+ * @param paint The paint used to draw the bitmap, or NULL
+ * @param constraint Control the tradeoff between speed and exactness w.r.t. the src-rect.
+ */
+ void drawBitmapRect(const SkBitmap& bitmap, const SkRect& src, const SkRect& dst,
+ const SkPaint* paint, SrcRectConstraint = kStrict_SrcRectConstraint);
+ // variant where src is SkIRect
+ void drawBitmapRect(const SkBitmap& bitmap, const SkIRect& isrc, const SkRect& dst,
+ const SkPaint* paint, SrcRectConstraint = kStrict_SrcRectConstraint);
+ void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst, const SkPaint* paint,
+ SrcRectConstraint = kStrict_SrcRectConstraint);
/**
* Draw the bitmap stretched differentially to fit into dst.
@@ -875,8 +901,8 @@ public:
* - The corners shrink proportionally
* - The sides (along the shrink axis) and center are not drawn
*/
- virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
- const SkRect& dst, const SkPaint* paint = NULL);
+ void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst,
+ const SkPaint* paint = NULL);
/** Draw the specified bitmap, with its top/left corner at (x,y),
NOT transformed by the current matrix. Note: if the paint
@@ -889,8 +915,7 @@ public:
@param top The position of the top side of the bitmap being drawn
@param paint The paint used to draw the bitmap, or NULL
*/
- virtual void drawSprite(const SkBitmap& bitmap, int left, int top,
- const SkPaint* paint = NULL);
+ void drawSprite(const SkBitmap& bitmap, int left, int top, const SkPaint* paint = NULL);
/** Draw the text, with origin at (x,y), using the specified paint.
The origin is interpreted based on the Align setting in the paint.
@@ -900,8 +925,8 @@ public:
@param y The y-coordinate of the origin of the text being drawn
@param paint The paint used for the text (e.g. color, size, style)
*/
- SK_LEGACY_DRAWTEXT_VIRTUAL void drawText(const void* text, size_t byteLength, SkScalar x,
- SkScalar y, const SkPaint& paint);
+ void drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
+ const SkPaint& paint);
/** Draw the text, with each character/glyph origin specified by the pos[]
array. The origin is interpreted by the Align setting in the paint.
@@ -910,8 +935,8 @@ public:
@param pos Array of positions, used to position each character
@param paint The paint used for the text (e.g. color, size, style)
*/
- SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosText(const void* text, size_t byteLength,
- const SkPoint pos[], const SkPaint& paint);
+ void drawPosText(const void* text, size_t byteLength, const SkPoint pos[],
+ const SkPaint& paint);
/** Draw the text, with each character/glyph origin specified by the x
coordinate taken from the xpos[] array, and the y from the constY param.
@@ -922,9 +947,8 @@ public:
@param constY The shared Y coordinate for all of the positions
@param paint The paint used for the text (e.g. color, size, style)
*/
- SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosTextH(const void* text, size_t byteLength,
- const SkScalar xpos[], SkScalar constY,
- const SkPaint& paint);
+ void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY,
+ const SkPaint& paint);
/** Draw the text, with origin at (x,y), using the specified paint, along
the specified path. The paint's Align setting determins where along the
@@ -938,8 +962,7 @@ public:
position the text
@param paint The paint used for the text
*/
- void drawTextOnPathHV(const void* text, size_t byteLength,
- const SkPath& path, SkScalar hOffset,
+ void drawTextOnPathHV(const void* text, size_t byteLength, const SkPath& path, SkScalar hOffset,
SkScalar vOffset, const SkPaint& paint);
/** Draw the text, with origin at (x,y), using the specified paint, along
@@ -952,17 +975,16 @@ public:
mapped onto the path
@param paint The paint used for the text
*/
- SK_LEGACY_DRAWTEXT_VIRTUAL void drawTextOnPath(const void* text, size_t byteLength,
- const SkPath& path, const SkMatrix* matrix,
- const SkPaint& paint);
+ void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
+ const SkMatrix* matrix, const SkPaint& paint);
- /** PRIVATE / EXPERIMENTAL -- do not call
- Perform back-end analysis/optimization of a picture. This may attach
- optimization data to the picture which can be used by a later
- drawPicture call.
- @param picture The recorded drawing commands to analyze/optimize
+ /** Draw the text blob, offset by (x,y), using the specified paint.
+ @param blob The text blob to be drawn
+ @param x The x-offset of the text being drawn
+ @param y The y-offset of the text being drawn
+ @param paint The paint used for the text (e.g. color, size, style)
*/
- void EXPERIMENTAL_optimize(const SkPicture* picture);
+ void drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint);
/** Draw the picture into this canvas. This method effective brackets the
playback of the picture's draw calls with save/restore, so the state
@@ -970,7 +992,23 @@ public:
@param picture The recorded drawing commands to playback into this
canvas.
*/
- void drawPicture(const SkPicture* picture);
+ void drawPicture(const SkPicture* picture) {
+ this->drawPicture(picture, NULL, NULL);
+ }
+
+ /**
+ * Draw the picture into this canvas.
+ *
+ * If matrix is non-null, apply that matrix to the CTM when drawing this picture. This is
+ * logically equivalent to
+ * save/concat/drawPicture/restore
+ *
+ * If paint is non-null, draw the picture into a temporary buffer, and then apply the paint's
+ * alpha/colorfilter/imagefilter/xfermode to that buffer as it is drawn to the canvas.
+ * This is logically equivalent to
+ * saveLayer(paint)/drawPicture/restore
+ */
+ void drawPicture(const SkPicture*, const SkMatrix* matrix, const SkPaint* paint);
enum VertexMode {
kTriangles_VertexMode,
@@ -1001,48 +1039,64 @@ public:
@param indexCount number of entries in the indices array (if not null)
@param paint Specifies the shader/texture if present.
*/
- virtual void drawVertices(VertexMode vmode, int vertexCount,
- const SkPoint vertices[], const SkPoint texs[],
- const SkColor colors[], SkXfermode* xmode,
- const uint16_t indices[], int indexCount,
- const SkPaint& paint);
+ void drawVertices(VertexMode vmode, int vertexCount,
+ const SkPoint vertices[], const SkPoint texs[],
+ const SkColor colors[], SkXfermode* xmode,
+ const uint16_t indices[], int indexCount,
+ const SkPaint& paint);
- /** Send a blob of data to the canvas.
- For canvases that draw, this call is effectively a no-op, as the data
- is not parsed, but just ignored. However, this call exists for
- subclasses like SkPicture's recording canvas, that can store the data
- and then play it back later (via another call to drawData).
- */
- virtual void drawData(const void* data, size_t length) {
- // do nothing. Subclasses may do something with the data
- }
+ /**
+ Draw a cubic coons patch
- /** Add comments. beginCommentGroup/endCommentGroup open/close a new group.
- Each comment added via addComment is notionally attached to its
- enclosing group. Top-level comments simply belong to no group.
+ @param cubic specifies the 4 bounding cubic bezier curves of a patch with clockwise order
+ starting at the top left corner.
+ @param colors specifies the colors for the corners which will be bilerp across the patch,
+ their order is clockwise starting at the top left corner.
+ @param texCoords specifies the texture coordinates that will be bilerp across the patch,
+ their order is the same as the colors.
+ @param xmode specifies how are the colors and the textures combined if both of them are
+ present.
+ @param paint Specifies the shader/texture if present.
*/
- virtual void beginCommentGroup(const char* description) {
- // do nothing. Subclasses may do something
- }
- virtual void addComment(const char* kywd, const char* value) {
- // do nothing. Subclasses may do something
- }
- virtual void endCommentGroup() {
- // do nothing. Subclasses may do something
+ void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
+ const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
+
+ /**
+ * Draw a set of sprites from the atlas. Each is specified by a tex rectangle in the
+ * coordinate space of the atlas, and a corresponding xform which transforms the tex rectangle
+ * into a quad.
+ *
+ * xform maps [0, 0, tex.width, tex.height] -> quad
+ *
+ * The color array is optional. When specified, each color modulates the pixels in its
+ * corresponding quad (via the specified SkXfermode::Mode).
+ *
+ * The cullRect is optional. When specified, it must be a conservative bounds of all of the
+ * resulting transformed quads, allowing the canvas to skip drawing if the cullRect does not
+ * intersect the current clip.
+ *
+ * The paint is optional. If specified, its antialiasing, alpha, color-filter, image-filter
+ * and xfermode are used to affect each of the quads.
+ */
+ void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
+ const SkColor colors[], int count, SkXfermode::Mode, const SkRect* cullRect,
+ const SkPaint* paint);
+
+ void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[], int count,
+ const SkRect* cullRect, const SkPaint* paint) {
+ this->drawAtlas(atlas, xform, tex, NULL, count, SkXfermode::kDst_Mode, cullRect, paint);
}
/**
- * With this call the client asserts that subsequent draw operations (up to the
- * matching popCull()) are fully contained within the given bounding box. The assertion
- * is not enforced, but the information might be used to quick-reject command blocks,
- * so an incorrect bounding box may result in incomplete rendering.
+ * Draw the contents of this drawable into the canvas. If the canvas is async
+ * (e.g. it is recording into a picture) then the drawable will be referenced instead,
+ * to have its draw() method called when the picture is finalized.
+ *
+ * If the intent is to force the contents of the drawable into this canvas immediately,
+ * then drawable->draw(canvas) may be called.
*/
- void pushCull(const SkRect& cullRect);
-
- /**
- * Terminates the current culling block, and restores the previous one (if any).
- */
- void popCull();
+ void drawDrawable(SkDrawable* drawable, const SkMatrix* = NULL);
+ void drawDrawable(SkDrawable*, SkScalar x, SkScalar y);
//////////////////////////////////////////////////////////////////////////
@@ -1085,25 +1139,13 @@ public:
*/
const SkMatrix& getTotalMatrix() const;
-#ifdef SK_SUPPORT_LEGACY_GETCLIPTYPE
- enum ClipType {
- kEmpty_ClipType = 0,
- kRect_ClipType,
- kComplex_ClipType
- };
- /** Returns a description of the total clip; may be cheaper than
- getting the clip and querying it directly.
- */
- virtual ClipType getClipType() const;
-#endif
-
/** Return the clip stack. The clip stack stores all the individual
* clips organized by the save/restore frame in which they were
* added.
* @return the current clip stack ("list" of individual clip elements)
*/
const SkClipStack* getClipStack() const {
- return &fClipStack;
+ return fClipStack;
}
typedef SkCanvasClipVisitor ClipVisitor;
@@ -1154,20 +1196,30 @@ public:
bool fDone;
};
- // don't call
- const SkRegion& internal_private_getTotalClip() const;
- // don't call
- void internal_private_getTotalClipAsPath(SkPath*) const;
// don't call
GrRenderTarget* internal_private_accessTopLayerRenderTarget();
+ // don't call
+ static void Internal_Private_SetIgnoreSaveLayerBounds(bool);
+ static bool Internal_Private_GetIgnoreSaveLayerBounds();
+ static void Internal_Private_SetTreatSpriteAsBitmap(bool);
+ static bool Internal_Private_GetTreatSpriteAsBitmap();
+
+ // TEMP helpers until we switch virtual over to const& for src-rect
+ void legacy_drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
+ const SkPaint* paint,
+ SrcRectConstraint constraint = kStrict_SrcRectConstraint);
+ void legacy_drawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
+ const SkPaint* paint,
+ SrcRectConstraint constraint = kStrict_SrcRectConstraint);
+
protected:
// default impl defers to getDevice()->newSurface(info)
- virtual SkSurface* onNewSurface(const SkImageInfo&);
+ virtual SkSurface* onNewSurface(const SkImageInfo&, const SkSurfaceProps&);
// default impl defers to its device
- virtual const void* onPeekPixels(SkImageInfo*, size_t* rowBytes);
- virtual void* onAccessTopLayerPixels(SkImageInfo*, size_t* rowBytes);
+ virtual bool onPeekPixels(SkPixmap*);
+ virtual bool onAccessTopLayerPixels(SkPixmap*);
// Subclass save/restore notifiers.
// Overriders should call the corresponding INHERITED method up the inheritance chain.
@@ -1182,6 +1234,7 @@ protected:
return kFullLayer_SaveLayerStrategy;
}
virtual void willRestore() {}
+ virtual void didRestore() {}
virtual void didConcat(const SkMatrix&) {}
virtual void didSetMatrix(const SkMatrix&) {}
@@ -1201,6 +1254,39 @@ protected:
const SkPath& path, const SkMatrix* matrix,
const SkPaint& paint);
+ virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
+ const SkPaint& paint);
+
+ virtual void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
+ const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
+
+ virtual void onDrawDrawable(SkDrawable*, const SkMatrix*);
+
+ virtual void onDrawPaint(const SkPaint&);
+ virtual void onDrawRect(const SkRect&, const SkPaint&);
+ virtual void onDrawOval(const SkRect&, const SkPaint&);
+ virtual void onDrawRRect(const SkRRect&, const SkPaint&);
+ virtual void onDrawPoints(PointMode, size_t count, const SkPoint pts[], const SkPaint&);
+ virtual void onDrawVertices(VertexMode, int vertexCount, const SkPoint vertices[],
+ const SkPoint texs[], const SkColor colors[], SkXfermode*,
+ const uint16_t indices[], int indexCount, const SkPaint&);
+
+ virtual void onDrawAtlas(const SkImage*, const SkRSXform[], const SkRect[], const SkColor[],
+ int count, SkXfermode::Mode, const SkRect* cull, const SkPaint*);
+ virtual void onDrawPath(const SkPath&, const SkPaint&);
+ virtual void onDrawImage(const SkImage*, SkScalar dx, SkScalar dy, const SkPaint*);
+ virtual void onDrawImageRect(const SkImage*, const SkRect*, const SkRect&, const SkPaint*,
+ SrcRectConstraint);
+ virtual void onDrawImageNine(const SkImage*, const SkIRect& center, const SkRect& dst,
+ const SkPaint*);
+
+ virtual void onDrawBitmap(const SkBitmap&, SkScalar dx, SkScalar dy, const SkPaint*);
+ virtual void onDrawBitmapRect(const SkBitmap&, const SkRect*, const SkRect&, const SkPaint*,
+ SrcRectConstraint);
+ virtual void onDrawBitmapNine(const SkBitmap&, const SkIRect& center, const SkRect& dst,
+ const SkPaint*);
+ virtual void onDrawSprite(const SkBitmap&, int left, int top, const SkPaint*);
+
enum ClipEdgeStyle {
kHard_ClipEdgeStyle,
kSoft_ClipEdgeStyle
@@ -1213,7 +1299,7 @@ protected:
virtual void onDiscard();
- virtual void onDrawPicture(const SkPicture* picture);
+ virtual void onDrawPicture(const SkPicture*, const SkMatrix*, const SkPaint*);
// Returns the canvas to be used by DrawIter. Default implementation
// returns this. Subclasses that encapsulate an indirect canvas may
@@ -1229,30 +1315,40 @@ protected:
SkIRect* intersection,
const SkImageFilter* imageFilter = NULL);
- // Called by child classes that override clipPath and clipRRect to only
- // track fast conservative clip bounds, rather than exact clips.
- void updateClipConservativelyUsingBounds(const SkRect&, SkRegion::Op,
- bool inverseFilled);
+private:
+ enum ShaderOverrideOpacity {
+ kNone_ShaderOverrideOpacity, //!< there is no overriding shader (bitmap or image)
+ kOpaque_ShaderOverrideOpacity, //!< the overriding shader is opaque
+ kNotOpaque_ShaderOverrideOpacity, //!< the overriding shader may not be opaque
+ };
// notify our surface (if we have one) that we are about to draw, so it
// can perform copy-on-write or invalidate any cached images
- void predrawNotify();
+ void predrawNotify(bool willOverwritesEntireSurface = false);
+ void predrawNotify(const SkRect* rect, const SkPaint* paint, ShaderOverrideOpacity);
+ void predrawNotify(const SkRect* rect, const SkPaint* paint, bool shaderOverrideIsOpaque) {
+ this->predrawNotify(rect, paint, shaderOverrideIsOpaque ? kOpaque_ShaderOverrideOpacity
+ : kNotOpaque_ShaderOverrideOpacity);
+ }
- virtual void onPushCull(const SkRect& cullRect);
- virtual void onPopCull();
-
-private:
class MCRec;
- SkClipStack fClipStack;
+ SkAutoTUnref fClipStack;
SkDeque fMCStack;
// points to top of stack
MCRec* fMCRec;
// the first N recs that can fit here mean we won't call malloc
- uint32_t fMCRecStorage[32];
+ enum {
+ kMCRecSize = 128, // most recent measurement
+ kMCRecCount = 32, // common depth for save/restores
+ kDeviceCMSize = 136, // most recent measurement
+ };
+ intptr_t fMCRecStorage[kMCRecSize * kMCRecCount / sizeof(intptr_t)];
+ intptr_t fDeviceCMStorage[kDeviceCMSize / sizeof(intptr_t)];
- int fSaveLayerCount; // number of successful saveLayer calls
- int fCullCount; // number of active culls
+ const SkSurfaceProps fProps;
+
+ int fSaveCount; // value returned by getSaveCount()
SkMetaData* fMetaData;
@@ -1267,25 +1363,37 @@ private:
bool fDeviceCMDirty; // cleared by updateDeviceCMCache()
void updateDeviceCMCache();
+ void doSave();
+ void checkForDeferredSave();
+
friend class SkDrawIter; // needs setupDrawForLayerDevice()
friend class AutoDrawLooper;
friend class SkLua; // needs top layer size and offset
friend class SkDebugCanvas; // needs experimental fAllowSimplifyClip
- friend class SkDeferredDevice; // needs getTopDevice()
friend class SkSurface_Raster; // needs getDevice()
+ friend class SkRecorder; // InitFlags
+ friend class SkNoSaveLayerCanvas; // InitFlags
+ friend class SkPictureImageFilter; // SkCanvas(SkBaseDevice*, SkSurfaceProps*, InitFlags)
+ friend class SkPictureRecord; // predrawNotify (why does it need it? )
- SkBaseDevice* createLayerDevice(const SkImageInfo&);
+ enum InitFlags {
+ kDefault_InitFlags = 0,
+ kConservativeRasterClip_InitFlag = 1 << 0,
+ };
+ SkCanvas(const SkIRect& bounds, InitFlags);
+ SkCanvas(SkBaseDevice* device, InitFlags);
- SkBaseDevice* init(SkBaseDevice*);
+ void resetForNextPicture(const SkIRect& bounds);
- /**
- * DEPRECATED
- *
- * Specify a device for this canvas to draw into. If it is not null, its
- * reference count is incremented. If the canvas was already holding a
- * device, its reference count is decremented. The new device is returned.
- */
- SkBaseDevice* setRootDevice(SkBaseDevice* device);
+ // needs gettotalclip()
+ friend class SkCanvasStateUtils;
+
+ // call this each time we attach ourselves to a device
+ // - constructor
+ // - internalSaveLayer
+ void setupDevice(SkBaseDevice*);
+
+ SkBaseDevice* init(SkBaseDevice*, InitFlags);
/**
* Gets the size/origin of the top level layer in global canvas coordinates. We don't want this
@@ -1294,21 +1402,15 @@ private:
SkISize getTopLayerSize() const;
SkIPoint getTopLayerOrigin() const;
- // internal methods are not virtual, so they can safely be called by other
- // canvas apis, without confusing subclasses (like SkPictureRecording)
- void internalDrawBitmap(const SkBitmap&, const SkMatrix& m, const SkPaint* paint);
void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
const SkRect& dst, const SkPaint* paint,
- DrawBitmapRectFlags flags);
- void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
- const SkRect& dst, const SkPaint* paint);
+ SrcRectConstraint);
void internalDrawPaint(const SkPaint& paint);
- int internalSaveLayer(const SkRect* bounds, const SkPaint* paint,
- SaveFlags, bool justForImageFilter, SaveLayerStrategy strategy);
- void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*);
+ void internalSaveLayer(const SkRect* bounds, const SkPaint*, SaveFlags, SaveLayerStrategy);
+ void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*, bool isBitmapDevice);
// shared by save() and saveLayer()
- int internalSave();
+ void internalSave();
void internalRestore();
static void DrawRect(const SkDraw& draw, const SkPaint& paint,
const SkRect& r, SkScalar textSize);
@@ -1316,6 +1418,17 @@ private:
const char text[], size_t byteLength,
SkScalar x, SkScalar y);
+ // only for canvasutils
+ const SkRegion& internal_private_getTotalClip() const;
+
+ /*
+ * Returns true if drawing the specified rect (or all if it is null) with the specified
+ * paint (or default if null) would overwrite the entire root device of the canvas
+ * (i.e. the canvas' surface if it had one).
+ */
+ bool wouldOverwriteEntireSurface(const SkRect*, const SkPaint*, ShaderOverrideOpacity) const;
+
+
/* These maintain a cache of the clip bounds in local coordinates,
(converted to 2s-compliment if floats are slow).
*/
@@ -1323,6 +1436,7 @@ private:
mutable bool fCachedLocalClipBoundsDirty;
bool fAllowSoftClip;
bool fAllowSimplifyClip;
+ const bool fConservativeRasterClip;
const SkRect& getLocalClipBounds() const {
if (fCachedLocalClipBoundsDirty) {
@@ -1346,9 +1460,6 @@ private:
};
#ifdef SK_DEBUG
- // The cull stack rects are in device-space
- SkTDArray fCullStack;
- void validateCull(const SkIRect&);
void validateClip() const;
#else
void validateClip() const {}
@@ -1394,28 +1505,6 @@ private:
};
#define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
-/** Stack helper class to automatically open and close a comment block
- */
-class SkAutoCommentBlock : SkNoncopyable {
-public:
- SkAutoCommentBlock(SkCanvas* canvas, const char* description) {
- fCanvas = canvas;
- if (NULL != fCanvas) {
- fCanvas->beginCommentGroup(description);
- }
- }
-
- ~SkAutoCommentBlock() {
- if (NULL != fCanvas) {
- fCanvas->endCommentGroup();
- }
- }
-
-private:
- SkCanvas* fCanvas;
-};
-#define SkAutoCommentBlock(...) SK_REQUIRE_LOCAL_VAR(SkAutoCommentBlock)
-
/**
* If the caller wants read-only access to the pixels in a canvas, it can just
* call canvas->peekPixels(), since that is the fastest way to "peek" at the
diff --git a/gfx/skia/skia/include/core/SkChunkAlloc.h b/gfx/skia/skia/include/core/SkChunkAlloc.h
index e13e2b99c6..9699842e6b 100644
--- a/gfx/skia/skia/include/core/SkChunkAlloc.h
+++ b/gfx/skia/skia/include/core/SkChunkAlloc.h
@@ -22,6 +22,11 @@ public:
* pointers.
*/
void reset();
+ /**
+ * Reset to 0 used bytes preserving as much memory as possible.
+ * This invalidates all returned pointers.
+ */
+ void rewind();
enum AllocFailType {
kReturnNil_AllocFailType,
@@ -43,7 +48,8 @@ public:
size_t totalCapacity() const { return fTotalCapacity; }
size_t totalUsed() const { return fTotalUsed; }
- int blockCount() const { return fBlockCount; }
+ SkDEBUGCODE(int blockCount() const { return fBlockCount; })
+ SkDEBUGCODE(size_t totalLost() const { return fTotalLost; })
/**
* Returns true if the specified address is within one of the chunks, and
@@ -60,9 +66,13 @@ private:
size_t fChunkSize;
size_t fTotalCapacity;
size_t fTotalUsed; // will be <= fTotalCapacity
- int fBlockCount;
+ SkDEBUGCODE(int fBlockCount;)
+ SkDEBUGCODE(size_t fTotalLost;) // will be <= fTotalCapacity
Block* newBlock(size_t bytes, AllocFailType ftype);
+ Block* addBlockIfNecessary(size_t bytes, AllocFailType ftype);
+
+ SkDEBUGCODE(void validate();)
};
#endif
diff --git a/gfx/skia/skia/include/core/SkClipStack.h b/gfx/skia/skia/include/core/SkClipStack.h
index 95e41e6220..b74e47697f 100644
--- a/gfx/skia/skia/include/core/SkClipStack.h
+++ b/gfx/skia/skia/include/core/SkClipStack.h
@@ -24,7 +24,7 @@ class SkCanvasClipVisitor;
// (i.e., the fSaveCount in force when it was added). Restores are thus
// implemented by removing clips from fDeque that have an fSaveCount larger
// then the freshly decremented count.
-class SK_API SkClipStack {
+class SK_API SkClipStack : public SkNVRefCnt {
public:
enum BoundsType {
// The bounding box contains all the pixels that can be written to
@@ -309,13 +309,6 @@ public:
BoundsType* boundType,
bool* isIntersectionOfRects = NULL) const;
- /**
- * Takes an input rect in device space and conservatively clips it to the
- * clip-stack. If false is returned then the rect does not intersect the
- * clip and is unmodified.
- */
- bool intersectRectWithClip(SkRect* devRect) const;
-
/**
* Returns true if the input rect in device space is entirely contained
* by the clip. A return value of false does not guarantee that the rect
@@ -323,6 +316,12 @@ public:
*/
bool quickContains(const SkRect& devRect) const;
+ /**
+ * Flattens the clip stack into a single SkPath. Returns true if any of
+ * the clip stack components requires anti-aliasing.
+ */
+ bool asPath(SkPath* path) const;
+
void clipDevRect(const SkIRect& ir, SkRegion::Op op) {
SkRect r;
r.set(ir);
diff --git a/gfx/skia/skia/include/core/SkColor.h b/gfx/skia/skia/include/core/SkColor.h
index 7faeca7f84..1ba1331c1a 100644
--- a/gfx/skia/skia/include/core/SkColor.h
+++ b/gfx/skia/skia/include/core/SkColor.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,11 +5,11 @@
* found in the LICENSE file.
*/
-
#ifndef SkColor_DEFINED
#define SkColor_DEFINED
#include "SkScalar.h"
+#include "SkTypes.h"
/** \file SkColor.h
@@ -161,9 +160,4 @@ SK_API SkPMColor SkPreMultiplyColor(SkColor c);
*/
typedef SkPMColor (*SkXfermodeProc)(SkPMColor src, SkPMColor dst);
-/** Define a function pointer type for combining a premultiplied src color
- and a 16bit device color.
-*/
-typedef uint16_t (*SkXfermodeProc16)(SkPMColor src, uint16_t dst);
-
#endif
diff --git a/gfx/skia/skia/include/core/SkColorFilter.h b/gfx/skia/skia/include/core/SkColorFilter.h
index 25e6bbe746..57650fbd98 100644
--- a/gfx/skia/skia/include/core/SkColorFilter.h
+++ b/gfx/skia/skia/include/core/SkColorFilter.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,17 +5,17 @@
* found in the LICENSE file.
*/
-
#ifndef SkColorFilter_DEFINED
#define SkColorFilter_DEFINED
#include "SkColor.h"
#include "SkFlattenable.h"
+#include "SkTDArray.h"
#include "SkXfermode.h"
-class SkBitmap;
-class GrEffect;
class GrContext;
+class GrFragmentProcessor;
+class SkBitmap;
/**
* ColorFilters are optional objects in the drawing pipeline. When present in
@@ -28,8 +27,6 @@ class GrContext;
*/
class SK_API SkColorFilter : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkColorFilter)
-
/**
* If the filter can be represented by a source color plus Mode, this
* returns true, and sets (if not NULL) the color and mode appropriately.
@@ -69,34 +66,27 @@ public:
@param count the number of entries in the src[] and result[] arrays
@param result written by the filter
*/
- virtual void filterSpan(const SkPMColor src[], int count,
- SkPMColor result[]) const = 0;
- /** Called with a scanline of colors, as if there was a shader installed.
- The implementation writes out its filtered version into result[].
- Note: shader and result may be the same buffer.
- @param src array of colors, possibly generated by a shader
- @param count the number of entries in the src[] and result[] arrays
- @param result written by the filter
- */
- virtual void filterSpan16(const uint16_t shader[], int count,
- uint16_t result[]) const;
+ virtual void filterSpan(const SkPMColor src[], int count, SkPMColor result[]) const = 0;
enum Flags {
- /** If set the filter methods will not change the alpha channel of the
- colors.
+ /** If set the filter methods will not change the alpha channel of the colors.
*/
kAlphaUnchanged_Flag = 0x01,
- /** If set, this subclass implements filterSpan16(). If this flag is
- set, then kAlphaUnchanged_Flag must also be set.
- */
- kHasFilter16_Flag = 0x02
};
- /** Returns the flags for this filter. Override in subclasses to return
- custom flags.
+ /** Returns the flags for this filter. Override in subclasses to return custom flags.
*/
virtual uint32_t getFlags() const { return 0; }
+ /**
+ * If this subclass can optimally createa composition with the inner filter, return it as
+ * a new filter (which the caller must unref() when it is done). If no such optimization
+ * is known, return NULL.
+ *
+ * e.g. result(color) == this_filter(inner(color))
+ */
+ virtual SkColorFilter* newComposed(const SkColorFilter* /*inner*/) const { return NULL; }
+
/**
* Apply this colorfilter to the specified SkColor. This routine handles
* converting to SkPMColor, calling the filter, and then converting back
@@ -123,10 +113,31 @@ public:
*/
static SkColorFilter* CreateLightingFilter(SkColor mul, SkColor add);
- /** A subclass may implement this factory function to work with the GPU backend. If the return
- is non-NULL then the caller owns a ref on the returned object.
+ /** Construct a colorfilter whose effect is to first apply the inner filter and then apply
+ * the outer filter to the result of the inner's.
+ * The reference counts for outer and inner are incremented.
+ *
+ * Due to internal limits, it is possible that this will return NULL, so the caller must
+ * always check.
*/
- virtual GrEffect* asNewEffect(GrContext*) const;
+ static SkColorFilter* CreateComposeFilter(SkColorFilter* outer, SkColorFilter* inner);
+
+ /**
+ * A subclass may implement this factory function to work with the GPU backend. It returns
+ * a GrFragmentProcessor that implemets the color filter in GPU shader code.
+ *
+ * The fragment processor receives a premultiplied input color and produces a premultiplied
+ * output color.
+ *
+ * A null return indicates that the color filter isn't implemented for the GPU backend.
+ */
+ virtual const GrFragmentProcessor* asFragmentProcessor(GrContext*) const {
+ return nullptr;
+ }
+
+ bool affectsTransparentBlack() const {
+ return this->filterColor(0) != 0;
+ }
SK_TO_STRING_PUREVIRT()
@@ -135,9 +146,18 @@ public:
protected:
SkColorFilter() {}
- SkColorFilter(SkReadBuffer& rb) : INHERITED(rb) {}
private:
+ /*
+ * Returns 1 if this is a single filter (not a composition of other filters), otherwise it
+ * reutrns the number of leaf-node filters in a composition. This should be the same value
+ * as the number of GrFragmentProcessors returned by asFragmentProcessors's array parameter.
+ *
+ * e.g. compose(filter, compose(compose(filter, filter), filter)) --> 4
+ */
+ virtual int privateComposedFilterCount() const { return 1; }
+ friend class SkComposeColorFilter;
+
typedef SkFlattenable INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkColorPriv.h b/gfx/skia/skia/include/core/SkColorPriv.h
index 6f23f9be14..6347660dbc 100644
--- a/gfx/skia/skia/include/core/SkColorPriv.h
+++ b/gfx/skia/skia/include/core/SkColorPriv.h
@@ -193,7 +193,7 @@ static inline unsigned Sk255To256(U8CPU value) {
/** Multiplify value by 0..256, and shift the result down 8
(i.e. return (value * alpha256) >> 8)
*/
-#define SkAlphaMul(value, alpha256) (SkMulS16(value, alpha256) >> 8)
+#define SkAlphaMul(value, alpha256) (((value) * (alpha256)) >> 8)
// The caller may want negative values, so keep all params signed (int)
// so we don't accidentally slip into unsigned math and lose the sign
@@ -213,11 +213,21 @@ static inline int SkAlphaBlend255(S16CPU src, S16CPU dst, U8CPU alpha) {
SkASSERT((int16_t)dst == dst);
SkASSERT((uint8_t)alpha == alpha);
- int prod = SkMulS16(src - dst, alpha) + 128;
+ int prod = (src - dst) * alpha + 128;
prod = (prod + (prod >> 8)) >> 8;
return dst + prod;
}
+static inline U8CPU SkUnitScalarClampToByte(SkScalar x) {
+ if (x < 0) {
+ return 0;
+ }
+ if (x >= SK_Scalar1) {
+ return 255;
+ }
+ return SkScalarToFixed(x) >> 8;
+}
+
#define SK_R16_BITS 5
#define SK_G16_BITS 6
#define SK_B16_BITS 5
@@ -281,6 +291,16 @@ static inline U16CPU SkAlphaMulRGB16(U16CPU c, unsigned scale) {
// this helper explicitly returns a clean 16bit value (but slower)
#define SkAlphaMulRGB16_ToU16(c, s) (uint16_t)SkAlphaMulRGB16(c, s)
+/** Blend pre-expanded RGB32 with 16bit color value by the 0..32 scale parameter.
+ The computation yields only 16bits of valid data, but we claim to return
+ 32bits, so that the compiler won't generate extra instructions to "clean"
+ the top 16bits.
+*/
+static inline U16CPU SkBlend32_RGB16(uint32_t src_expand, uint16_t dst, unsigned scale) {
+ uint32_t dst_expand = SkExpand_rgb_16(dst) * scale;
+ return SkCompact_rgb_16((src_expand + dst_expand) >> 5);
+}
+
/** Blend src and dst 16bit colors by the 0..256 scale parameter.
The computation yields only 16bits of valid data, but we claim
to return 32bits, so that the compiler won't generate extra instructions to
@@ -306,7 +326,8 @@ static inline void SkBlendRGB16(const uint16_t src[], uint16_t dst[],
do {
uint32_t src32 = SkExpand_rgb_16(*src++);
uint32_t dst32 = SkExpand_rgb_16(*dst);
- *dst++ = SkCompact_rgb_16(dst32 + ((src32 - dst32) * srcScale >> 5));
+ *dst++ = static_cast(
+ SkCompact_rgb_16(dst32 + ((src32 - dst32) * srcScale >> 5)));
} while (--count > 0);
}
@@ -345,21 +366,31 @@ static inline void SkBlendRGB16(const uint16_t src[], uint16_t dst[],
#define SkB32Assert(b) SkASSERT((unsigned)(b) <= SK_B32_MASK)
#ifdef SK_DEBUG
- static inline void SkPMColorAssert(SkPMColor c) {
- unsigned a = SkGetPackedA32(c);
- unsigned r = SkGetPackedR32(c);
- unsigned g = SkGetPackedG32(c);
- unsigned b = SkGetPackedB32(c);
-
- SkA32Assert(a);
- SkASSERT(r <= a);
- SkASSERT(g <= a);
- SkASSERT(b <= a);
- }
+ #define SkPMColorAssert(color_value) \
+ do { \
+ SkPMColor pm_color_value = (color_value); \
+ uint32_t alpha_color_value = SkGetPackedA32(pm_color_value); \
+ SkA32Assert(alpha_color_value); \
+ SkASSERT(SkGetPackedR32(pm_color_value) <= alpha_color_value); \
+ SkASSERT(SkGetPackedG32(pm_color_value) <= alpha_color_value); \
+ SkASSERT(SkGetPackedB32(pm_color_value) <= alpha_color_value); \
+ } while (false)
#else
#define SkPMColorAssert(c)
#endif
+static inline bool SkPMColorValid(SkPMColor c) {
+ auto a = SkGetPackedA32(c);
+ bool valid = a <= SK_A32_MASK
+ && SkGetPackedR32(c) <= a
+ && SkGetPackedG32(c) <= a
+ && SkGetPackedB32(c) <= a;
+ if (valid) {
+ SkPMColorAssert(c); // Make sure we're consistent when it counts.
+ }
+ return valid;
+}
+
/**
* Pack the components into a SkPMColor, checking (in the debug version) that
* the components are 0..255, and are already premultiplied (i.e. alpha >= color)
@@ -787,7 +818,7 @@ static inline SkPMColor16 SkPackARGB4444(unsigned a, unsigned r,
(g << SK_G4444_SHIFT) | (b << SK_B4444_SHIFT));
}
-static inline U16CPU SkAlphaMulQ4(U16CPU c, unsigned scale) {
+static inline SkPMColor16 SkAlphaMulQ4(SkPMColor16 c, int scale) {
SkASSERT(scale <= 16);
const unsigned mask = 0xF0F; //gMask_0F0F;
@@ -797,14 +828,14 @@ static inline U16CPU SkAlphaMulQ4(U16CPU c, unsigned scale) {
unsigned ag = ((c >> 4) & mask) * scale;
return (rb & mask) | (ag & ~mask);
#else
- c = (c & mask) | ((c & (mask << 4)) << 12);
- c = c * scale >> 4;
- return (c & mask) | ((c >> 12) & (mask << 4));
+ unsigned expanded_c = (c & mask) | ((c & (mask << 4)) << 12);
+ unsigned scaled_c = (expanded_c * scale) >> 4;
+ return (scaled_c & mask) | ((scaled_c >> 12) & (mask << 4));
#endif
}
/** Expand the SkPMColor16 color into a 32bit value that can be scaled all at
- once by a value up to 16. Used in conjunction with SkCompact_4444.
+ once by a value up to 16.
*/
static inline uint32_t SkExpand_4444(U16CPU c) {
SkASSERT(c == (uint16_t)c);
@@ -813,18 +844,6 @@ static inline uint32_t SkExpand_4444(U16CPU c) {
return (c & mask) | ((c & ~mask) << 12);
}
-/** Compress an expanded value (from SkExpand_4444) back down to a SkPMColor16.
- NOTE: this explicitly does not clean the top 16 bits (which may be garbage).
- It does this for speed, since if it is being written directly to 16bits of
- memory, the top 16bits will be ignored. Casting the result to uint16_t here
- would add 2 more instructions, slow us down. It is up to the caller to
- perform the cast if needed.
-*/
-static inline U16CPU SkCompact_4444(uint32_t c) {
- const unsigned mask = 0xF0F; //gMask_0F0F;
- return (c & mask) | ((c >> 12) & ~mask);
-}
-
static inline uint16_t SkSrcOver4444To16(SkPMColor16 s, uint16_t d) {
unsigned sa = SkGetPackedA4444(s);
unsigned sr = SkR4444ToR565(SkGetPackedR4444(s));
@@ -856,22 +875,6 @@ static inline uint16_t SkBlend4444To16(SkPMColor16 src, uint16_t dst, int scale1
return SkSrcOver4444To16(SkAlphaMulQ4(src, scale16), dst);
}
-static inline uint16_t SkBlend4444(SkPMColor16 src, SkPMColor16 dst, int scale16) {
- SkASSERT((unsigned)scale16 <= 16);
-
- uint32_t src32 = SkExpand_4444(src) * scale16;
- // the scaled srcAlpha is the bottom byte
-#ifdef SK_DEBUG
- {
- unsigned srcA = SkGetPackedA4444(src) * scale16;
- SkASSERT(srcA == (src32 & 0xFF));
- }
-#endif
- unsigned dstScale = SkAlpha255To256(255 - (src32 & 0xFF)) >> 4;
- uint32_t dst32 = SkExpand_4444(dst) * dstScale;
- return SkCompact_4444((src32 + dst32) >> 4);
-}
-
static inline SkPMColor SkPixel4444ToPixel32(U16CPU c) {
uint32_t d = (SkGetPackedA4444(c) << SK_A32_SHIFT) |
(SkGetPackedR4444(c) << SK_R32_SHIFT) |
diff --git a/gfx/skia/skia/include/core/SkColorShader.h b/gfx/skia/skia/include/core/SkColorShader.h
deleted file mode 100644
index 4ff7d2b01d..0000000000
--- a/gfx/skia/skia/include/core/SkColorShader.h
+++ /dev/null
@@ -1,77 +0,0 @@
-
-/*
- * Copyright 2007 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkColorShader_DEFINED
-#define SkColorShader_DEFINED
-
-#include "SkShader.h"
-
-/** \class SkColorShader
- A Shader that represents a single color. In general, this effect can be
- accomplished by just using the color field on the paint, but if an
- actual shader object is needed, this provides that feature.
-*/
-class SK_API SkColorShader : public SkShader {
-public:
- /** Create a ColorShader that ignores the color in the paint, and uses the
- specified color. Note: like all shaders, at draw time the paint's alpha
- will be respected, and is applied to the specified color.
- */
- explicit SkColorShader(SkColor c);
-
- virtual bool isOpaque() const SK_OVERRIDE;
-
- virtual size_t contextSize() const SK_OVERRIDE {
- return sizeof(ColorShaderContext);
- }
-
- class ColorShaderContext : public SkShader::Context {
- public:
- ColorShaderContext(const SkColorShader& shader, const ContextRec&);
-
- virtual uint32_t getFlags() const SK_OVERRIDE;
- virtual uint8_t getSpan16Alpha() const SK_OVERRIDE;
- virtual void shadeSpan(int x, int y, SkPMColor span[], int count) SK_OVERRIDE;
- virtual void shadeSpan16(int x, int y, uint16_t span[], int count) SK_OVERRIDE;
- virtual void shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) SK_OVERRIDE;
-
- private:
- SkPMColor fPMColor;
- uint32_t fFlags;
- uint16_t fColor16;
-
- typedef SkShader::Context INHERITED;
- };
-
- // we return false for this, use asAGradient
- virtual BitmapType asABitmap(SkBitmap* outTexture,
- SkMatrix* outMatrix,
- TileMode xy[2]) const SK_OVERRIDE;
-
- virtual GradientType asAGradient(GradientInfo* info) const SK_OVERRIDE;
-
- virtual bool asNewEffect(GrContext* context, const SkPaint& paint,
- const SkMatrix* localMatrix, GrColor* paintColor,
- GrEffect** effect) const SK_OVERRIDE;
-
- SK_TO_STRING_OVERRIDE()
- SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkColorShader)
-
-protected:
- SkColorShader(SkReadBuffer&);
- virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
- virtual Context* onCreateContext(const ContextRec&, void* storage) const SK_OVERRIDE;
-
-private:
- SkColor fColor; // ignored if fInheritColor is true
-
- typedef SkShader INHERITED;
-};
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkColorTable.h b/gfx/skia/skia/include/core/SkColorTable.h
index e4c8c86c13..ccea7ed550 100644
--- a/gfx/skia/skia/include/core/SkColorTable.h
+++ b/gfx/skia/skia/include/core/SkColorTable.h
@@ -10,6 +10,7 @@
#ifndef SkColorTable_DEFINED
#define SkColorTable_DEFINED
+#include "../private/SkOncePtr.h"
#include "SkColor.h"
#include "SkFlattenable.h"
#include "SkImageInfo.h"
@@ -18,75 +19,64 @@
SkColorTable holds an array SkPMColors (premultiplied 32-bit colors) used by
8-bit bitmaps, where the bitmap bytes are interpreted as indices into the colortable.
-*/
-class SkColorTable : public SkRefCnt {
-public:
- SK_DECLARE_INST_COUNT(SkColorTable)
- /** Makes a deep copy of colors.
+ SkColorTable is thread-safe.
+*/
+class SK_API SkColorTable : public SkRefCnt {
+public:
+ /** Copy up to 256 colors into a new SkColorTable.
*/
- SkColorTable(const SkColorTable& src);
- SkColorTable(const SkPMColor colors[], int count,
- SkAlphaType alphaType = kPremul_SkAlphaType);
+ SkColorTable(const SkPMColor colors[], int count);
virtual ~SkColorTable();
- SkAlphaType alphaType() const { return (SkAlphaType)fAlphaType; }
-
- bool isOpaque() const {
- return SkAlphaTypeIsOpaque(this->alphaType());
- }
-
/** Returns the number of colors in the table.
- */
+ */
int count() const { return fCount; }
/** Returns the specified color from the table. In the debug build, this asserts that
- the index is in range (0 <= index < count).
- */
+ * the index is in range (0 <= index < count).
+ */
SkPMColor operator[](int index) const {
- SkASSERT(fColors != NULL && (unsigned)index < fCount);
+ SkASSERT(fColors != NULL && (unsigned)index < (unsigned)fCount);
return fColors[index];
}
- /**
- * Return the array of colors for reading. This must be balanced by a call
- * to unlockColors().
+ /** Return the array of colors for reading.
*/
- const SkPMColor* lockColors() {
- SkDEBUGCODE(sk_atomic_inc(&fColorLockCount);)
- return fColors;
- }
+ const SkPMColor* readColors() const { return fColors; }
- /**
- * Balancing call to lockColors().
+ /** read16BitCache() returns the array of RGB16 colors that mirror the 32bit colors.
*/
- void unlockColors();
+ const uint16_t* read16BitCache() const;
- /** Similar to lockColors(), lock16BitCache() returns the array of
- RGB16 colors that mirror the 32bit colors. However, this function
- will return null if kColorsAreOpaque_Flag is not set.
- Also, unlike lockColors(), the returned array here cannot be modified.
- */
- const uint16_t* lock16BitCache();
- /** Balancing call to lock16BitCache().
- */
- void unlock16BitCache() {
- SkASSERT(f16BitCacheLockCount > 0);
- SkDEBUGCODE(f16BitCacheLockCount -= 1);
- }
-
- explicit SkColorTable(SkReadBuffer&);
void writeToBuffer(SkWriteBuffer&) const;
-private:
- SkPMColor* fColors;
- uint16_t* f16BitCache;
- uint16_t fCount;
- uint8_t fAlphaType;
- SkDEBUGCODE(int fColorLockCount;)
- SkDEBUGCODE(int f16BitCacheLockCount;)
+ // may return null
+ static SkColorTable* Create(SkReadBuffer&);
- void inval16BitCache();
+private:
+ enum AllocatedWithMalloc {
+ kAllocatedWithMalloc
+ };
+ // assumes ownership of colors (assumes it was allocated w/ malloc)
+ SkColorTable(SkPMColor* colors, int count, AllocatedWithMalloc);
+
+ SkPMColor* fColors;
+ SkOncePtr f16BitCache;
+ int fCount;
+
+ void init(const SkPMColor* colors, int count);
+
+ friend class SkImageGenerator;
+ // Only call if no other thread or cache has seen this table.
+ void dangerous_overwriteColors(const SkPMColor newColors[], int count) {
+ if (count < 0 || count > fCount) {
+ sk_throw();
+ }
+ // assumes that f16BitCache nas NOT been initialized yet, so we don't try to update it
+ memcpy(fColors, newColors, count * sizeof(SkPMColor));
+ fCount = count; // update fCount, in case count is smaller
+ }
typedef SkRefCnt INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkComposeShader.h b/gfx/skia/skia/include/core/SkComposeShader.h
index 3a28e1e03d..bc9d932ee5 100644
--- a/gfx/skia/skia/include/core/SkComposeShader.h
+++ b/gfx/skia/skia/include/core/SkComposeShader.h
@@ -34,7 +34,14 @@ public:
SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode = NULL);
virtual ~SkComposeShader();
- virtual size_t contextSize() const SK_OVERRIDE;
+ size_t contextSize() const override;
+
+#if SK_SUPPORT_GPU
+ const GrFragmentProcessor* asFragmentProcessor(GrContext*,
+ const SkMatrix& viewM,
+ const SkMatrix* localMatrix,
+ SkFilterQuality) const override;
+#endif
class ComposeShaderContext : public SkShader::Context {
public:
@@ -48,7 +55,7 @@ public:
virtual ~ComposeShaderContext();
- virtual void shadeSpan(int x, int y, SkPMColor[], int count) SK_OVERRIDE;
+ void shadeSpan(int x, int y, SkPMColor[], int count) override;
private:
SkShader::Context* fShaderContextA;
@@ -62,15 +69,15 @@ public:
SkShader* getShaderB() { return fShaderB; }
#endif
- virtual bool asACompose(ComposeRec* rec) const SK_OVERRIDE;
+ bool asACompose(ComposeRec* rec) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkComposeShader)
protected:
SkComposeShader(SkReadBuffer& );
- virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
- virtual Context* onCreateContext(const ContextRec&, void*) const SK_OVERRIDE;
+ void flatten(SkWriteBuffer&) const override;
+ Context* onCreateContext(const ContextRec&, void*) const override;
private:
SkShader* fShaderA;
diff --git a/gfx/skia/skia/include/core/SkData.h b/gfx/skia/skia/include/core/SkData.h
index fba2846c70..60a98e00f0 100644
--- a/gfx/skia/skia/include/core/SkData.h
+++ b/gfx/skia/skia/include/core/SkData.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2011 Google Inc.
*
@@ -6,14 +5,14 @@
* found in the LICENSE file.
*/
-
-
#ifndef SkData_DEFINED
#define SkData_DEFINED
+#include
+
#include "SkRefCnt.h"
-struct SkFILE;
+class SkStream;
/**
* SkData holds an immutable data buffer. Not only is the data immutable,
@@ -22,8 +21,6 @@ struct SkFILE;
*/
class SK_API SkData : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkData)
-
/**
* Returns the number of bytes stored.
*/
@@ -44,6 +41,19 @@ public:
return reinterpret_cast(fPtr);
}
+ /**
+ * USE WITH CAUTION.
+ * This call will assert that the refcnt is 1, as a precaution against modifying the
+ * contents when another client/thread has access to the data.
+ */
+ void* writable_data() {
+ if (fSize) {
+ // only assert we're unique if we're not empty
+ SkASSERT(this->unique());
+ }
+ return fPtr;
+ }
+
/**
* Helper to copy a range of the data into a caller-provided buffer.
* Returns the actual number of bytes copied, after clamping offset and
@@ -60,15 +70,21 @@ public:
/**
* Function that, if provided, will be called when the SkData goes out
- * of scope, allowing for custom allocation/freeing of the data.
+ * of scope, allowing for custom allocation/freeing of the data's contents.
*/
- typedef void (*ReleaseProc)(const void* ptr, size_t length, void* context);
+ typedef void (*ReleaseProc)(const void* ptr, void* context);
/**
* Create a new dataref by copying the specified data
*/
static SkData* NewWithCopy(const void* data, size_t length);
+ /**
+ * Create a new data with uninitialized contents. The caller should call writable_data()
+ * to write into the buffer, but this must be done before another ref() is made.
+ */
+ static SkData* NewUninitialized(size_t length);
+
/**
* Create a new dataref by copying the specified c-string
* (a null-terminated array of bytes). The returned SkData will have size()
@@ -78,11 +94,18 @@ public:
static SkData* NewWithCString(const char cstr[]);
/**
- * Create a new dataref, taking the data ptr as is, and using the
+ * Create a new dataref, taking the ptr as is, and using the
* releaseproc to free it. The proc may be NULL.
*/
- static SkData* NewWithProc(const void* data, size_t length,
- ReleaseProc proc, void* context);
+ static SkData* NewWithProc(const void* ptr, size_t length, ReleaseProc proc, void* context);
+
+ /**
+ * Call this when the data parameter is already const and will outlive the lifetime of the
+ * SkData. Suitable for with const globals.
+ */
+ static SkData* NewWithoutCopy(const void* data, size_t length) {
+ return NewWithProc(data, length, DummyReleaseProc, NULL);
+ }
/**
* Create a new dataref from a pointer allocated by malloc. The Data object
@@ -97,13 +120,13 @@ public:
static SkData* NewFromFileName(const char path[]);
/**
- * Create a new dataref from a SkFILE.
- * This does not take ownership of the SkFILE, nor close it.
- * The caller is free to close the SkFILE at its convenience.
- * The SkFILE must be open for reading only.
+ * Create a new dataref from a stdio FILE.
+ * This does not take ownership of the FILE, nor close it.
+ * The caller is free to close the FILE at its convenience.
+ * The FILE must be open for reading only.
* Returns NULL on failure.
*/
- static SkData* NewFromFILE(SkFILE* f);
+ static SkData* NewFromFILE(FILE* f);
/**
* Create a new dataref from a file descriptor.
@@ -114,6 +137,13 @@ public:
*/
static SkData* NewFromFD(int fd);
+ /**
+ * Attempt to read size bytes into a SkData. If the read succeeds, return the data,
+ * else return NULL. Either way the stream's cursor may have been changed as a result
+ * of calling read().
+ */
+ static SkData* NewFromStream(SkStream*, size_t size);
+
/**
* Create a new dataref using a subset of the data in the specified
* src dataref.
@@ -129,16 +159,29 @@ public:
private:
ReleaseProc fReleaseProc;
void* fReleaseProcContext;
-
- const void* fPtr;
+ void* fPtr;
size_t fSize;
SkData(const void* ptr, size_t size, ReleaseProc, void* context);
+ explicit SkData(size_t size); // inplace new/delete
virtual ~SkData();
+
+ // Objects of this type are sometimes created in a custom fashion using sk_malloc_throw and
+ // therefore must be sk_freed. We overload new to also call sk_malloc_throw so that memory
+ // can be unconditionally released using sk_free in an overloaded delete. Overloading regular
+ // new means we must also overload placement new.
+ void* operator new(size_t size) { return sk_malloc_throw(size); }
+ void* operator new(size_t, void* p) { return p; }
+ void operator delete(void* p) { sk_free(p); }
+
// Called the first time someone calls NewEmpty to initialize the singleton.
- static SkData* NewEmptyImpl();
- static void DeleteEmpty(SkData*);
+ friend SkData* sk_new_empty_data();
+
+ // shared internal factory
+ static SkData* PrivateNewWithCopy(const void* srcOrNull, size_t length);
+
+ static void DummyReleaseProc(const void*, void*) {}
typedef SkRefCnt INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkDataTable.h b/gfx/skia/skia/include/core/SkDataTable.h
index 9440000e00..798ca9c0c4 100644
--- a/gfx/skia/skia/include/core/SkDataTable.h
+++ b/gfx/skia/skia/include/core/SkDataTable.h
@@ -20,8 +20,6 @@
*/
class SK_API SkDataTable : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkDataTable)
-
/**
* Returns true if the table is empty (i.e. has no entries).
*/
diff --git a/gfx/skia/skia/include/core/SkDevice.h b/gfx/skia/skia/include/core/SkDevice.h
index 4a9edee0ec..c52c579424 100644
--- a/gfx/skia/skia/include/core/SkDevice.h
+++ b/gfx/skia/skia/include/core/SkDevice.h
@@ -9,47 +9,31 @@
#define SkDevice_DEFINED
#include "SkRefCnt.h"
-#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
-#include "SkDeviceProperties.h"
#include "SkImageFilter.h"
+#include "SkSurfaceProps.h"
+class SkBitmap;
class SkClipStack;
class SkDraw;
+class SkDrawFilter;
struct SkIRect;
class SkMatrix;
class SkMetaData;
class SkRegion;
-
class GrRenderTarget;
class SK_API SkBaseDevice : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkBaseDevice)
-
/**
* Construct a new device.
*/
- SkBaseDevice();
-
- /**
- * Construct a new device.
- */
- SkBaseDevice(const SkDeviceProperties& deviceProperties);
-
+ explicit SkBaseDevice(const SkSurfaceProps&);
virtual ~SkBaseDevice();
- SkBaseDevice* createCompatibleDevice(const SkImageInfo&);
-
SkMetaData& getMetaData();
- /** Return the image properties of the device. */
- virtual const SkDeviceProperties& getDeviceProperties() const {
- //Currently, all the properties are leaky.
- return fLeakyProperties;
- }
-
/**
* Return ImageInfo for this device. If the canvas is not backed by pixels
* (cpu or gpu), then the info's ColorType will be kUnknown_SkColorType.
@@ -67,6 +51,12 @@ public:
bounds->setXYWH(origin.x(), origin.y(), this->width(), this->height());
}
+ SkIRect getGlobalBounds() const {
+ SkIRect bounds;
+ this->getGlobalBounds(&bounds);
+ return bounds;
+ }
+
int width() const {
return this->imageInfo().width();
}
@@ -89,7 +79,22 @@ public:
bool writePixels(const SkImageInfo&, const void*, size_t rowBytes, int x, int y);
- void* accessPixels(SkImageInfo* info, size_t* rowBytes);
+ /**
+ * Try to get write-access to the pixels behind the device. If successful, this returns true
+ * and fills-out the pixmap parameter. On success it also bumps the genID of the underlying
+ * bitmap.
+ *
+ * On failure, returns false and ignores the pixmap parameter.
+ */
+ bool accessPixels(SkPixmap* pmap);
+
+ /**
+ * Try to get read-only-access to the pixels behind the device. If successful, this returns
+ * true and fills-out the pixmap parameter.
+ *
+ * On failure, returns false and ignores the pixmap parameter.
+ */
+ bool peekPixels(SkPixmap*);
/**
* Return the device's associated gpu render target, or NULL.
@@ -111,7 +116,6 @@ public:
*/
virtual void onAttachToCanvas(SkCanvas*) {
SkASSERT(!fAttachedToCanvas);
- this->lockPixels();
#ifdef SK_DEBUG
fAttachedToCanvas = true;
#endif
@@ -125,30 +129,28 @@ public:
*/
virtual void onDetachFromCanvas() {
SkASSERT(fAttachedToCanvas);
- this->unlockPixels();
#ifdef SK_DEBUG
fAttachedToCanvas = false;
#endif
};
protected:
- enum Usage {
- kGeneral_Usage,
- kSaveLayer_Usage // clear(eraseColor); }
-
/** These are called inside the per-device-layer loop for each draw call.
When these are called, we have already applied any saveLayer operations,
and are handling any looping from the paint, and any effects from the
@@ -223,7 +217,15 @@ protected:
virtual void drawBitmapRect(const SkDraw&, const SkBitmap&,
const SkRect* srcOrNull, const SkRect& dst,
const SkPaint& paint,
- SkCanvas::DrawBitmapRectFlags flags) = 0;
+ SkCanvas::SrcRectConstraint) = 0;
+ virtual void drawBitmapNine(const SkDraw&, const SkBitmap&, const SkIRect& center,
+ const SkRect& dst, const SkPaint&);
+
+ virtual void drawImage(const SkDraw&, const SkImage*, SkScalar x, SkScalar y, const SkPaint&);
+ virtual void drawImageRect(const SkDraw&, const SkImage*, const SkRect* src, const SkRect& dst,
+ const SkPaint&, SkCanvas::SrcRectConstraint);
+ virtual void drawImageNine(const SkDraw&, const SkImage*, const SkIRect& center,
+ const SkRect& dst, const SkPaint&);
/**
* Does not handle text decoration.
@@ -232,22 +234,33 @@ protected:
virtual void drawText(const SkDraw&, const void* text, size_t len,
SkScalar x, SkScalar y, const SkPaint& paint) = 0;
virtual void drawPosText(const SkDraw&, const void* text, size_t len,
- const SkScalar pos[], SkScalar constY,
- int scalarsPerPos, const SkPaint& paint) = 0;
- virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,
- const SkPath& path, const SkMatrix* matrix,
- const SkPaint& paint) = 0;
+ const SkScalar pos[], int scalarsPerPos,
+ const SkPoint& offset, const SkPaint& paint) = 0;
virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,
const SkPoint verts[], const SkPoint texs[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) = 0;
+ // default implementation unrolls the blob runs.
+ virtual void drawTextBlob(const SkDraw&, const SkTextBlob*, SkScalar x, SkScalar y,
+ const SkPaint& paint, SkDrawFilter* drawFilter);
+ // default implementation calls drawVertices
+ virtual void drawPatch(const SkDraw&, const SkPoint cubics[12], const SkColor colors[4],
+ const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
+
+ // default implementation calls drawPath
+ virtual void drawAtlas(const SkDraw&, const SkImage* atlas, const SkRSXform[], const SkRect[],
+ const SkColor[], int count, SkXfermode::Mode, const SkPaint&);
+
/** The SkDevice passed will be an SkDevice which was returned by a call to
- onCreateDevice on this device with kSaveLayer_Usage.
+ onCreateDevice on this device with kNeverTile_TileExpectation.
*/
virtual void drawDevice(const SkDraw&, SkBaseDevice*, int x, int y,
const SkPaint&) = 0;
+ virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len, const SkPath&,
+ const SkMatrix*, const SkPaint&);
+
bool readPixels(const SkImageInfo&, void* dst, size_t rowBytes, int x, int y);
///////////////////////////////////////////////////////////////////////////
@@ -258,20 +271,6 @@ protected:
*/
virtual const SkBitmap& onAccessBitmap() = 0;
- /** Called when this device is installed into a Canvas. Balanced by a call
- to unlockPixels() when the device is removed from a Canvas.
- */
- virtual void lockPixels() {}
- virtual void unlockPixels() {}
-
- /**
- * Returns true if the device allows processing of this imagefilter. If
- * false is returned, then the filter is ignored. This may happen for
- * some subclasses that do not support pixel manipulations after drawing
- * has occurred (e.g. printing). The default implementation returns true.
- */
- virtual bool allowImageFilter(const SkImageFilter*) { return true; }
-
/**
* Override and return true for filters that the device can handle
* intrinsically. Doing so means that SkCanvas will pass-through this
@@ -289,17 +288,14 @@ protected:
* it just returns false and leaves result and offset unchanged.
*/
virtual bool filterImage(const SkImageFilter*, const SkBitmap&,
- const SkImageFilter::Context& ctx,
- SkBitmap* result, SkIPoint* offset) {
+ const SkImageFilter::Context&,
+ SkBitmap* /*result*/, SkIPoint* /*offset*/) {
return false;
}
protected:
- // default impl returns NULL
- virtual SkSurface* newSurface(const SkImageInfo&);
-
- // default impl returns NULL
- virtual const void* peekPixels(SkImageInfo*, size_t* rowBytes);
+ virtual SkSurface* newSurface(const SkImageInfo&, const SkSurfaceProps&) { return NULL; }
+ virtual bool onPeekPixels(SkPixmap*) { return false; }
/**
* The caller is responsible for "pre-clipping" the dst. The impl can assume that the dst
@@ -317,24 +313,11 @@ protected:
*/
virtual bool onWritePixels(const SkImageInfo&, const void*, size_t, int x, int y);
- /**
- * Default impl returns NULL.
- */
- virtual void* onAccessPixels(SkImageInfo* info, size_t* rowBytes);
+ virtual bool onAccessPixels(SkPixmap*) { return false; }
- /**
- * Leaky properties are those which the device should be applying but it isn't.
- * These properties will be applied by the draw, when and as it can.
- * If the device does handle a property, that property should be set to the identity value
- * for that property, effectively making it non-leaky.
- */
- SkDeviceProperties fLeakyProperties;
-
- /**
- * PRIVATE / EXPERIMENTAL -- do not call
- * Construct an acceleration object and attach it to 'picture'
- */
- virtual void EXPERIMENTAL_optimize(const SkPicture* picture);
+ const SkSurfaceProps& surfaceProps() const {
+ return fSurfaceProps;
+ }
/**
* PRIVATE / EXPERIMENTAL -- do not call
@@ -346,7 +329,42 @@ protected:
* to perform some device-specific warm up tasks and then let SkCanvas
* perform the main rendering loop (by return false from here).
*/
- virtual bool EXPERIMENTAL_drawPicture(SkCanvas* canvas, const SkPicture* picture);
+ virtual bool EXPERIMENTAL_drawPicture(SkCanvas*, const SkPicture*, const SkMatrix*,
+ const SkPaint*);
+
+ struct CreateInfo {
+ static SkPixelGeometry AdjustGeometry(const SkImageInfo&, TileUsage, SkPixelGeometry);
+
+ // The constructor may change the pixel geometry based on other parameters.
+ CreateInfo(const SkImageInfo& info,
+ TileUsage tileUsage,
+ SkPixelGeometry geo,
+ bool forImageFilter = false)
+ : fInfo(info)
+ , fTileUsage(tileUsage)
+ , fPixelGeometry(AdjustGeometry(info, tileUsage, geo))
+ , fForImageFilter(forImageFilter) {}
+
+ const SkImageInfo fInfo;
+ const TileUsage fTileUsage;
+ const SkPixelGeometry fPixelGeometry;
+ const bool fForImageFilter;
+ };
+
+ /**
+ * Create a new device based on CreateInfo. If the paint is not null, then it represents a
+ * preview of how the new device will be composed with its creator device (this).
+ *
+ * The subclass may be handed this device in drawDevice(), so it must always return
+ * a device that it knows how to draw, and that it knows how to identify if it is not of the
+ * same subclass (since drawDevice is passed a SkBaseDevice*). If the subclass cannot fulfill
+ * that contract (e.g. PDF cannot support some settings on the paint) it should return NULL,
+ * and the caller may then decide to explicitly create a bitmapdevice, knowing that later
+ * it could not call drawDevice with it (but it could call drawSprite or drawBitmap).
+ */
+ virtual SkBaseDevice* onCreateDevice(const CreateInfo&, const SkPaint*) {
+ return NULL;
+ }
private:
friend class SkCanvas;
@@ -354,8 +372,8 @@ private:
friend class SkDraw;
friend class SkDrawIter;
friend class SkDeviceFilteredPaint;
- friend class SkDeviceImageFilterProxy;
- friend class SkDeferredDevice; // for newSurface
+ friend class SkImageFilter::DeviceProxy;
+ friend class SkNoPixelsBitmapDevice;
friend class SkSurface_Raster;
@@ -365,21 +383,20 @@ private:
// TODO: move to SkBitmapDevice
virtual void replaceBitmapBackendForRasterSurface(const SkBitmap&) {}
+ virtual bool forceConservativeRasterClip() const { return false; }
+
// just called by SkCanvas when built as a layer
void setOrigin(int x, int y) { fOrigin.set(x, y); }
- // just called by SkCanvas for saveLayer
- SkBaseDevice* createCompatibleDeviceForSaveLayer(const SkImageInfo&);
-
- virtual SkBaseDevice* onCreateDevice(const SkImageInfo&, Usage) {
- return NULL;
- }
/** Causes any deferred drawing to the device to be completed.
*/
virtual void flush() {}
+ virtual SkImageFilter::Cache* getImageFilterCache() { return NULL; }
+
SkIPoint fOrigin;
SkMetaData* fMetaData;
+ SkSurfaceProps fSurfaceProps;
#ifdef SK_DEBUG
bool fAttachedToCanvas;
diff --git a/gfx/skia/skia/include/core/SkDeviceProperties.h b/gfx/skia/skia/include/core/SkDeviceProperties.h
deleted file mode 100644
index 80e0177650..0000000000
--- a/gfx/skia/skia/include/core/SkDeviceProperties.h
+++ /dev/null
@@ -1,103 +0,0 @@
-#ifndef SkDeviceProperties_DEFINED
-#define SkDeviceProperties_DEFINED
-
-//TODO: get everyone to stop using SkFontLCDConfig::SetSubpixel* and remove this import.
-#include "SkFontLCDConfig.h"
-
-struct SkDeviceProperties {
- struct Geometry {
- /** The orientation of the pixel specifies the interpretation of the
- * layout. If the orientation is horizontal, the layout is interpreted as
- * left to right. It the orientation is vertical, the layout is
- * interpreted top to bottom (rotated 90deg cw from horizontal).
- */
- enum Orientation {
- kUnknown_Orientation = 0x0,
- kKnown_Orientation = 0x2,
-
- kHorizontal_Orientation = 0x2, //!< this is the default
- kVertical_Orientation = 0x3,
-
- kOrientationMask = 0x3,
- };
-
- /** The layout of the pixel specifies its subpixel geometry.
- *
- * kUnknown_Layout means that the subpixel elements are not spatially
- * separated in any known or usable fashion.
- */
- enum Layout {
- kUnknown_Layout = 0x0,
- kKnown_Layout = 0x8,
-
- kRGB_Layout = 0x8, //!< this is the default
- kBGR_Layout = 0xC,
-
- kLayoutMask = 0xC,
- };
-
- Orientation getOrientation() {
- return static_cast(fGeometry & kOrientationMask);
- }
- Layout getLayout() {
- return static_cast(fGeometry & kLayoutMask);
- }
-
- bool isOrientationKnown() {
- return SkToBool(fGeometry & kKnown_Orientation);
- }
- bool isLayoutKnown() {
- return SkToBool(fGeometry & kKnown_Layout);
- }
-
- private:
- //TODO: get everyone to stop using SkFontLCDConfig::SetSubpixel* and replace these calls with constants.
- static Orientation fromOldOrientation(SkFontLCDConfig::LCDOrientation orientation) {
- switch (orientation) {
- case SkFontLCDConfig::kHorizontal_LCDOrientation: return kHorizontal_Orientation;
- case SkFontLCDConfig::kVertical_LCDOrientation: return kVertical_Orientation;
- default: return kUnknown_Orientation;
- }
- }
- static Layout fromOldLayout(SkFontLCDConfig::LCDOrder order) {
- switch (order) {
- case SkFontLCDConfig::kRGB_LCDOrder: return kRGB_Layout;
- case SkFontLCDConfig::kBGR_LCDOrder: return kBGR_Layout;
- default: return kUnknown_Layout;
- }
- }
- public:
- static Geometry MakeDefault() {
- Orientation orientation = fromOldOrientation(SkFontLCDConfig::GetSubpixelOrientation()); //kHorizontal_Orientation
- Layout layout = fromOldLayout(SkFontLCDConfig::GetSubpixelOrder()); //kRGB_Layout
- Geometry ret = { SkToU8(orientation | layout) };
- return ret;
- }
-
- static Geometry Make(Orientation orientation, Layout layout) {
- Geometry ret = { SkToU8(orientation | layout) };
- return ret;
- }
-
- uint8_t fGeometry;
- };
-
- static SkDeviceProperties MakeDefault() {
- SkDeviceProperties ret = { Geometry::MakeDefault(), SK_GAMMA_EXPONENT };
- return ret;
- }
-
- static SkDeviceProperties Make(Geometry geometry, SkScalar gamma) {
- SkDeviceProperties ret = { geometry, gamma };
- return ret;
- }
-
- /** Each pixel of an image will have some number of channels.
- * Can the layout of those channels be exploited? */
- Geometry fGeometry;
-
- /** Represents the color space of the image. This is a woefully inadequate beginning. */
- SkScalar fGamma;
-};
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkDocument.h b/gfx/skia/skia/include/core/SkDocument.h
index dbf4bc5957..316d15a253 100644
--- a/gfx/skia/skia/include/core/SkDocument.h
+++ b/gfx/skia/skia/include/core/SkDocument.h
@@ -12,6 +12,8 @@
#include "SkPicture.h"
#include "SkRect.h"
#include "SkRefCnt.h"
+#include "SkString.h"
+#include "SkTime.h"
class SkCanvas;
class SkWStream;
@@ -30,56 +32,50 @@ class SkWStream;
* c. doc->endPage();
* 3. Close the document with doc->close().
*/
-class SkDocument : public SkRefCnt {
+class SK_API SkDocument : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkDocument)
+ /**
+ * Create a PDF-backed document, writing the results into a SkWStream.
+ *
+ * PDF pages are sized in point units. 1 pt == 1/72 inch == 127/360 mm.
+ *
+ * @param SkWStream* A PDF document will be written to this
+ * stream. The document may write to the stream at
+ * anytime during its lifetime, until either close() is
+ * called or the document is deleted.
+ * @param dpi The DPI (pixels-per-inch) at which features without
+ * native PDF support will be rasterized (e.g. draw image
+ * with perspective, draw text with perspective, ...) A
+ * larger DPI would create a PDF that reflects the
+ * original intent with better fidelity, but it can make
+ * for larger PDF files too, which would use more memory
+ * while rendering, and it would be slower to be processed
+ * or sent online or to printer.
+ * @returns NULL if there is an error, otherwise a newly created
+ * PDF-backed SkDocument.
+ */
+ static SkDocument* CreatePDF(SkWStream*,
+ SkScalar dpi = SK_ScalarDefaultRasterDPI);
/**
* Create a PDF-backed document, writing the results into a file.
- * If there is an error trying to create the doc, returns NULL.
- * encoder sets the DCTEncoder for images, to encode a bitmap
- * as JPEG (DCT).
- * rasterDpi - the DPI at which features without native PDF support
- * will be rasterized (e.g. draw image with perspective,
- * draw text with perspective, ...)
- * A larger DPI would create a PDF that reflects the original
- * intent with better fidelity, but it can make for larger
- * PDF files too, which would use more memory while rendering,
- * and it would be slower to be processed or sent online or
- * to printer.
*/
- static SkDocument* CreatePDF(
- const char filename[],
- SkPicture::EncodeBitmap encoder = NULL,
- SkScalar rasterDpi = SK_ScalarDefaultRasterDPI);
+ static SkDocument* CreatePDF(const char outputFilePath[],
+ SkScalar dpi = SK_ScalarDefaultRasterDPI);
/**
- * Create a PDF-backed document, writing the results into a stream.
- * If there is an error trying to create the doc, returns NULL.
- *
- * The document may write to the stream at anytime during its lifetime,
- * until either close() is called or the document is deleted. Once close()
- * has been called, and all of the data has been written to the stream,
- * if there is a Done proc provided, it will be called with the stream.
- * The proc can delete the stream, or whatever it needs to do.
- * encoder sets the DCTEncoder for images, to encode a bitmap
- * as JPEG (DCT).
- * Done - clean up method intended to allow deletion of the stream.
- * Its aborted parameter is true if the cleanup is due to an abort
- * call. It is false otherwise.
- * rasterDpi - the DPI at which features without native PDF support
- * will be rasterized (e.g. draw image with perspective,
- * draw text with perspective, ...)
- * A larger DPI would create a PDF that reflects the original
- * intent with better fidelity, but it can make for larger
- * PDF files too, which would use more memory while rendering,
- * and it would be slower to be processed or sent online or
- * to printer. */
- static SkDocument* CreatePDF(
- SkWStream*, void (*Done)(SkWStream*,bool aborted) = NULL,
- SkPicture::EncodeBitmap encoder = NULL,
- SkScalar rasterDpi = SK_ScalarDefaultRasterDPI);
+ * Create a XPS-backed document, writing the results into the stream.
+ * Returns NULL if XPS is not supported.
+ */
+ static SkDocument* CreateXPS(SkWStream* stream,
+ SkScalar dpi = SK_ScalarDefaultRasterDPI);
+ /**
+ * Create a XPS-backed document, writing the results into a file.
+ * Returns NULL if XPS is not supported.
+ */
+ static SkDocument* CreateXPS(const char path[],
+ SkScalar dpi = SK_ScalarDefaultRasterDPI);
/**
* Begin a new page for the document, returning the canvas that will draw
* into the page. The document owns this canvas, and it will go out of
@@ -110,8 +106,36 @@ public:
*/
void abort();
+ /**
+ * Set the document's metadata, if supported by the document
+ * type. The creationDate and modifiedDate parameters can be
+ * nullptr. For example:
+ *
+ * SkDocument* make_doc(SkWStream* output) {
+ * SkTArray info;
+ * info.emplace_back(SkString("Title"), SkString("..."));
+ * info.emplace_back(SkString("Author"), SkString("..."));
+ * info.emplace_back(SkString("Subject"), SkString("..."));
+ * info.emplace_back(SkString("Keywords"), SkString("..."));
+ * info.emplace_back(SkString("Creator"), SkString("..."));
+ * SkTime::DateTime now;
+ * SkTime::GetDateTime(&now);
+ * SkDocument* doc = SkDocument::CreatePDF(output);
+ * doc->setMetadata(info, &now, &now);
+ * return doc;
+ * }
+ */
+ struct Attribute {
+ SkString fKey, fValue;
+ Attribute(const SkString& k, const SkString& v) : fKey(k), fValue(v) {}
+ };
+ virtual void setMetadata(const SkTArray&,
+ const SkTime::DateTime* /* creationDate */,
+ const SkTime::DateTime* /* modifiedDate */) {}
+
protected:
SkDocument(SkWStream*, void (*)(SkWStream*, bool aborted));
+
// note: subclasses must call close() in their destructor, as the base class
// cannot do this for them.
virtual ~SkDocument();
@@ -122,6 +146,9 @@ protected:
virtual bool onClose(SkWStream*) = 0;
virtual void onAbort() = 0;
+ // Allows subclasses to write to the stream as pages are written.
+ SkWStream* getStream() { return fStream; }
+
enum State {
kBetweenPages_State,
kInPage_State,
diff --git a/gfx/skia/skia/include/core/SkDraw.h b/gfx/skia/skia/include/core/SkDraw.h
index 918f2335ea..b8cf8027dd 100644
--- a/gfx/skia/skia/include/core/SkDraw.h
+++ b/gfx/skia/skia/include/core/SkDraw.h
@@ -17,6 +17,7 @@
class SkBitmap;
class SkClipStack;
class SkBaseDevice;
+class SkBlitter;
class SkMatrix;
class SkPath;
class SkRegion;
@@ -33,7 +34,11 @@ public:
void drawPaint(const SkPaint&) const;
void drawPoints(SkCanvas::PointMode, size_t count, const SkPoint[],
const SkPaint&, bool forceUseDevice = false) const;
- void drawRect(const SkRect&, const SkPaint&) const;
+ void drawRect(const SkRect& prePaintRect, const SkPaint&, const SkMatrix* paintMatrix,
+ const SkRect* postPaintRect) const;
+ void drawRect(const SkRect& rect, const SkPaint& paint) const {
+ this->drawRect(rect, paint, NULL, NULL);
+ }
void drawRRect(const SkRRect&, const SkPaint&) const;
/**
* To save on mallocs, we allow a flag that tells us that srcPath is
@@ -49,19 +54,20 @@ public:
this->drawPath(path, paint, prePathMatrix, pathIsMutable, false);
}
- void drawPath(const SkPath& path, const SkPaint& paint) const {
- this->drawPath(path, paint, NULL, false, false);
+ void drawPath(const SkPath& path, const SkPaint& paint,
+ SkBlitter* customBlitter = NULL) const {
+ this->drawPath(path, paint, NULL, false, false, customBlitter);
}
- void drawBitmap(const SkBitmap&, const SkMatrix&, const SkPaint&) const;
+ /* If dstOrNull is null, computes a dst by mapping the bitmap's bounds through the matrix. */
+ void drawBitmap(const SkBitmap&, const SkMatrix&, const SkRect* dstOrNull,
+ const SkPaint&) const;
void drawSprite(const SkBitmap&, int x, int y, const SkPaint&) const;
void drawText(const char text[], size_t byteLength, SkScalar x,
SkScalar y, const SkPaint& paint) const;
void drawPosText(const char text[], size_t byteLength,
- const SkScalar pos[], SkScalar constY,
- int scalarsPerPosition, const SkPaint& paint) const;
- void drawTextOnPath(const char text[], size_t byteLength,
- const SkPath&, const SkMatrix*, const SkPaint&) const;
+ const SkScalar pos[], int scalarsPerPosition,
+ const SkPoint& offset, const SkPaint& paint) const;
void drawVertices(SkCanvas::VertexMode mode, int count,
const SkPoint vertices[], const SkPoint textures[],
const SkColor colors[], SkXfermode* xmode,
@@ -74,8 +80,9 @@ public:
*
* Only device A8 is supported right now.
*/
- void drawPathCoverage(const SkPath& src, const SkPaint& paint) const {
- this->drawPath(src, paint, NULL, false, true);
+ void drawPathCoverage(const SkPath& src, const SkPaint& paint,
+ SkBlitter* customBlitter = NULL) const {
+ this->drawPath(src, paint, NULL, false, true, customBlitter);
}
/** Helper function that creates a mask from a path and an optional maskfilter.
@@ -110,15 +117,16 @@ public:
void drawText_asPaths(const char text[], size_t byteLength,
SkScalar x, SkScalar y, const SkPaint&) const;
void drawPosText_asPaths(const char text[], size_t byteLength,
- const SkScalar pos[], SkScalar constY,
- int scalarsPerPosition, const SkPaint&) const;
+ const SkScalar pos[], int scalarsPerPosition,
+ const SkPoint& offset, const SkPaint&) const;
private:
void drawDevMask(const SkMask& mask, const SkPaint&) const;
void drawBitmapAsMask(const SkBitmap&, const SkPaint&) const;
void drawPath(const SkPath&, const SkPaint&, const SkMatrix* preMatrix,
- bool pathIsMutable, bool drawCoverage) const;
+ bool pathIsMutable, bool drawCoverage,
+ SkBlitter* customBlitter = NULL) const;
/**
* Return the current clip bounds, in local coordinates, with slop to account
@@ -132,14 +140,13 @@ private:
computeConservativeLocalClipBounds(SkRect* bounds) const;
public:
- const SkBitmap* fBitmap; // required
+ SkPixmap fDst;
const SkMatrix* fMatrix; // required
const SkRegion* fClip; // DEPRECATED
const SkRasterClip* fRC; // required
const SkClipStack* fClipStack; // optional
SkBaseDevice* fDevice; // optional
- SkDrawProcs* fProcs; // optional
#ifdef SK_DEBUG
void validate() const;
diff --git a/gfx/skia/skia/include/core/SkDrawFilter.h b/gfx/skia/skia/include/core/SkDrawFilter.h
index 52cbba9d20..865df5f1e1 100644
--- a/gfx/skia/skia/include/core/SkDrawFilter.h
+++ b/gfx/skia/skia/include/core/SkDrawFilter.h
@@ -23,8 +23,6 @@ class SkPaint;
*/
class SK_API SkDrawFilter : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkDrawFilter)
-
enum Type {
kPaint_Type,
kPoint_Type,
diff --git a/gfx/skia/skia/include/core/SkDrawLooper.h b/gfx/skia/skia/include/core/SkDrawLooper.h
index b92baccc08..28d7d8beef 100644
--- a/gfx/skia/skia/include/core/SkDrawLooper.h
+++ b/gfx/skia/skia/include/core/SkDrawLooper.h
@@ -30,8 +30,6 @@ class SkString;
*/
class SK_API SkDrawLooper : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkDrawLooper)
-
/**
* Holds state during a draw. Users call next() until it returns false.
*
@@ -87,9 +85,8 @@ public:
* storage rect, where the storage rect is with the union of the src rect
* and the looper's bounding rect.
*/
- virtual bool canComputeFastBounds(const SkPaint& paint) const;
- virtual void computeFastBounds(const SkPaint& paint,
- const SkRect& src, SkRect* dst) const;
+ bool canComputeFastBounds(const SkPaint& paint) const;
+ void computeFastBounds(const SkPaint& paint, const SkRect& src, SkRect* dst) const;
struct BlurShadowRec {
SkScalar fSigma;
@@ -114,7 +111,6 @@ public:
protected:
SkDrawLooper() {}
- SkDrawLooper(SkReadBuffer& buffer) : INHERITED(buffer) {}
private:
typedef SkFlattenable INHERITED;
diff --git a/gfx/skia/skia/include/core/SkDrawPictureCallback.h b/gfx/skia/skia/include/core/SkDrawPictureCallback.h
deleted file mode 100644
index e86a227e62..0000000000
--- a/gfx/skia/skia/include/core/SkDrawPictureCallback.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2014 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkDrawPictureCallback_DEFINED
-#define SkDrawPictureCallback_DEFINED
-
-/**
- * Subclasses of this can be passed to canvas.drawPicture(). During the drawing
- * of the picture, this callback will periodically be invoked. If its
- * abortDrawing() returns true, then picture playback will be interrupted.
- *
- * The resulting drawing is undefined, as there is no guarantee how often the
- * callback will be invoked. If the abort happens inside some level of nested
- * calls to save(), restore will automatically be called to return the state
- * to the same level it was before the drawPicture call was made.
- */
-class SK_API SkDrawPictureCallback {
-public:
- SkDrawPictureCallback() {}
- virtual ~SkDrawPictureCallback() {}
-
- virtual bool abortDrawing() = 0;
-};
-
-#endif//SkDrawPictureCallback_DEFINED
diff --git a/gfx/skia/skia/include/core/SkDrawable.h b/gfx/skia/skia/include/core/SkDrawable.h
new file mode 100644
index 0000000000..2f0a62d8b5
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkDrawable.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkDrawable_DEFINED
+#define SkDrawable_DEFINED
+
+#include "SkRefCnt.h"
+
+class SkCanvas;
+class SkPicture;
+struct SkRect;
+
+/**
+ * Base-class for objects that draw into SkCanvas.
+ *
+ * The object has a generation ID, which is guaranteed to be unique across all drawables. To
+ * allow for clients of the drawable that may want to cache the results, the drawable must
+ * change its generation ID whenever its internal state changes such that it will draw differently.
+ */
+class SkDrawable : public SkRefCnt {
+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,
+ * and the current matrix and clip settings will not be changed.
+ */
+ void draw(SkCanvas*, const SkMatrix* = NULL);
+ void draw(SkCanvas*, SkScalar x, SkScalar y);
+
+ SkPicture* newPictureSnapshot();
+
+ /**
+ * Return a unique value for this instance. If two calls to this return the same value,
+ * it is presumed that calling the draw() method will render the same thing as well.
+ *
+ * Subclasses that change their state should call notifyDrawingChanged() to ensure that
+ * a new value will be returned the next time it is called.
+ */
+ uint32_t getGenerationID();
+
+ /**
+ * Return the (conservative) bounds of what the drawable will draw. If the drawable can
+ * change what it draws (e.g. animation or in response to some external change), then this
+ * must return a bounds that is always valid for all possible states.
+ */
+ SkRect getBounds();
+
+ /**
+ * Calling this invalidates the previous generation ID, and causes a new one to be computed
+ * the next time getGenerationID() is called. Typically this is called by the object itself,
+ * in response to its internal state changing.
+ */
+ void notifyDrawingChanged();
+
+protected:
+ virtual SkRect onGetBounds() = 0;
+ virtual void onDraw(SkCanvas*) = 0;
+
+ /**
+ * 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
+ * of their drawable. Note: this picture must draw the same as what would be drawn from
+ * onDraw().
+ */
+ virtual SkPicture* onNewPictureSnapshot();
+
+private:
+ int32_t fGenerationID;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkDynamicAnnotations.h b/gfx/skia/skia/include/core/SkDynamicAnnotations.h
deleted file mode 100644
index 422d98db43..0000000000
--- a/gfx/skia/skia/include/core/SkDynamicAnnotations.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2014 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkDynamicAnnotations_DEFINED
-#define SkDynamicAnnotations_DEFINED
-
-// This file contains macros used to send out-of-band signals to dynamic instrumentation systems,
-// namely thread sanitizer. This is a cut-down version of the full dynamic_annotations library with
-// only the features used by Skia.
-
-#if SK_DYNAMIC_ANNOTATIONS_ENABLED
-
-extern "C" {
-// TSAN provides these hooks.
-void AnnotateIgnoreReadsBegin(const char* file, int line);
-void AnnotateIgnoreReadsEnd(const char* file, int line);
-void AnnotateIgnoreWritesBegin(const char* file, int line);
-void AnnotateIgnoreWritesEnd(const char* file, int line);
-void AnnotateBenignRaceSized(const char* file, int line,
- const volatile void* addr, long size, const char* desc);
-} // extern "C"
-
-// SK_ANNOTATE_UNPROTECTED_READ can wrap any variable read to tell TSAN to ignore that it appears to
-// be a racy read. This should be used only when we can make an external guarantee that though this
-// particular read is racy, it is being used as part of a mechanism which is thread safe. Examples:
-// - the first check in double-checked locking;
-// - checking if a ref count is equal to 1.
-// Note that in both these cases, we must still add terrifyingly subtle memory barriers to provide
-// that overall thread safety guarantee. Using this macro to shut TSAN up without providing such an
-// external guarantee is pretty much never correct.
-template
-inline T SK_ANNOTATE_UNPROTECTED_READ(const volatile T& x) {
- AnnotateIgnoreReadsBegin(__FILE__, __LINE__);
- T read = x;
- AnnotateIgnoreReadsEnd(__FILE__, __LINE__);
- return read;
-}
-
-// Like SK_ANNOTATE_UNPROTECTED_READ, but for writes.
-template
-inline void SK_ANNOTATE_UNPROTECTED_WRITE(T* ptr, const volatile T& val) {
- AnnotateIgnoreWritesBegin(__FILE__, __LINE__);
- *ptr = val;
- AnnotateIgnoreWritesEnd(__FILE__, __LINE__);
-}
-
-// Ignore racy reads and racy writes to this pointer, indefinitely.
-// If at all possible, use the more precise SK_ANNOTATE_UNPROTECTED_READ.
-template
-void SK_ANNOTATE_BENIGN_RACE(T* ptr) {
- AnnotateBenignRaceSized(__FILE__, __LINE__, ptr, sizeof(*ptr), "SK_ANNOTATE_BENIGN_RACE");
-}
-
-#else // !SK_DYNAMIC_ANNOTATIONS_ENABLED
-
-#define SK_ANNOTATE_UNPROTECTED_READ(x) (x)
-#define SK_ANNOTATE_UNPROTECTED_WRITE(ptr, val) *(ptr) = (val)
-#define SK_ANNOTATE_BENIGN_RACE(ptr)
-
-#endif
-
-// Can be used to wrap values that are intentionally racy, usually small mutable cached values, e.g.
-// - SkMatrix type mask
-// - SkPixelRef genIDs
-template
-class SkTRacy {
-public:
- operator const T() const {
- return SK_ANNOTATE_UNPROTECTED_READ(fVal);
- }
-
- SkTRacy& operator=(const T& val) {
- SK_ANNOTATE_UNPROTECTED_WRITE(&fVal, val);
- return *this;
- }
-
-private:
- T fVal;
-};
-
-// This is like SkTRacy, but allows you to return the value by reference.
-// TSAN is better at suppressing SkTRacy than SkTRacyReffable, so use SkTRacy when possible.
-//
-// We use this for SkPathRef bounds, which is an SkRect we pass around by reference publically.
-template
-class SkTRacyReffable {
-public:
- SkTRacyReffable() { SK_ANNOTATE_BENIGN_RACE(&fVal); }
-
- operator const T&() const {
- return fVal;
- }
-
- SkTRacyReffable& operator=(const T& val) {
- fVal = val;
- return *this;
- }
-
- const T* get() const { return &fVal; }
- T* get() { return &fVal; }
-
- const T* operator->() const { return &fVal; }
- T* operator->() { return &fVal; }
-
-private:
- T fVal;
-};
-
-#endif//SkDynamicAnnotations_DEFINED
diff --git a/gfx/skia/skia/include/core/SkEndian.h b/gfx/skia/skia/include/core/SkEndian.h
deleted file mode 100644
index 0955fcc505..0000000000
--- a/gfx/skia/skia/include/core/SkEndian.h
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright 2006 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkEndian_DEFINED
-#define SkEndian_DEFINED
-
-#include "SkTypes.h"
-
-/** \file SkEndian.h
-
- Macros and helper functions for handling 16 and 32 bit values in
- big and little endian formats.
-*/
-
-#if defined(SK_CPU_LENDIAN) && defined(SK_CPU_BENDIAN)
- #error "can't have both LENDIAN and BENDIAN defined"
-#endif
-
-#if !defined(SK_CPU_LENDIAN) && !defined(SK_CPU_BENDIAN)
- #error "need either LENDIAN or BENDIAN defined"
-#endif
-
-/** Swap the two bytes in the low 16bits of the parameters.
- e.g. 0x1234 -> 0x3412
-*/
-static inline uint16_t SkEndianSwap16(uint16_t value) {
- return static_cast((value >> 8) | (value << 8));
-}
-
-template struct SkTEndianSwap16 {
- static const uint16_t value = static_cast((N >> 8) | ((N & 0xFF) << 8));
-};
-
-/** Vector version of SkEndianSwap16(), which swaps the
- low two bytes of each value in the array.
-*/
-static inline void SkEndianSwap16s(uint16_t array[], int count) {
- SkASSERT(count == 0 || array != NULL);
-
- while (--count >= 0) {
- *array = SkEndianSwap16(*array);
- array += 1;
- }
-}
-
-/** Reverse all 4 bytes in a 32bit value.
- e.g. 0x12345678 -> 0x78563412
-*/
-static inline uint32_t SkEndianSwap32(uint32_t value) {
- return ((value & 0xFF) << 24) |
- ((value & 0xFF00) << 8) |
- ((value & 0xFF0000) >> 8) |
- (value >> 24);
-}
-
-template struct SkTEndianSwap32 {
- static const uint32_t value = ((N & 0xFF) << 24) |
- ((N & 0xFF00) << 8) |
- ((N & 0xFF0000) >> 8) |
- (N >> 24);
-};
-
-/** Vector version of SkEndianSwap32(), which swaps the
- bytes of each value in the array.
-*/
-static inline void SkEndianSwap32s(uint32_t array[], int count) {
- SkASSERT(count == 0 || array != NULL);
-
- while (--count >= 0) {
- *array = SkEndianSwap32(*array);
- array += 1;
- }
-}
-
-/** Reverse all 8 bytes in a 64bit value.
- e.g. 0x1122334455667788 -> 0x8877665544332211
-*/
-static inline uint64_t SkEndianSwap64(uint64_t value) {
- return (((value & 0x00000000000000FFULL) << (8*7)) |
- ((value & 0x000000000000FF00ULL) << (8*5)) |
- ((value & 0x0000000000FF0000ULL) << (8*3)) |
- ((value & 0x00000000FF000000ULL) << (8*1)) |
- ((value & 0x000000FF00000000ULL) >> (8*1)) |
- ((value & 0x0000FF0000000000ULL) >> (8*3)) |
- ((value & 0x00FF000000000000ULL) >> (8*5)) |
- ((value) >> (8*7)));
-}
-template struct SkTEndianSwap64 {
- static const uint64_t value = (((N & 0x00000000000000FFULL) << (8*7)) |
- ((N & 0x000000000000FF00ULL) << (8*5)) |
- ((N & 0x0000000000FF0000ULL) << (8*3)) |
- ((N & 0x00000000FF000000ULL) << (8*1)) |
- ((N & 0x000000FF00000000ULL) >> (8*1)) |
- ((N & 0x0000FF0000000000ULL) >> (8*3)) |
- ((N & 0x00FF000000000000ULL) >> (8*5)) |
- ((N) >> (8*7)));
-};
-
-/** Vector version of SkEndianSwap64(), which swaps the
- bytes of each value in the array.
-*/
-static inline void SkEndianSwap64s(uint64_t array[], int count) {
- SkASSERT(count == 0 || array != NULL);
-
- while (--count >= 0) {
- *array = SkEndianSwap64(*array);
- array += 1;
- }
-}
-
-#ifdef SK_CPU_LENDIAN
- #define SkEndian_SwapBE16(n) SkEndianSwap16(n)
- #define SkEndian_SwapBE32(n) SkEndianSwap32(n)
- #define SkEndian_SwapBE64(n) SkEndianSwap64(n)
- #define SkEndian_SwapLE16(n) (n)
- #define SkEndian_SwapLE32(n) (n)
- #define SkEndian_SwapLE64(n) (n)
-
- #define SkTEndian_SwapBE16(n) SkTEndianSwap16::value
- #define SkTEndian_SwapBE32(n) SkTEndianSwap32::value
- #define SkTEndian_SwapBE64(n) SkTEndianSwap64::value
- #define SkTEndian_SwapLE16(n) (n)
- #define SkTEndian_SwapLE32(n) (n)
- #define SkTEndian_SwapLE64(n) (n)
-#else // SK_CPU_BENDIAN
- #define SkEndian_SwapBE16(n) (n)
- #define SkEndian_SwapBE32(n) (n)
- #define SkEndian_SwapBE64(n) (n)
- #define SkEndian_SwapLE16(n) SkEndianSwap16(n)
- #define SkEndian_SwapLE32(n) SkEndianSwap32(n)
- #define SkEndian_SwapLE64(n) SkEndianSwap64(n)
-
- #define SkTEndian_SwapBE16(n) (n)
- #define SkTEndian_SwapBE32(n) (n)
- #define SkTEndian_SwapBE64(n) (n)
- #define SkTEndian_SwapLE16(n) SkTEndianSwap16::value
- #define SkTEndian_SwapLE32(n) SkTEndianSwap32::value
- #define SkTEndian_SwapLE64(n) SkTEndianSwap64::value
-#endif
-
-// When a bytestream is embedded in a 32-bit word, how far we need to
-// shift the word to extract each byte from the low 8 bits by anding with 0xff.
-#ifdef SK_CPU_LENDIAN
- #define SkEndian_Byte0Shift 0
- #define SkEndian_Byte1Shift 8
- #define SkEndian_Byte2Shift 16
- #define SkEndian_Byte3Shift 24
-#else // SK_CPU_BENDIAN
- #define SkEndian_Byte0Shift 24
- #define SkEndian_Byte1Shift 16
- #define SkEndian_Byte2Shift 8
- #define SkEndian_Byte3Shift 0
-#endif
-
-
-#if defined(SK_UINT8_BITFIELD_LENDIAN) && defined(SK_UINT8_BITFIELD_BENDIAN)
- #error "can't have both bitfield LENDIAN and BENDIAN defined"
-#endif
-
-#if !defined(SK_UINT8_BITFIELD_LENDIAN) && !defined(SK_UINT8_BITFIELD_BENDIAN)
- #ifdef SK_CPU_LENDIAN
- #define SK_UINT8_BITFIELD_LENDIAN
- #else
- #define SK_UINT8_BITFIELD_BENDIAN
- #endif
-#endif
-
-#ifdef SK_UINT8_BITFIELD_LENDIAN
- #define SK_UINT8_BITFIELD(f0, f1, f2, f3, f4, f5, f6, f7) \
- SK_OT_BYTE f0 : 1; \
- SK_OT_BYTE f1 : 1; \
- SK_OT_BYTE f2 : 1; \
- SK_OT_BYTE f3 : 1; \
- SK_OT_BYTE f4 : 1; \
- SK_OT_BYTE f5 : 1; \
- SK_OT_BYTE f6 : 1; \
- SK_OT_BYTE f7 : 1;
-#else
- #define SK_UINT8_BITFIELD(f0, f1, f2, f3, f4, f5, f6, f7) \
- SK_OT_BYTE f7 : 1; \
- SK_OT_BYTE f6 : 1; \
- SK_OT_BYTE f5 : 1; \
- SK_OT_BYTE f4 : 1; \
- SK_OT_BYTE f3 : 1; \
- SK_OT_BYTE f2 : 1; \
- SK_OT_BYTE f1 : 1; \
- SK_OT_BYTE f0 : 1;
-#endif
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkFilterQuality.h b/gfx/skia/skia/include/core/SkFilterQuality.h
new file mode 100644
index 0000000000..db0597e697
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkFilterQuality.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkFilterQuality_DEFINED
+#define SkFilterQuality_DEFINED
+
+#include "SkTypes.h"
+
+/**
+ * Controls how much filtering to be done when scaling/transforming complex colors
+ * e.g. images
+ */
+enum SkFilterQuality {
+ kNone_SkFilterQuality, //!< fastest but lowest quality, typically nearest-neighbor
+ kLow_SkFilterQuality, //!< typically bilerp
+ kMedium_SkFilterQuality, //!< typically bilerp + mipmaps for down-scaling
+ kHigh_SkFilterQuality //!< slowest but highest quality, typically bicubic or better
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkFixed.h b/gfx/skia/skia/include/core/SkFixed.h
index 6f168c8edd..fefa718d0f 100644
--- a/gfx/skia/skia/include/core/SkFixed.h
+++ b/gfx/skia/skia/include/core/SkFixed.h
@@ -28,7 +28,7 @@ typedef int32_t SkFixed;
#define SK_FixedTanPIOver8 (0x6A0A)
#define SK_FixedRoot2Over2 (0xB505)
-#define SkFixedToFloat(x) ((x) * 1.5258789e-5f)
+#define SkFixedToFloat(x) ((x) * 1.52587890625e-5f)
#if 1
#define SkFloatToFixed(x) ((SkFixed)((x) * SK_Fixed1))
#else
@@ -50,7 +50,7 @@ typedef int32_t SkFixed;
#define SkFloatToFixed_Check(x) SkFloatToFixed(x)
#endif
-#define SkFixedToDouble(x) ((x) * 1.5258789e-5)
+#define SkFixedToDouble(x) ((x) * 1.52587890625e-5)
#define SkDoubleToFixed(x) ((SkFixed)((x) * SK_Fixed1))
/** Converts an integer to a SkFixed, asserting that the result does not overflow
@@ -60,11 +60,15 @@ typedef int32_t SkFixed;
inline SkFixed SkIntToFixed(int n)
{
SkASSERT(n >= -32768 && n <= 32767);
- return n << 16;
+ // Left shifting a negative value has undefined behavior in C, so we cast to unsigned before
+ // shifting.
+ return (unsigned)n << 16;
}
#else
- // force the cast to SkFixed to ensure that the answer is signed (like the debug version)
- #define SkIntToFixed(n) (SkFixed)((n) << 16)
+ // Left shifting a negative value has undefined behavior in C, so we cast to unsigned before
+ // shifting. Then we force the cast to SkFixed to ensure that the answer is signed (like the
+ // debug version).
+ #define SkIntToFixed(n) (SkFixed)((unsigned)(n) << 16)
#endif
#define SkFixedRoundToInt(x) (((x) + SK_FixedHalf) >> 16)
@@ -78,32 +82,23 @@ typedef int32_t SkFixed;
#define SkFixedAbs(x) SkAbs32(x)
#define SkFixedAve(a, b) (((a) + (b)) >> 1)
-SkFixed SkFixedMul_portable(SkFixed, SkFixed);
-
-#define SkFixedDiv(numer, denom) SkDivBits(numer, denom, 16)
-
-///////////////////////////////////////////////////////////////////////////////
-// TODO: move fixed sin/cos into SkCosineMapper, as that is the only caller
-// or rewrite SkCosineMapper to not use it at all
-
-SkFixed SkFixedSinCos(SkFixed radians, SkFixed* cosValueOrNull);
-#define SkFixedSin(radians) SkFixedSinCos(radians, NULL)
-static inline SkFixed SkFixedCos(SkFixed radians) {
- SkFixed cosValue;
- (void)SkFixedSinCos(radians, &cosValue);
- return cosValue;
-}
+// Blink layout tests are baselined to Clang optimizing through undefined behavior in SkDivBits.
+#if defined(SK_SUPPORT_LEGACY_DIVBITS_UB)
+ #define SkFixedDiv(numer, denom) SkDivBits(numer, denom, 16)
+#else
+ // TODO(reed): this clamp shouldn't be needed. Use SkToS32().
+ #define SkFixedDiv(numer, denom) \
+ SkTPin(((int64_t)numer << 16) / denom, SK_MinS32, SK_MaxS32)
+#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Now look for ASM overrides for our portable versions (should consider putting this in its own file)
-#ifdef SkLONGLONG
- inline SkFixed SkFixedMul_longlong(SkFixed a, SkFixed b)
- {
- return (SkFixed)((int64_t)a * b >> 16);
- }
- #define SkFixedMul(a,b) SkFixedMul_longlong(a,b)
-#endif
+inline SkFixed SkFixedMul_longlong(SkFixed a, SkFixed b) {
+ return (SkFixed)((int64_t)a * b >> 16);
+}
+#define SkFixedMul(a,b) SkFixedMul_longlong(a,b)
+
#if defined(SK_CPU_ARM32)
/* This guy does not handle NaN or other obscurities, but is faster than
@@ -146,20 +141,31 @@ static inline SkFixed SkFixedCos(SkFixed radians) {
#define SkFloatToFixed(x) SkFloatToFixed_arm(x)
#endif
-#ifndef SkFixedMul
- #define SkFixedMul(x, y) SkFixedMul_portable(x, y)
-#endif
+///////////////////////////////////////////////////////////////////////////////
+
+typedef int64_t SkFixed3232; // 32.32
+
+#define SkIntToFixed3232(x) ((SkFixed3232)(x) << 32)
+#define SkFixed3232ToInt(x) ((int)((x) >> 32))
+#define SkFixedToFixed3232(x) ((SkFixed3232)(x) << 16)
+#define SkFixed3232ToFixed(x) ((SkFixed)((x) >> 16))
+#define SkFloatToFixed3232(x) ((SkFixed3232)((x) * (65536.0f * 65536.0f)))
+
+#define SkScalarToFixed3232(x) SkFloatToFixed3232(x)
///////////////////////////////////////////////////////////////////////////////
-typedef int64_t SkFixed48;
+// 64bits wide, with a 16bit bias. Useful when accumulating lots of 16.16 so
+// we don't overflow along the way
+typedef int64_t Sk48Dot16;
-#define SkIntToFixed48(x) ((SkFixed48)(x) << 48)
-#define SkFixed48ToInt(x) ((int)((x) >> 48))
-#define SkFixedToFixed48(x) ((SkFixed48)(x) << 32)
-#define SkFixed48ToFixed(x) ((SkFixed)((x) >> 32))
-#define SkFloatToFixed48(x) ((SkFixed48)((x) * (65536.0f * 65536.0f * 65536.0f)))
+#define Sk48Dot16FloorToInt(x) static_cast((x) >> 16)
-#define SkScalarToFixed48(x) SkFloatToFixed48(x)
+static inline float Sk48Dot16ToScalar(Sk48Dot16 x) {
+ return static_cast(x * 1.5258789e-5); // x * (1.0f / (1 << 16))
+}
+#define SkFloatTo48Dot16(x) (static_cast((x) * (1 << 16)))
+
+#define SkScalarTo48Dot16(x) SkFloatTo48Dot16(x)
#endif
diff --git a/gfx/skia/skia/include/core/SkFlattenable.h b/gfx/skia/skia/include/core/SkFlattenable.h
index f6d377a9d7..bccabc18fa 100644
--- a/gfx/skia/skia/include/core/SkFlattenable.h
+++ b/gfx/skia/skia/include/core/SkFlattenable.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,7 +5,6 @@
* found in the LICENSE file.
*/
-
#ifndef SkFlattenable_DEFINED
#define SkFlattenable_DEFINED
@@ -15,9 +13,26 @@
class SkReadBuffer;
class SkWriteBuffer;
-#define SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(flattenable) \
- SkFlattenable::Registrar(#flattenable, flattenable::CreateProc, \
- flattenable::GetFlattenableType());
+class SkPrivateEffectInitializer;
+
+/*
+ * Flattening is straight-forward:
+ * 1. call getFactory() so we have a function-ptr to recreate the subclass
+ * 2. call flatten(buffer) to write out enough data for the factory to read
+ *
+ * Unflattening is easy for the caller: new_instance = factory(buffer)
+ *
+ * The complexity of supporting this is as follows.
+ *
+ * If your subclass wants to control unflattening, use this macro in your declaration:
+ * SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS
+ * This will provide a getFactory(), and require that the subclass implements CreateProc.
+ *
+ * For older buffers (before the DEEPFLATTENING change, the macros below declare
+ * a thin factory DeepCreateProc. It checks the version of the buffer, and if it is pre-deep,
+ * then it calls through to a (usually protected) constructor, passing the buffer.
+ * If the buffer is newer, then it directly calls the "real" factory: CreateProc.
+ */
#define SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP() static void InitializeFlattenables();
@@ -27,14 +42,16 @@ class SkWriteBuffer;
#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END \
}
-#define SK_DECLARE_UNFLATTENABLE_OBJECT() \
- virtual Factory getFactory() const SK_OVERRIDE { return NULL; }
+#define SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(flattenable) \
+ SkFlattenable::Register(#flattenable, flattenable::CreateProc, \
+ flattenable::GetFlattenableType());
-#define SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(flattenable) \
- virtual Factory getFactory() const SK_OVERRIDE { return CreateProc; } \
- static SkFlattenable* CreateProc(SkReadBuffer& buffer) { \
- return SkNEW_ARGS(flattenable, (buffer)); \
- }
+#define SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(flattenable) \
+ private: \
+ static SkFlattenable* CreateProc(SkReadBuffer&); \
+ friend class ::SkPrivateEffectInitializer; \
+ public: \
+ Factory getFactory() const override { return CreateProc; }
/** For SkFlattenable derived objects with a valid type
This macro should only be used in base class objects in core
@@ -65,8 +82,6 @@ public:
kSkXfermode_Type,
};
- SK_DECLARE_INST_COUNT(SkFlattenable)
-
typedef SkFlattenable* (*Factory)(SkReadBuffer&);
SkFlattenable() {}
@@ -87,21 +102,11 @@ public:
static void Register(const char name[], Factory, Type);
- class Registrar {
- public:
- Registrar(const char name[], Factory factory, Type type) {
- SkFlattenable::Register(name, factory, type);
- }
- };
-
- /** Override this to write data specific to your subclass into the buffer,
- being sure to call your super-class' version first. This data will later
- be passed to your Factory function, returned by getFactory().
+ /**
+ * Override this if your subclass needs to record data that it will need to recreate itself
+ * from its CreateProc (returned by getFactory()).
*/
- virtual void flatten(SkWriteBuffer&) const;
-
-protected:
- SkFlattenable(SkReadBuffer&) {}
+ virtual void flatten(SkWriteBuffer&) const {}
private:
static void InitializeFlattenablesIfNeeded();
diff --git a/gfx/skia/skia/include/core/SkFlattenableBuffers.h b/gfx/skia/skia/include/core/SkFlattenableBuffers.h
deleted file mode 100644
index 3e5d5b94ee..0000000000
--- a/gfx/skia/skia/include/core/SkFlattenableBuffers.h
+++ /dev/null
@@ -1,10 +0,0 @@
-// Temporary shim to keep a couple dependencies working in Chromium.
-#ifndef SkFlattenableBuffers_DEFINED
-#define SkFlattenableBuffers_DEFINED
-
-#include "SkReadBuffer.h"
-#include "SkWriteBuffer.h"
-
-typedef SkReadBuffer SkFlattenableReadBuffer;
-
-#endif//SkFlattenableBuffers_DEFINED
diff --git a/gfx/skia/skia/include/core/SkFloatBits.h b/gfx/skia/skia/include/core/SkFloatBits.h
deleted file mode 100644
index 552e712f53..0000000000
--- a/gfx/skia/skia/include/core/SkFloatBits.h
+++ /dev/null
@@ -1,133 +0,0 @@
-
-/*
- * Copyright 2008 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkFloatBits_DEFINED
-#define SkFloatBits_DEFINED
-
-#include "SkTypes.h"
-
-/** Convert a sign-bit int (i.e. float interpreted as int) into a 2s compliement
- int. This also converts -0 (0x80000000) to 0. Doing this to a float allows
- it to be compared using normal C operators (<, <=, etc.)
-*/
-static inline int32_t SkSignBitTo2sCompliment(int32_t x) {
- if (x < 0) {
- x &= 0x7FFFFFFF;
- x = -x;
- }
- return x;
-}
-
-/** Convert a 2s compliment int to a sign-bit (i.e. int interpreted as float).
- This undoes the result of SkSignBitTo2sCompliment().
- */
-static inline int32_t Sk2sComplimentToSignBit(int32_t x) {
- int sign = x >> 31;
- // make x positive
- x = (x ^ sign) - sign;
- // set the sign bit as needed
- x |= sign << 31;
- return x;
-}
-
-/** Given the bit representation of a float, return its value cast to an int.
- If the value is out of range, or NaN, return return +/- SK_MaxS32
-*/
-int32_t SkFloatBits_toIntCast(int32_t floatBits);
-
-/** Given the bit representation of a float, return its floor as an int.
- If the value is out of range, or NaN, return return +/- SK_MaxS32
- */
-SK_API int32_t SkFloatBits_toIntFloor(int32_t floatBits);
-
-/** Given the bit representation of a float, return it rounded to an int.
- If the value is out of range, or NaN, return return +/- SK_MaxS32
- */
-SK_API int32_t SkFloatBits_toIntRound(int32_t floatBits);
-
-/** Given the bit representation of a float, return its ceiling as an int.
- If the value is out of range, or NaN, return return +/- SK_MaxS32
- */
-SK_API int32_t SkFloatBits_toIntCeil(int32_t floatBits);
-
-
-union SkFloatIntUnion {
- float fFloat;
- int32_t fSignBitInt;
-};
-
-// Helper to see a float as its bit pattern (w/o aliasing warnings)
-static inline int32_t SkFloat2Bits(float x) {
- SkFloatIntUnion data;
- data.fFloat = x;
- return data.fSignBitInt;
-}
-
-// Helper to see a bit pattern as a float (w/o aliasing warnings)
-static inline float SkBits2Float(int32_t floatAsBits) {
- SkFloatIntUnion data;
- data.fSignBitInt = floatAsBits;
- return data.fFloat;
-}
-
-/** Return the float as a 2s compliment int. Just to be used to compare floats
- to each other or against positive float-bit-constants (like 0). This does
- not return the int equivalent of the float, just something cheaper for
- compares-only.
- */
-static inline int32_t SkFloatAs2sCompliment(float x) {
- return SkSignBitTo2sCompliment(SkFloat2Bits(x));
-}
-
-/** Return the 2s compliment int as a float. This undos the result of
- SkFloatAs2sCompliment
- */
-static inline float Sk2sComplimentAsFloat(int32_t x) {
- return SkBits2Float(Sk2sComplimentToSignBit(x));
-}
-
-/** Return x cast to a float (i.e. (float)x)
-*/
-float SkIntToFloatCast(int x);
-float SkIntToFloatCast_NoOverflowCheck(int x);
-
-/** Return the float cast to an int.
- If the value is out of range, or NaN, return +/- SK_MaxS32
-*/
-static inline int32_t SkFloatToIntCast(float x) {
- return SkFloatBits_toIntCast(SkFloat2Bits(x));
-}
-
-/** Return the floor of the float as an int.
- If the value is out of range, or NaN, return +/- SK_MaxS32
-*/
-static inline int32_t SkFloatToIntFloor(float x) {
- return SkFloatBits_toIntFloor(SkFloat2Bits(x));
-}
-
-/** Return the float rounded to an int.
- If the value is out of range, or NaN, return +/- SK_MaxS32
-*/
-static inline int32_t SkFloatToIntRound(float x) {
- return SkFloatBits_toIntRound(SkFloat2Bits(x));
-}
-
-/** Return the ceiling of the float as an int.
- If the value is out of range, or NaN, return +/- SK_MaxS32
-*/
-static inline int32_t SkFloatToIntCeil(float x) {
- return SkFloatBits_toIntCeil(SkFloat2Bits(x));
-}
-
-// Scalar wrappers for float-bit routines
-
-#define SkScalarAs2sCompliment(x) SkFloatAs2sCompliment(x)
-#define Sk2sComplimentAsScalar(x) Sk2sComplimentAsFloat(x)
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkFloatingPoint.h b/gfx/skia/skia/include/core/SkFloatingPoint.h
deleted file mode 100644
index 6c480c3b07..0000000000
--- a/gfx/skia/skia/include/core/SkFloatingPoint.h
+++ /dev/null
@@ -1,161 +0,0 @@
-
-/*
- * Copyright 2006 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkFloatingPoint_DEFINED
-#define SkFloatingPoint_DEFINED
-
-#include "SkTypes.h"
-
-#include
-#include
-
-// For _POSIX_VERSION
-#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
-#include
-#endif
-
-#include "SkFloatBits.h"
-
-// C++98 cmath std::pow seems to be the earliest portable way to get float pow.
-// However, on Linux including cmath undefines isfinite.
-// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=14608
-static inline float sk_float_pow(float base, float exp) {
- return powf(base, exp);
-}
-
-static inline float sk_float_copysign(float x, float y) {
-// c++11 contains a 'float copysign(float, float)' function in .
-#if (!defined(_MSC_VER) && __cplusplus >= 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1800)
- return copysign(x, y);
-
-// Posix has demanded 'float copysignf(float, float)' (from C99) since Issue 6.
-#elif defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L
- return copysignf(x, y);
-
-// Visual studio prior to 13 only has 'double _copysign(double, double)'.
-#elif defined(_MSC_VER)
- return (float)_copysign(x, y);
-
-// Otherwise convert to bits and extract sign.
-#else
- int32_t xbits = SkFloat2Bits(x);
- int32_t ybits = SkFloat2Bits(y);
- return SkBits2Float((xbits & 0x7FFFFFFF) | (ybits & 0x80000000));
-#endif
-}
-
-#ifdef SK_BUILD_FOR_WINCE
- #define sk_float_sqrt(x) (float)::sqrt(x)
- #define sk_float_sin(x) (float)::sin(x)
- #define sk_float_cos(x) (float)::cos(x)
- #define sk_float_tan(x) (float)::tan(x)
- #define sk_float_acos(x) (float)::acos(x)
- #define sk_float_asin(x) (float)::asin(x)
- #define sk_float_atan2(y,x) (float)::atan2(y,x)
- #define sk_float_abs(x) (float)::fabs(x)
- #define sk_float_mod(x,y) (float)::fmod(x,y)
- #define sk_float_exp(x) (float)::exp(x)
- #define sk_float_log(x) (float)::log(x)
- #define sk_float_floor(x) (float)::floor(x)
- #define sk_float_ceil(x) (float)::ceil(x)
-#else
- #define sk_float_sqrt(x) sqrtf(x)
- #define sk_float_sin(x) sinf(x)
- #define sk_float_cos(x) cosf(x)
- #define sk_float_tan(x) tanf(x)
- #define sk_float_floor(x) floorf(x)
- #define sk_float_ceil(x) ceilf(x)
-#ifdef SK_BUILD_FOR_MAC
- #define sk_float_acos(x) static_cast(acos(x))
- #define sk_float_asin(x) static_cast(asin(x))
-#else
- #define sk_float_acos(x) acosf(x)
- #define sk_float_asin(x) asinf(x)
-#endif
- #define sk_float_atan2(y,x) atan2f(y,x)
- #define sk_float_abs(x) fabsf(x)
- #define sk_float_mod(x,y) fmodf(x,y)
- #define sk_float_exp(x) expf(x)
- #define sk_float_log(x) logf(x)
-#endif
-
-#ifdef SK_BUILD_FOR_WIN
- #define sk_float_isfinite(x) _finite(x)
- #define sk_float_isnan(x) _isnan(x)
- static inline int sk_float_isinf(float x) {
- int32_t bits = SkFloat2Bits(x);
- return (bits << 1) == (0xFF << 24);
- }
-#else
- #define sk_float_isfinite(x) isfinite(x)
- #define sk_float_isnan(x) isnan(x)
- #define sk_float_isinf(x) isinf(x)
-#endif
-
-#define sk_double_isnan(a) sk_float_isnan(a)
-
-#ifdef SK_USE_FLOATBITS
- #define sk_float_floor2int(x) SkFloatToIntFloor(x)
- #define sk_float_round2int(x) SkFloatToIntRound(x)
- #define sk_float_ceil2int(x) SkFloatToIntCeil(x)
-#else
- #define sk_float_floor2int(x) (int)sk_float_floor(x)
- #define sk_float_round2int(x) (int)sk_float_floor((x) + 0.5f)
- #define sk_float_ceil2int(x) (int)sk_float_ceil(x)
-#endif
-
-extern const uint32_t gIEEENotANumber;
-extern const uint32_t gIEEEInfinity;
-extern const uint32_t gIEEENegativeInfinity;
-
-#define SK_FloatNaN (*SkTCast(&gIEEENotANumber))
-#define SK_FloatInfinity (*SkTCast(&gIEEEInfinity))
-#define SK_FloatNegativeInfinity (*SkTCast(&gIEEENegativeInfinity))
-
-#if defined(__SSE__)
-#include
-#elif defined(__ARM_NEON__)
-#include
-#endif
-
-// Fast, approximate inverse square root.
-// Compare to name-brand "1.0f / sk_float_sqrt(x)". Should be around 10x faster on SSE, 2x on NEON.
-static inline float sk_float_rsqrt(const float x) {
-// We want all this inlined, so we'll inline SIMD and just take the hit when we don't know we've got
-// it at compile time. This is going to be too fast to productively hide behind a function pointer.
-//
-// We do one step of Newton's method to refine the estimates in the NEON and null paths. No
-// refinement is faster, but very innacurate. Two steps is more accurate, but slower than 1/sqrt.
-#if defined(__SSE__)
- float result;
- _mm_store_ss(&result, _mm_rsqrt_ss(_mm_set_ss(x)));
- return result;
-#elif defined(__ARM_NEON__)
- // Get initial estimate.
- const float32x2_t xx = vdup_n_f32(x); // Clever readers will note we're doing everything 2x.
- float32x2_t estimate = vrsqrte_f32(xx);
-
- // One step of Newton's method to refine.
- const float32x2_t estimate_sq = vmul_f32(estimate, estimate);
- estimate = vmul_f32(estimate, vrsqrts_f32(xx, estimate_sq));
- return vget_lane_f32(estimate, 0); // 1 will work fine too; the answer's in both places.
-#else
- // Get initial estimate.
- int i = *SkTCast(&x);
- i = 0x5f3759df - (i>>1);
- float estimate = *SkTCast(&i);
-
- // One step of Newton's method to refine.
- const float estimate_sq = estimate*estimate;
- estimate *= (1.5f-0.5f*x*estimate_sq);
- return estimate;
-#endif
-}
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkFont.h b/gfx/skia/skia/include/core/SkFont.h
index 9bdecd6eb9..e4ebebb244 100644
--- a/gfx/skia/skia/include/core/SkFont.h
+++ b/gfx/skia/skia/include/core/SkFont.h
@@ -75,8 +75,8 @@ public:
enum Flags {
/**
* Use the system's automatic hinting mechanism to hint the typeface.
- * 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.
+ * 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,
@@ -87,6 +87,13 @@ public:
*/
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
@@ -96,10 +103,9 @@ public:
* This applies to calls that return metrics (e.g. measureText) and to drawing the glyphs
* (see SkCanvas drawText and drawPosText).
*/
- kUseNonlinearMetrics_Flag = 1 << 2,
+ kUseNonlinearMetrics_Flag = 1 << 3,
- kVertical_Flag = 1 << 3,
- kEmbeddedBitmaps_Flag = 1 << 4,
+ kVertical_Flag = 1 << 4,
kGenA8FromLCD_Flag = 1 << 5,
kEmbolden_Flag = 1 << 6,
kDevKern_Flag = 1 << 7, // ifdef ANDROID ?
diff --git a/gfx/skia/skia/include/core/SkFontHost.h b/gfx/skia/skia/include/core/SkFontHost.h
index 4c5013fe4a..a2cc04bc70 100644
--- a/gfx/skia/skia/include/core/SkFontHost.h
+++ b/gfx/skia/skia/include/core/SkFontHost.h
@@ -90,42 +90,6 @@ public:
static void SetSubpixelOrder(LCDOrder order);
/** @deprecated get from Device. */
static LCDOrder GetSubpixelOrder();
-
-private:
- /** Return a new, closest matching typeface given either an existing family
- (specified by a typeface in that family) or by a familyName and a
- requested style.
- 1) If familyFace is null, use familyName.
- 2) If familyName is null, use data (UTF-16 to cover).
- 3) If all are null, return the default font that best matches style
- */
- static SkTypeface* CreateTypeface(const SkTypeface* familyFace,
- const char familyName[],
- SkTypeface::Style style);
-
- /** Return a new typeface given the data buffer. If the data does not
- represent a valid font, returns null.
-
- If a typeface instance is returned, the caller is responsible for
- calling unref() on the typeface when they are finished with it.
-
- The returned typeface may or may not have called ref() on the stream
- parameter. If the typeface has not called ref(), then it may have made
- a copy of the releveant data. In either case, the caller is still
- responsible for its refcnt ownership of the stream.
- */
- static SkTypeface* CreateTypefaceFromStream(SkStream*);
-
- /** Return a new typeface from the specified file path. If the file does not
- represent a valid font, this returns null. If a typeface is returned,
- the caller is responsible for calling unref() when it is no longer used.
- */
- static SkTypeface* CreateTypefaceFromFile(const char path[]);
-
- ///////////////////////////////////////////////////////////////////////////
-
- friend class SkScalerContext;
- friend class SkTypeface;
};
#endif
diff --git a/gfx/skia/skia/include/core/SkFontStyle.h b/gfx/skia/skia/include/core/SkFontStyle.h
new file mode 100644
index 0000000000..f42d7dd470
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkFontStyle.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2013 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkFontStyle_DEFINED
+#define SkFontStyle_DEFINED
+
+#include "SkTypes.h"
+
+class SK_API SkFontStyle {
+public:
+ enum Weight {
+ kThin_Weight = 100,
+ kExtraLight_Weight = 200,
+ kLight_Weight = 300,
+ kNormal_Weight = 400,
+ kMedium_Weight = 500,
+ kSemiBold_Weight = 600,
+ kBold_Weight = 700,
+ kExtraBold_Weight = 800,
+ kBlack_Weight = 900
+ };
+
+ enum Width {
+ kUltraCondensed_Width = 1,
+ kExtraCondensed_Width = 2,
+ kCondensed_Width = 3,
+ kSemiCondensed_Width = 4,
+ kNormal_Width = 5,
+ kSemiExpanded_Width = 6,
+ kExpanded_Width = 7,
+ kExtraExpanded_Width = 8,
+ kUltaExpanded_Width = 9
+ };
+
+ enum Slant {
+ kUpright_Slant,
+ kItalic_Slant,
+ };
+
+ SkFontStyle();
+ SkFontStyle(int weight, int width, Slant);
+ /** oldStyle means the style-bits in SkTypeface::Style: bold=1, italic=2 */
+ explicit SkFontStyle(unsigned oldStyle);
+
+ bool operator==(const SkFontStyle& rhs) const {
+ return fUnion.fU32 == rhs.fUnion.fU32;
+ }
+
+ int weight() const { return fUnion.fR.fWeight; }
+ int width() const { return fUnion.fR.fWidth; }
+ Slant slant() const { return (Slant)fUnion.fR.fSlant; }
+
+ bool isItalic() const {
+ return kItalic_Slant == fUnion.fR.fSlant;
+ }
+
+private:
+ union {
+ struct {
+ uint16_t fWeight; // 100 .. 900
+ uint8_t fWidth; // 1 .. 9
+ uint8_t fSlant; // 0 .. 2
+ } fR;
+ uint32_t fU32;
+ } fUnion;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkGraphics.h b/gfx/skia/skia/include/core/SkGraphics.h
index e7865ca5af..5aecc7acd0 100644
--- a/gfx/skia/skia/include/core/SkGraphics.h
+++ b/gfx/skia/skia/include/core/SkGraphics.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,25 +5,26 @@
* found in the LICENSE file.
*/
-
#ifndef SkGraphics_DEFINED
#define SkGraphics_DEFINED
#include "SkTypes.h"
+class SkData;
+class SkImageGenerator;
+class SkTraceMemoryDump;
+
class SK_API SkGraphics {
public:
/**
* Call this at process initialization time if your environment does not
- * permit static global initializers that execute code. Note that
- * Init() is not thread-safe.
+ * permit static global initializers that execute code.
+ * Init() is thread-safe and idempotent.
*/
static void Init();
- /**
- * Call this to release any memory held privately, such as the font cache.
- */
- static void Term();
+ // We're in the middle of cleaning this up.
+ static void Term() {}
/**
* Return the version numbers for the library. If the parameter is not
@@ -80,46 +80,44 @@ public:
static void PurgeFontCache();
/**
- * Scaling bitmaps with the SkPaint::kHigh_FilterLevel setting is
+ * Scaling bitmaps with the kHigh_SkFilterQuality setting is
* expensive, so the result is saved in the global Scaled Image
* Cache.
*
* This function returns the memory usage of the Scaled Image Cache.
*/
- static size_t GetImageCacheTotalBytesUsed();
- /**
- * These functions get/set the memory usage limit for the Scaled
- * Image Cache. Bitmaps are purged from the cache when the
- * memory useage exceeds this limit.
- */
- static size_t GetImageCacheTotalByteLimit();
- static size_t SetImageCacheTotalByteLimit(size_t newLimit);
-
- // DEPRECATED
- static size_t GetImageCacheBytesUsed() {
- return GetImageCacheTotalBytesUsed();
- }
- // DEPRECATED
- static size_t GetImageCacheByteLimit() {
- return GetImageCacheTotalByteLimit();
- }
- // DEPRECATED
- static size_t SetImageCacheByteLimit(size_t newLimit) {
- return SetImageCacheTotalByteLimit(newLimit);
- }
+ static size_t GetResourceCacheTotalBytesUsed();
/**
- * Scaling bitmaps with the SkPaint::kHigh_FilterLevel setting is
- * expensive, so the result is saved in the global Scaled Image
- * Cache. When the resulting bitmap is too large, this can
- * overload the cache. If the ImageCacheSingleAllocationByteLimit
- * is set to a non-zero number, and the resulting bitmap would be
- * larger than that value, the bitmap scaling algorithm falls
- * back onto a cheaper algorithm and does not cache the result.
- * Zero is the default value.
+ * These functions get/set the memory usage limit for the resource cache, used for temporary
+ * bitmaps and other resources. Entries are purged from the cache when the memory useage
+ * exceeds this limit.
*/
- static size_t GetImageCacheSingleAllocationByteLimit();
- static size_t SetImageCacheSingleAllocationByteLimit(size_t newLimit);
+ static size_t GetResourceCacheTotalByteLimit();
+ static size_t SetResourceCacheTotalByteLimit(size_t newLimit);
+
+ /**
+ * For debugging purposes, this will attempt to purge the resource cache. It
+ * does not change the limit.
+ */
+ static void PurgeResourceCache();
+
+ /**
+ * When the cachable entry is very lage (e.g. a large scaled bitmap), adding it to the cache
+ * can cause most/all of the existing entries to be purged. To avoid the, the client can set
+ * a limit for a single allocation. If a cacheable entry would have been cached, but its size
+ * exceeds this limit, then we do not attempt to cache it at all.
+ *
+ * Zero is the default value, meaning we always attempt to cache entries.
+ */
+ static size_t GetResourceCacheSingleAllocationByteLimit();
+ static size_t SetResourceCacheSingleAllocationByteLimit(size_t newLimit);
+
+ /**
+ * Dumps memory usage of caches using the SkTraceMemoryDump interface. See SkTraceMemoryDump
+ * for usage of this method.
+ */
+ static void DumpMemoryStatistics(SkTraceMemoryDump* dump);
/**
* Applications with command line options may pass optional state, such
@@ -151,12 +149,17 @@ public:
*/
static void SetTLSFontCacheLimit(size_t bytes);
-private:
- /** This is automatically called by SkGraphics::Init(), and must be
- implemented by the host OS. This allows the host OS to register a callback
- with the C++ runtime to call SkGraphics::FreeCaches()
- */
- static void InstallNewHandler();
+ typedef SkImageGenerator* (*ImageGeneratorFromEncodedFactory)(SkData*);
+
+ /**
+ * To instantiate images from encoded data, first looks at this runtime function-ptr. If it
+ * exists, it is called to create an SkImageGenerator from SkData. If there is no function-ptr
+ * or there is, but it returns NULL, then skia will call its internal default implementation.
+ *
+ * Returns the previous factory (which could be NULL).
+ */
+ static ImageGeneratorFromEncodedFactory
+ SetImageGeneratorFromEncodedFactory(ImageGeneratorFromEncodedFactory);
};
class SkAutoGraphics {
@@ -164,9 +167,6 @@ public:
SkAutoGraphics() {
SkGraphics::Init();
}
- ~SkAutoGraphics() {
- SkGraphics::Term();
- }
};
#endif
diff --git a/gfx/skia/skia/include/core/SkImage.h b/gfx/skia/skia/include/core/SkImage.h
index 04e184370f..d6b10a8e18 100644
--- a/gfx/skia/skia/include/core/SkImage.h
+++ b/gfx/skia/skia/include/core/SkImage.h
@@ -8,6 +8,7 @@
#ifndef SkImage_DEFINED
#define SkImage_DEFINED
+#include "SkFilterQuality.h"
#include "SkImageInfo.h"
#include "SkImageEncoder.h"
#include "SkRefCnt.h"
@@ -16,7 +17,13 @@
class SkData;
class SkCanvas;
+class SkColorTable;
+class SkImageGenerator;
class SkPaint;
+class SkPicture;
+class SkPixelSerializer;
+class SkString;
+class SkSurface;
class GrContext;
class GrTexture;
@@ -29,50 +36,128 @@ class GrTexture;
* The content of SkImage is always immutable, though the actual storage may
* change, if for example that image can be re-created via encoded data or
* other means.
+ *
+ * SkImage always has a non-zero dimensions. If there is a request to create a new image, either
+ * directly or via SkSurface, and either of the requested dimensions are zero, then NULL will be
+ * returned.
*/
class SK_API SkImage : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkImage)
-
typedef SkImageInfo Info;
+ typedef void* ReleaseContext;
- static SkImage* NewRasterCopy(const Info&, const void* pixels, size_t rowBytes);
+ static SkImage* NewRasterCopy(const Info&, const void* pixels, size_t rowBytes,
+ SkColorTable* ctable = NULL);
static SkImage* NewRasterData(const Info&, SkData* pixels, size_t rowBytes);
- static SkImage* NewEncodedData(SkData*);
+
+ typedef void (*RasterReleaseProc)(const void* pixels, ReleaseContext);
/**
- * GrTexture is a more logical parameter for this factory, but its
- * interactions with scratch cache still has issues, so for now we take
- * SkBitmap instead. This will be changed in the future. skbug.com/1449
+ * Return a new Image referencing the specified pixels. These must remain valid and unchanged
+ * until the specified release-proc is called, indicating that Skia no longer has a reference
+ * to the pixels.
+ *
+ * Returns NULL if the requested Info is unsupported.
*/
- static SkImage* NewTexture(const SkBitmap&);
+ static SkImage* NewFromRaster(const Info&, const void* pixels, size_t rowBytes,
+ RasterReleaseProc, ReleaseContext);
+
+ /**
+ * Construct a new image from the specified bitmap. If the bitmap is marked immutable, and
+ * its pixel memory is shareable, it may be shared instead of copied.
+ */
+ static SkImage* NewFromBitmap(const SkBitmap&);
+
+ /**
+ * Construct a new SkImage based on the given ImageGenerator.
+ * This function will always take ownership of the passed
+ * ImageGenerator. Returns NULL on error.
+ *
+ * If a subset is specified, it must be contained within the generator's bounds.
+ */
+ static SkImage* NewFromGenerator(SkImageGenerator*, const SkIRect* subset = NULL);
+
+ /**
+ * Construct a new SkImage based on the specified encoded data. Returns NULL on failure,
+ * which can mean that the format of the encoded data was not recognized/supported.
+ *
+ * If a subset is specified, it must be contained within the encoded data's bounds.
+ *
+ * Regardless of success or failure, the caller is responsible for managing their ownership
+ * of the data.
+ */
+ static SkImage* NewFromEncoded(SkData* encoded, const SkIRect* subset = NULL);
+
+ /**
+ * Create a new image from the specified descriptor. Note - the caller is responsible for
+ * managing the lifetime of the underlying platform texture.
+ *
+ * Will return NULL if the specified descriptor is unsupported.
+ */
+ static SkImage* NewFromTexture(GrContext* ctx, const GrBackendTextureDesc& desc) {
+ return NewFromTexture(ctx, desc, kPremul_SkAlphaType, NULL, NULL);
+ }
+
+ static SkImage* NewFromTexture(GrContext* ctx, const GrBackendTextureDesc& de, SkAlphaType at) {
+ return NewFromTexture(ctx, de, at, NULL, NULL);
+ }
+
+ typedef void (*TextureReleaseProc)(ReleaseContext);
+
+ /**
+ * Create a new image from the specified descriptor. The underlying platform texture must stay
+ * valid and unaltered until the specified release-proc is invoked, indicating that Skia
+ * no longer is holding a reference to it.
+ *
+ * Will return NULL if the specified descriptor is unsupported.
+ */
+ static SkImage* NewFromTexture(GrContext*, const GrBackendTextureDesc&, SkAlphaType,
+ TextureReleaseProc, ReleaseContext);
+
+ /**
+ * Create a new image from the specified descriptor. Note - Skia will delete or recycle the
+ * texture when the image is released.
+ *
+ * Will return NULL if the specified descriptor is unsupported.
+ */
+ static SkImage* NewFromAdoptedTexture(GrContext*, const GrBackendTextureDesc&,
+ SkAlphaType = kPremul_SkAlphaType);
+
+ /**
+ * Create a new image by copying the pixels from the specified descriptor. No reference is
+ * kept to the original platform texture.
+ *
+ * Will return NULL if the specified descriptor is unsupported.
+ */
+ static SkImage* NewFromTextureCopy(GrContext*, const GrBackendTextureDesc&,
+ SkAlphaType = kPremul_SkAlphaType);
+
+ /**
+ * Create a new image by copying the pixels from the specified y, u, v textures. The data
+ * from the textures is immediately ingested into the image and the textures can be modified or
+ * deleted after the function returns. The image will have the dimensions of the y texture.
+ */
+ static SkImage* NewFromYUVTexturesCopy(GrContext*, SkYUVColorSpace,
+ const GrBackendObject yuvTextureHandles[3],
+ const SkISize yuvSizes[3],
+ GrSurfaceOrigin);
+
+ static SkImage* NewFromPicture(const SkPicture*, const SkISize& dimensions,
+ const SkMatrix*, const SkPaint*);
+
+ ///////////////////////////////////////////////////////////////////////////////////////////////
int width() const { return fWidth; }
int height() const { return fHeight; }
+ SkISize dimensions() const { return SkISize::Make(fWidth, fHeight); }
+ SkIRect bounds() const { return SkIRect::MakeWH(fWidth, fHeight); }
uint32_t uniqueID() const { return fUniqueID; }
-
- /**
- * Return the GrTexture that stores the image pixels. Calling getTexture
- * does not affect the reference count of the GrTexture object.
- * Will return NULL if the image does not use a texture.
- */
- GrTexture* getTexture();
+ virtual bool isOpaque() const { return false; }
virtual SkShader* newShader(SkShader::TileMode,
SkShader::TileMode,
const SkMatrix* localMatrix = NULL) const;
- void draw(SkCanvas*, SkScalar x, SkScalar y, const SkPaint*);
-
- /**
- * Draw the image, cropped to the src rect, to the dst rect of a canvas.
- * If src is larger than the bounds of the image, the rest of the image is
- * filled with transparent black pixels.
- *
- * See SkCanvas::drawBitmapRectToRect for similar behavior.
- */
- void draw(SkCanvas*, const SkRect* src, const SkRect& dst, const SkPaint*);
-
/**
* If the image has direct access to its pixels (i.e. they are in local
* RAM) return the (const) address of those pixels, and if not null, return
@@ -84,57 +169,192 @@ public:
*/
const void* peekPixels(SkImageInfo* info, size_t* rowBytes) const;
+ /**
+ * If the image has direct access to its pixels (i.e. they are in local
+ * RAM) return the (const) address of those pixels, and if not null, return
+ * true, and if pixmap is not NULL, set it to point into the image.
+ *
+ * On failure, return false and ignore the pixmap parameter.
+ */
+ bool peekPixels(SkPixmap* pixmap) const;
+
+ /**
+ * Some images have to perform preliminary work in preparation for drawing. This can be
+ * decoding, uploading to a GPU, or other tasks. These happen automatically when an image
+ * is drawn, and often they are cached so that the cost is only paid the first time.
+ *
+ * Preroll() can be called before drawing to try to perform this prepatory work ahead of time.
+ * For images that have no such work, this returns instantly. Others may do some thing to
+ * prepare their cache and then return.
+ *
+ * If the image will drawn to a GPU-backed canvas or surface, pass the associated GrContext.
+ * If the image will be drawn to any other type of canvas or surface, pass null.
+ */
+ void preroll(GrContext* = nullptr) const;
+
+ // DEPRECATED
+ GrTexture* getTexture() const;
+
+ /**
+ * Returns true if the image is texture backed.
+ */
+ bool isTextureBacked() const;
+
+ /**
+ * Retrieves the backend API handle of the texture. If flushPendingGrContextIO then the
+ * GrContext will issue to the backend API any deferred IO operations on the texture before
+ * returning.
+ */
+ GrBackendObject getTextureHandle(bool flushPendingGrContextIO) const;
+
+ /**
+ * Hints to image calls where the system might cache computed intermediates (e.g. the results
+ * of decoding or a read-back from the GPU. Passing kAllow signals that the system's default
+ * behavior is fine. Passing kDisallow signals that caching should be avoided.
+ */
+ enum CachingHint {
+ kAllow_CachingHint,
+ kDisallow_CachingHint,
+ };
+
+ /**
+ * Copy the pixels from the image into the specified buffer (pixels + rowBytes),
+ * converting them into the requested format (dstInfo). The image pixels are read
+ * starting at the specified (srcX,srcY) location.
+ *
+ * The specified ImageInfo and (srcX,srcY) offset specifies a source rectangle
+ *
+ * srcR.setXYWH(srcX, srcY, dstInfo.width(), dstInfo.height());
+ *
+ * srcR is intersected with the bounds of the image. If this intersection is not empty,
+ * then we have two sets of pixels (of equal size). Replace the dst pixels with the
+ * corresponding src pixels, performing any colortype/alphatype transformations needed
+ * (in the case where the src and dst have different colortypes or alphatypes).
+ *
+ * This call can fail, returning false, for several reasons:
+ * - If srcR does not intersect the image bounds.
+ * - If the requested colortype/alphatype cannot be converted from the image's types.
+ */
+ bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
+ int srcX, int srcY, CachingHint = kAllow_CachingHint) const;
+
+ bool readPixels(const SkPixmap& dst, int srcX, int srcY,
+ CachingHint = kAllow_CachingHint) const;
+
+ /**
+ * Copy the pixels from this image into the dst pixmap, converting as needed into dst's
+ * colortype/alphatype. If the conversion cannot be performed, false is returned.
+ *
+ * If dst's dimensions differ from the src dimension, the image will be scaled, applying the
+ * specified filter-quality.
+ */
+ bool scalePixels(const SkPixmap& dst, SkFilterQuality, CachingHint = kAllow_CachingHint) const;
+
/**
* Encode the image's pixels and return the result as a new SkData, which
* the caller must manage (i.e. call unref() when they are done).
*
* If the image type cannot be encoded, or the requested encoder type is
* not supported, this will return NULL.
+ *
+ * Note: this will attempt to encode the image's pixels in the specified format,
+ * even if the image returns a data from refEncoded(). That data will be ignored.
*/
- SkData* encode(SkImageEncoder::Type t = SkImageEncoder::kPNG_Type,
- int quality = 80) const;
+ SkData* encode(SkImageEncoder::Type, int quality) const;
+
+ /**
+ * Encode the image and return the result as a caller-managed SkData. This will
+ * attempt to reuse existing encoded data (as returned by refEncoded).
+ *
+ * We defer to the SkPixelSerializer both for vetting existing encoded data
+ * (useEncodedData) and for encoding the image (encodePixels) when no such data is
+ * present or is rejected by the serializer.
+ *
+ * If not specified, we use a default serializer which 1) always accepts existing data
+ * (in any format) and 2) encodes to PNG.
+ *
+ * If no compatible encoded data exists and encoding fails, this method will also
+ * fail (return NULL).
+ */
+ SkData* encode(SkPixelSerializer* = nullptr) const;
+
+ /**
+ * If the image already has its contents in encoded form (e.g. PNG or JPEG), return a ref
+ * to that data (which the caller must call unref() on). The caller is responsible for calling
+ * unref on the data when they are done.
+ *
+ * If the image does not already has its contents in encoded form, return NULL.
+ *
+ * Note: to force the image to return its contents as encoded data, try calling encode(...).
+ */
+ SkData* refEncoded() const;
+
+ const char* toString(SkString*) const;
+
+ /**
+ * Return a new image that is a subset of this image. The underlying implementation may
+ * share the pixels, or it may make a copy.
+ *
+ * If subset does not intersect the bounds of this image, or the copy/share cannot be made,
+ * NULL will be returned.
+ */
+ SkImage* newSubset(const SkIRect& subset) const;
+
+ // Helper functions to convert to SkBitmap
+
+ enum LegacyBitmapMode {
+ kRO_LegacyBitmapMode,
+ kRW_LegacyBitmapMode,
+ };
+
+ /**
+ * Attempt to create a bitmap with the same pixels as the image. The result will always be
+ * a raster-backed bitmap (texture-backed bitmaps are DEPRECATED, and not supported here).
+ *
+ * If the mode is kRO (read-only), the resulting bitmap will be marked as immutable.
+ *
+ * On succcess, returns true. On failure, returns false and the bitmap parameter will be reset
+ * to empty.
+ */
+ bool asLegacyBitmap(SkBitmap*, LegacyBitmapMode) const;
+
+ /**
+ * Returns true if the image is backed by an image-generator or other src that creates
+ * (and caches) its pixels / texture on-demand.
+ */
+ bool isLazyGenerated() const;
+
+ /**
+ * Apply the specified filter to this image, and return the result as a new image.
+ *
+ * if forceResultToOriginalSize is true, then the resulting image will be the same size as the
+ * src, regardless of the normal output of the filter.
+ *
+ * If offset is non-null, it is set to the relative offset needed to draw the resulting image
+ * in the same logical place as the original.
+ *
+ * e.g.
+ * If the filter makes the result larger by a margin of 4 the output would be:
+ * result->width() == this->width + 8
+ * result->height() == this->height + 8
+ * offset.x() == -4
+ * offset.y() == -4
+ *
+ * If the filter fails to create a resulting image, null is returned, and the offset parameter
+ * (if specified) will be undefined.
+ */
+ SkImage* applyFilter(SkImageFilter* filter, SkIPoint* offset,
+ bool forceResultToOriginalSize) const;
protected:
- SkImage(int width, int height) :
- fWidth(width),
- fHeight(height),
- fUniqueID(NextUniqueID()) {
-
- SkASSERT(width >= 0);
- SkASSERT(height >= 0);
- }
+ SkImage(int width, int height, uint32_t uniqueID);
private:
const int fWidth;
const int fHeight;
const uint32_t fUniqueID;
- static uint32_t NextUniqueID();
-
typedef SkRefCnt INHERITED;
-
- /**
- * Return a copy of the image's pixels, limiting them to the subset
- * rectangle's intersection wit the image bounds. If subset is NULL, then
- * the entire image will be considered.
- *
- * If the bitmap's pixels have already been allocated, then readPixels()
- * will succeed only if it can support converting the image's pixels into
- * the bitmap's ColorType/AlphaType. Any pixels in the bitmap that do not
- * intersect with the image's bounds and the subset (if not null) will be
- * left untouched.
- *
- * If the bitmap is initially empty/unallocated, then it will be allocated
- * using the default allocator, and the ColorType/AlphaType will be chosen
- * to most closely fit the image's configuration.
- *
- * On failure, false will be returned, and bitmap will unmodified.
- */
- // On ice for now:
- // - should it respect the particular colortype/alphatype of the src
- // - should it have separate entrypoints for preallocated and not bitmaps?
- // - isn't it enough to allow the caller to draw() the image into a canvas?
- bool readPixels(SkBitmap* bitmap, const SkIRect* subset = NULL) const;
};
#endif
diff --git a/gfx/skia/skia/include/core/SkImageDecoder.h b/gfx/skia/skia/include/core/SkImageDecoder.h
index b258afedce..30323b59ee 100644
--- a/gfx/skia/skia/include/core/SkImageDecoder.h
+++ b/gfx/skia/skia/include/core/SkImageDecoder.h
@@ -10,11 +10,14 @@
#include "SkBitmap.h"
#include "SkImage.h"
+#include "SkPngChunkReader.h"
#include "SkRect.h"
#include "SkRefCnt.h"
#include "SkTRegistry.h"
#include "SkTypes.h"
+//#define SK_LEGACY_PEEKER
+
class SkStream;
class SkStreamRewindable;
@@ -26,6 +29,7 @@ class SkImageDecoder : SkNoncopyable {
public:
virtual ~SkImageDecoder();
+ // TODO (scroggo): Merge with SkEncodedFormat
enum Format {
kUnknown_Format,
kBMP_Format,
@@ -37,6 +41,7 @@ public:
kWEBP_Format,
kPKM_Format,
kKTX_Format,
+ kASTC_Format,
kLastKnownFormat = kKTX_Format,
};
@@ -46,6 +51,15 @@ public:
*/
virtual Format getFormat() const;
+ /** If planes or rowBytes is NULL, decodes the header and computes componentSizes
+ for memory allocation.
+ Otherwise, decodes the YUV planes into the provided image planes and
+ updates componentSizes to the final image size.
+ Returns whether the decoding was successful.
+ */
+ bool decodeYUV8Planes(SkStream* stream, SkISize componentSizes[3], void* planes[3],
+ size_t rowBytes[3], SkYUVColorSpace*);
+
/** Return the format of the SkStreamRewindable or kUnknown_Format if it cannot be determined.
Rewinds the stream before returning.
*/
@@ -115,95 +129,20 @@ public:
*/
bool getRequireUnpremultipliedColors() const { return fRequireUnpremultipliedColors; }
- /** \class Peeker
-
- Base class for optional callbacks to retrieve meta/chunk data out of
- an image as it is being decoded.
- */
- class Peeker : public SkRefCnt {
+#ifdef SK_LEGACY_PEEKER
+ // Android subclasses SkImageDecoder::Peeker, which has been changed into SkPngChunkReader.
+ // Temporarily use this class until Android can be updated to directly inherit from
+ // SkPngChunkReader.
+ class Peeker : public SkPngChunkReader {
public:
- SK_DECLARE_INST_COUNT(Peeker)
-
- /** Return true to continue decoding, or false to indicate an error, which
- will cause the decoder to not return the image.
- */
+ bool readChunk(const char tag[], const void* data, size_t length) final {
+ return this->peek(tag, data, length);
+ }
virtual bool peek(const char tag[], const void* data, size_t length) = 0;
- private:
- typedef SkRefCnt INHERITED;
};
-
- Peeker* getPeeker() const { return fPeeker; }
- Peeker* setPeeker(Peeker*);
-
-#ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
- /** \class Chooser
-
- Base class for optional callbacks to choose an image from a format that
- contains multiple images.
- */
- class Chooser : public SkRefCnt {
- public:
- SK_DECLARE_INST_COUNT(Chooser)
-
- virtual void begin(int count) {}
- virtual void inspect(int index, SkBitmap::Config config, int width, int height) {}
- /** Return the index of the subimage you want, or -1 to choose none of them.
- */
- virtual int choose() = 0;
-
- private:
- typedef SkRefCnt INHERITED;
- };
-
- Chooser* getChooser() const { return fChooser; }
- Chooser* setChooser(Chooser*);
-#endif
-
-#ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
- /**
- * Optional table describing the caller's preferred config based on
- * information about the src data. Each field should be set to the
- * preferred config for a src described in the name of the field. The
- * src attributes are described in terms of depth (8-index,
- * 8bit-grayscale, or 8-bits/component) and whether there is per-pixel
- * alpha (does not apply to grayscale). If the caller has no preference
- * for a particular src type, its slot should be set to kNo_Config.
- *
- * NOTE ABOUT PREFERRED CONFIGS:
- * If a config is preferred, either using a pref table or as a parameter
- * to some flavor of decode, it is still at the discretion of the codec
- * as to what output config is actually returned, as it may not be able
- * to support the caller's preference.
- *
- * If a bitmap is decoded into SkBitmap::A8_Config, the resulting bitmap
- * will either be a conversion of the grayscale in the case of a
- * grayscale source or the alpha channel in the case of a source with
- * an alpha channel.
- */
- struct PrefConfigTable {
- SkBitmap::Config fPrefFor_8Index_NoAlpha_src;
- SkBitmap::Config fPrefFor_8Index_YesAlpha_src;
- SkBitmap::Config fPrefFor_8Gray_src;
- SkBitmap::Config fPrefFor_8bpc_NoAlpha_src;
- SkBitmap::Config fPrefFor_8bpc_YesAlpha_src;
- };
-
- /**
- * Set an optional table for specifying the caller's preferred config
- * based on information about the src data.
- *
- * The default is no preference, which will assume the config set by
- * decode is preferred.
- */
- void setPrefConfigTable(const PrefConfigTable&);
-
- /**
- * Do not use a PrefConfigTable to determine the output config. This
- * is the default, so there is no need to call unless a PrefConfigTable
- * was previously set.
- */
- void resetPrefConfigTable() { fUsePrefTable = false; }
#endif
+ SkPngChunkReader* getPeeker() const { return fPeeker; }
+ SkPngChunkReader* setPeeker(SkPngChunkReader*);
/**
* By default, the codec will try to comply with the "pref" colortype
@@ -261,13 +200,26 @@ public:
kDecodePixels_Mode //!< return entire bitmap (including pixels)
};
+ /** Result of a decode. If read as a boolean, a partial success is
+ considered a success (true).
+ */
+ enum Result {
+ kFailure = 0, //!< Image failed to decode. bitmap will be
+ // unchanged.
+ kPartialSuccess = 1, //!< Part of the image decoded. The rest is
+ // filled in automatically
+ kSuccess = 2 //!< The entire image was decoded, if Mode is
+ // kDecodePixels_Mode, or the bounds were
+ // decoded, in kDecodeBounds_Mode.
+ };
+
/** Given a stream, decode it into the specified bitmap.
If the decoder can decompress the image, it calls bitmap.setInfo(),
and then if the Mode is kDecodePixels_Mode, call allocPixelRef(),
which will allocated a pixelRef. To access the pixel memory, the codec
needs to call lockPixels/unlockPixels on the
bitmap. It can then set the pixels with the decompressed image.
- * If the image cannot be decompressed, return false. After the
+ * If the image cannot be decompressed, return kFailure. After the
* decoding, the function converts the decoded colortype in bitmap
* to pref if possible. Whether a conversion is feasible is
* tested by Bitmap::canCopyTo(pref).
@@ -277,32 +229,14 @@ public:
to allocate the memory from a cache, volatile memory, or even from
an existing bitmap's memory.
- If a Peeker is installed via setPeeker, it may be used to peek into
- meta data during the decode.
+ If an SkPngChunkReader is installed via setPeeker, it may be used to
+ peek into meta data during the decode.
*/
- bool decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode);
- bool decode(SkStream* stream, SkBitmap* bitmap, Mode mode) {
+ Result decode(SkStream*, SkBitmap* bitmap, SkColorType pref, Mode);
+ Result decode(SkStream* stream, SkBitmap* bitmap, Mode mode) {
return this->decode(stream, bitmap, kUnknown_SkColorType, mode);
}
- /**
- * Given a stream, build an index for doing tile-based decode.
- * The built index will be saved in the decoder, and the image size will
- * be returned in width and height.
- *
- * Return true for success or false on failure.
- */
- bool buildTileIndex(SkStreamRewindable*, int *width, int *height);
-
- /**
- * Decode a rectangle subset in the image.
- * The method can only be called after buildTileIndex().
- *
- * Return true for success.
- * Return false if the index is never built or failing in decoding.
- */
- bool decodeSubset(SkBitmap* bm, const SkIRect& subset, SkColorType pref);
-
/** Given a stream, this will try to find an appropriate decoder object.
If none is found, the method returns NULL.
*/
@@ -311,8 +245,7 @@ public:
/** Decode the image stored in the specified file, and store the result
in bitmap. Return true for success or false on failure.
- @param pref If the PrefConfigTable is not set, prefer this colortype.
- See NOTE ABOUT PREFERRED CONFIGS.
+ @param pref Prefer this colortype.
@param format On success, if format is non-null, it is set to the format
of the decoded file. On failure it is ignored.
@@ -326,8 +259,7 @@ public:
/** Decode the image stored in the specified memory buffer, and store the
result in bitmap. Return true for success or false on failure.
- @param pref If the PrefConfigTable is not set, prefer this colortype.
- See NOTE ABOUT PREFERRED CONFIGS.
+ @param pref Prefer this colortype.
@param format On success, if format is non-null, it is set to the format
of the decoded buffer. On failure it is ignored.
@@ -338,26 +270,10 @@ public:
return DecodeMemory(buffer, size, bitmap, kUnknown_SkColorType, kDecodePixels_Mode, NULL);
}
- /**
- * Struct containing information about a pixel destination.
- */
- struct Target {
- /**
- * Pre-allocated memory.
- */
- void* fAddr;
-
- /**
- * Rowbytes of the allocated memory.
- */
- size_t fRowBytes;
- };
-
/** Decode the image stored in the specified SkStreamRewindable, and store the result
in bitmap. Return true for success or false on failure.
- @param pref If the PrefConfigTable is not set, prefer this colortype.
- See NOTE ABOUT PREFERRED CONFIGS.
+ @param pref Prefer this colortype.
@param format On success, if format is non-null, it is set to the format
of the decoded stream. On failure it is ignored.
@@ -370,39 +286,20 @@ public:
protected:
// must be overridden in subclasses. This guy is called by decode(...)
- virtual bool onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
+ virtual Result onDecode(SkStream*, SkBitmap* bitmap, Mode) = 0;
- // If the decoder wants to support tiled based decoding,
- // this method must be overridden. This guy is called by buildTileIndex(...)
- virtual bool onBuildTileIndex(SkStreamRewindable*, int *width, int *height) {
+ /** If planes or rowBytes is NULL, decodes the header and computes componentSizes
+ for memory allocation.
+ Otherwise, decodes the YUV planes into the provided image planes and
+ updates componentSizes to the final image size.
+ Returns whether the decoding was successful.
+ */
+ virtual bool onDecodeYUV8Planes(SkStream*, SkISize[3] /*componentSizes*/,
+ void*[3] /*planes*/, size_t[3] /*rowBytes*/,
+ SkYUVColorSpace*) {
return false;
}
- // If the decoder wants to support tiled based decoding,
- // this method must be overridden. This guy is called by decodeRegion(...)
- virtual bool onDecodeSubset(SkBitmap* bitmap, const SkIRect& rect) {
- return false;
- }
-
- /*
- * Crop a rectangle from the src Bitmap to the dest Bitmap. src and dst are
- * both sampled by sampleSize from an original Bitmap.
- *
- * @param dst the destination bitmap.
- * @param src the source bitmap that is sampled by sampleSize from the
- * original bitmap.
- * @param sampleSize the sample size that src is sampled from the original bitmap.
- * @param (dstX, dstY) the upper-left point of the dest bitmap in terms of
- * the coordinate in the original bitmap.
- * @param (width, height) the width and height of the unsampled dst.
- * @param (srcX, srcY) the upper-left point of the src bitmap in terms of
- * the coordinate in the original bitmap.
- * @return bool Whether or not it succeeded.
- */
- bool cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize,
- int dstX, int dstY, int width, int height,
- int srcX, int srcY);
-
/**
* Copy all fields on this decoder to the other decoder. Used by subclasses
* to decode a subimage using a different decoder, but with the same settings.
@@ -428,12 +325,6 @@ protected:
* Return the default preference being used by the current or latest call to decode.
*/
SkColorType getDefaultPref() { return fDefaultPref; }
-
-#ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
- // helper function for decoders to handle the (common) case where there is only
- // once choice available in the image file.
- bool chooseFromOneChoice(SkColorType, int width, int height) const;
-#endif
/* Helper for subclasses. Call this to allocate the pixel memory given the bitmap's info.
Returns true on success. This method handles checking for an optional Allocator.
@@ -459,17 +350,10 @@ protected:
SkColorType getPrefColorType(SrcDepth, bool hasAlpha) const;
private:
- Peeker* fPeeker;
-#ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER
- Chooser* fChooser;
-#endif
+ SkPngChunkReader* fPeeker;
SkBitmap::Allocator* fAllocator;
int fSampleSize;
SkColorType fDefaultPref; // use if fUsePrefTable is false
-#ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
- PrefConfigTable fPrefTable; // use if fUsePrefTable is true
- bool fUsePrefTable;
-#endif
bool fPreserveSrcDepth;
bool fDitherImage;
bool fSkipWritingZeroes;
@@ -486,7 +370,7 @@ private:
*/
class SkImageDecoderFactory : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkImageDecoderFactory)
+
virtual SkImageDecoder* newDecoder(SkStreamRewindable*) = 0;
@@ -509,10 +393,8 @@ public:
// This macro defines the global creation entry point for each decoder. Each
// decoder implementation that registers with the decoder factory must call it.
-#define DEFINE_DECODER_CREATOR(codec) \
- SkImageDecoder *Create ## codec () { \
- return SkNEW( Sk ## codec ); \
- }
+#define DEFINE_DECODER_CREATOR(codec) \
+ SkImageDecoder* Create##codec() { return new Sk##codec; }
// All the decoders known by Skia. Note that, depending on the compiler settings,
// not all of these will be available
@@ -525,6 +407,7 @@ DECLARE_DECODER_CREATOR(WBMPImageDecoder);
DECLARE_DECODER_CREATOR(WEBPImageDecoder);
DECLARE_DECODER_CREATOR(PKMImageDecoder);
DECLARE_DECODER_CREATOR(KTXImageDecoder);
+DECLARE_DECODER_CREATOR(ASTCImageDecoder);
// Typedefs to make registering decoder and formatter callbacks easier.
// These have to be defined outside SkImageDecoder. :(
diff --git a/gfx/skia/skia/include/core/SkImageEncoder.h b/gfx/skia/skia/include/core/SkImageEncoder.h
index 4d4d2a83c0..fc999dcc18 100644
--- a/gfx/skia/skia/include/core/SkImageEncoder.h
+++ b/gfx/skia/skia/include/core/SkImageEncoder.h
@@ -1,14 +1,14 @@
-
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
+
#ifndef SkImageEncoder_DEFINED
#define SkImageEncoder_DEFINED
-#include "SkTypes.h"
+#include "SkImageInfo.h"
#include "SkTRegistry.h"
class SkBitmap;
@@ -17,6 +17,7 @@ class SkWStream;
class SkImageEncoder {
public:
+ // TODO (scroggo): Merge with SkEncodedFormat.
enum Type {
kUnknown_Type,
kBMP_Type,
@@ -59,7 +60,10 @@ public:
*/
bool encodeStream(SkWStream* stream, const SkBitmap& bm, int quality);
+ static SkData* EncodeData(const SkImageInfo&, const void* pixels, size_t rowBytes,
+ Type, int quality);
static SkData* EncodeData(const SkBitmap&, Type, int quality);
+
static bool EncodeFile(const char file[], const SkBitmap&, Type,
int quality);
static bool EncodeStream(SkWStream*, const SkBitmap&, Type,
@@ -83,10 +87,8 @@ protected:
// This macro defines the global creation entry point for each encoder. Each
// encoder implementation that registers with the encoder factory must call it.
-#define DEFINE_ENCODER_CREATOR(codec) \
- SkImageEncoder *Create ## codec () { \
- return SkNEW( Sk ## codec ); \
- }
+#define DEFINE_ENCODER_CREATOR(codec) \
+ SkImageEncoder* Create##codec() { return new Sk##codec; }
// All the encoders known by Skia. Note that, depending on the compiler settings,
// not all of these will be available
diff --git a/gfx/skia/skia/include/core/SkImageFilter.h b/gfx/skia/skia/include/core/SkImageFilter.h
index cd34ba3f91..d90df29c8b 100644
--- a/gfx/skia/skia/include/core/SkImageFilter.h
+++ b/gfx/skia/skia/include/core/SkImageFilter.h
@@ -8,17 +8,19 @@
#ifndef SkImageFilter_DEFINED
#define SkImageFilter_DEFINED
+#include "../private/SkTemplates.h"
+#include "SkFilterQuality.h"
#include "SkFlattenable.h"
#include "SkMatrix.h"
#include "SkRect.h"
-#include "SkTemplates.h"
+#include "SkSurfaceProps.h"
+class GrFragmentProcessor;
+class GrTexture;
+class SkBaseDevice;
class SkBitmap;
class SkColorFilter;
-class SkBaseDevice;
struct SkIPoint;
-class GrEffect;
-class GrTexture;
/**
* Base class for image filters. If one is installed in the paint, then
@@ -29,66 +31,109 @@ class GrTexture;
*/
class SK_API SkImageFilter : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkImageFilter)
+ // This cache maps from (filter's unique ID + CTM + clipBounds + src bitmap generation ID) to
+ // (result, offset).
+ class Cache : public SkRefCnt {
+ public:
+ struct Key;
+ virtual ~Cache() {}
+ static Cache* Create(size_t maxBytes);
+ static Cache* Get();
+ virtual bool get(const Key& key, SkBitmap* result, SkIPoint* offset) const = 0;
+ virtual void set(const Key& key, const SkBitmap& result, const SkIPoint& offset) = 0;
+ virtual void purge() {}
+ };
+
+ enum SizeConstraint {
+ kExact_SizeConstraint,
+ kApprox_SizeConstraint,
+ };
+
+ class Context {
+ public:
+ Context(const SkMatrix& ctm, const SkIRect& clipBounds, Cache* cache,
+ SizeConstraint constraint)
+ : fCTM(ctm)
+ , fClipBounds(clipBounds)
+ , fCache(cache)
+ , fSizeConstraint(constraint)
+ {}
+
+ const SkMatrix& ctm() const { return fCTM; }
+ const SkIRect& clipBounds() const { return fClipBounds; }
+ Cache* cache() const { return fCache; }
+ SizeConstraint sizeConstraint() const { return fSizeConstraint; }
+
+ private:
+ SkMatrix fCTM;
+ SkIRect fClipBounds;
+ Cache* fCache;
+ SizeConstraint fSizeConstraint;
+ };
class CropRect {
public:
enum CropEdge {
kHasLeft_CropEdge = 0x01,
kHasTop_CropEdge = 0x02,
- kHasRight_CropEdge = 0x04,
- kHasBottom_CropEdge = 0x08,
+ kHasWidth_CropEdge = 0x04,
+ kHasHeight_CropEdge = 0x08,
kHasAll_CropEdge = 0x0F,
};
CropRect() {}
- explicit CropRect(const SkRect& rect, uint32_t flags = kHasAll_CropEdge) : fRect(rect), fFlags(flags) {}
+ explicit CropRect(const SkRect& rect, uint32_t flags = kHasAll_CropEdge)
+ : fRect(rect), fFlags(flags) {}
uint32_t flags() const { return fFlags; }
const SkRect& rect() const { return fRect; }
+#ifndef SK_IGNORE_TO_STRING
+ void toString(SkString* str) const;
+#endif
+
+ /**
+ * Apply this cropRect to the imageBounds. If a given edge of the cropRect is not
+ * set, then the corresponding edge from imageBounds will be used.
+ *
+ * Note: imageBounds is in "device" space, as the output cropped rectangle will be,
+ * so the context's CTM is ignore for those. It is only applied the croprect's bounds.
+ *
+ * The resulting rect will be intersected with the context's clip. If that intersection is
+ * empty, then this returns false and cropped is unmodified.
+ */
+ bool applyTo(const SkIRect& imageBounds, const Context&, SkIRect* cropped) const;
+
private:
SkRect fRect;
uint32_t fFlags;
};
- class SK_API Cache : public SkRefCnt {
- public:
- // By default, we cache only image filters with 2 or more children.
- // Values less than 2 mean always cache; values greater than 2 are not supported.
- static Cache* Create(int minChildren = 2);
- virtual ~Cache() {}
- virtual bool get(const SkImageFilter* key, SkBitmap* result, SkIPoint* offset) = 0;
- virtual void set(const SkImageFilter* key,
- const SkBitmap& result, const SkIPoint& offset) = 0;
- virtual void remove(const SkImageFilter* key) = 0;
- };
-
- class Context {
- public:
- Context(const SkMatrix& ctm, const SkIRect& clipBounds, Cache* cache) :
- fCTM(ctm), fClipBounds(clipBounds), fCache(cache) {
- }
- const SkMatrix& ctm() const { return fCTM; }
- const SkIRect& clipBounds() const { return fClipBounds; }
- Cache* cache() const { return fCache; }
- private:
- SkMatrix fCTM;
- SkIRect fClipBounds;
- Cache* fCache;
- };
-
class Proxy {
public:
- virtual ~Proxy() {};
+ virtual ~Proxy() {}
virtual SkBaseDevice* createDevice(int width, int height) = 0;
- // returns true if the proxy can handle this filter natively
- virtual bool canHandleImageFilter(const SkImageFilter*) = 0;
- // returns true if the proxy handled the filter itself. if this returns
+
+ // Returns true if the proxy handled the filter itself. If this returns
// false then the filter's code will be called.
virtual bool filterImage(const SkImageFilter*, const SkBitmap& src,
- const Context&,
+ const SkImageFilter::Context&,
SkBitmap* result, SkIPoint* offset) = 0;
};
+ class DeviceProxy : public Proxy {
+ public:
+ DeviceProxy(SkBaseDevice* device) : fDevice(device) {}
+
+ SkBaseDevice* createDevice(int width, int height) override;
+
+ // Returns true if the proxy handled the filter itself. If this returns
+ // false then the filter's code will be called.
+ bool filterImage(const SkImageFilter*, const SkBitmap& src, const SkImageFilter::Context&,
+ SkBitmap* result, SkIPoint* offset) override;
+
+ private:
+ SkBaseDevice* fDevice;
+ };
+
/**
* Request a new (result) image to be created from the src image.
* If the src has no pixels (isNull()) then the request just wants to
@@ -114,8 +159,8 @@ public:
/**
* Returns true if the filter can be processed on the GPU. This is most
* often used for multi-pass effects, where intermediate results must be
- * rendered to textures. For single-pass effects, use asNewEffect().
- * The default implementation returns asNewEffect(NULL, NULL, SkMatrix::I(),
+ * rendered to textures. For single-pass effects, use asFragmentProcessor().
+ * The default implementation returns asFragmentProcessor(NULL, NULL, SkMatrix::I(),
* SkIRect()).
*/
virtual bool canFilterImageGPU() const;
@@ -123,12 +168,12 @@ public:
/**
* Process this image filter on the GPU. This is most often used for
* multi-pass effects, where intermediate results must be rendered to
- * textures. For single-pass effects, use asNewEffect(). src is the
+ * textures. For single-pass effects, use asFragmentProcessor(). src is the
* source image for processing, as a texture-backed bitmap. result is
* the destination bitmap, which should contain a texture-backed pixelref
* on success. offset is the amount to translate the resulting image
* relative to the src when it is drawn. The default implementation does
- * single-pass processing using asNewEffect().
+ * single-pass processing using asFragmentProcessor().
*/
virtual bool filterImageGPU(Proxy*, const SkBitmap& src, const Context&,
SkBitmap* result, SkIPoint* offset) const;
@@ -140,7 +185,26 @@ public:
* If this returns true, then if filterPtr is not null, it must be set to a ref'd colorfitler
* (i.e. it may not be set to NULL).
*/
- virtual bool asColorFilter(SkColorFilter** filterPtr) const;
+ bool isColorFilterNode(SkColorFilter** filterPtr) const {
+ return this->onIsColorFilterNode(filterPtr);
+ }
+
+ // DEPRECATED : use isColorFilterNode() instead
+ bool asColorFilter(SkColorFilter** filterPtr) const {
+ return this->isColorFilterNode(filterPtr);
+ }
+
+ /**
+ * Returns true (and optionally returns a ref'd filter) if this imagefilter can be completely
+ * replaced by the returned colorfilter. i.e. the two effects will affect drawing in the
+ * same way.
+ */
+ bool asAColorFilter(SkColorFilter** filterPtr) const {
+ return this->countInputs() > 0 &&
+ NULL == this->getInput(0) &&
+ !this->affectsTransparentBlack() &&
+ this->isColorFilterNode(filterPtr);
+ }
/**
* Returns the number of inputs this filter will accept (some inputs can
@@ -160,7 +224,8 @@ public:
/**
* Returns whether any edges of the crop rect have been set. The crop
* rect is set at construction time, and determines which pixels from the
- * input image will be processed. The size of the crop rect should be
+ * input image will be processed, and which pixels in the output image will be allowed.
+ * The size of the crop rect should be
* used as the size of the destination image. The origin of this rect
* should be used to offset access to the input images, and should also
* be added to the "offset" parameter in onFilterImage and
@@ -169,34 +234,44 @@ public:
*/
bool cropRectIsSet() const { return fCropRect.flags() != 0x0; }
+ CropRect getCropRect() const { return fCropRect; }
+
// Default impl returns union of all input bounds.
virtual void computeFastBounds(const SkRect&, SkRect*) const;
-#ifdef SK_SUPPORT_GPU
+ // Can this filter DAG compute the resulting bounds of an object-space rectangle?
+ bool canComputeFastBounds() const;
+
+ /**
+ * If this filter can be represented by another filter + a localMatrix, return that filter,
+ * else return null.
+ */
+ SkImageFilter* newWithLocalMatrix(const SkMatrix& matrix) const;
+
+ /**
+ * Create an SkMatrixImageFilter, which transforms its input by the given matrix.
+ */
+ static SkImageFilter* CreateMatrixFilter(const SkMatrix& matrix,
+ SkFilterQuality,
+ SkImageFilter* input = NULL);
+
+#if SK_SUPPORT_GPU
/**
* Wrap the given texture in a texture-backed SkBitmap.
*/
static void WrapTexture(GrTexture* texture, int width, int height, SkBitmap* result);
- /**
- * Recursively evaluate this filter on the GPU. If the filter has no GPU
- * implementation, it will be processed in software and uploaded to the GPU.
- */
- bool getInputResultGPU(SkImageFilter::Proxy* proxy, const SkBitmap& src, const Context&,
- SkBitmap* result, SkIPoint* offset) const;
+ // Helper function which invokes GPU filter processing on the
+ // input at the specified "index". If the input is null, it leaves
+ // "result" and "offset" untouched, and returns true. If the input
+ // has a GPU implementation, it will be invoked directly.
+ // Otherwise, the filter will be processed in software and
+ // uploaded to the GPU.
+ bool filterInputGPU(int index, SkImageFilter::Proxy* proxy, const SkBitmap& src, const Context&,
+ SkBitmap* result, SkIPoint* offset, bool relaxSizeConstraint = true) const;
#endif
- /**
- * Set an external cache to be used for all image filter processing. This
- * will replace the default intra-frame cache.
- */
- static void SetExternalCache(Cache* cache);
-
- /**
- * Returns the currently-set external cache, or NULL if none is set.
- */
- static Cache* GetExternalCache();
-
+ SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkImageFilter)
protected:
@@ -205,12 +280,22 @@ protected:
Common() {}
~Common();
- bool unflatten(SkReadBuffer&, int expectedInputs = -1);
+ /**
+ * Attempt to unflatten the cropRect and the expected number of input filters.
+ * If any number of input filters is valid, pass -1.
+ * If this fails (i.e. corrupt buffer or contents) then return false and common will
+ * be left uninitialized.
+ * If this returns true, then inputCount() is the number of found input filters, each
+ * of which may be NULL or a valid imagefilter.
+ */
+ bool unflatten(SkReadBuffer&, int expectedInputs);
- CropRect cropRect() const { return fCropRect; }
+ const CropRect& cropRect() const { return fCropRect; }
int inputCount() const { return fInputs.count(); }
SkImageFilter** inputs() const { return fInputs.get(); }
+ SkImageFilter* getInput(int index) const { return fInputs[index]; }
+
// If the caller wants a copy of the inputs, call this and it will transfer ownership
// of the unflattened input filters to the caller. This is just a short-cut for copying
// the inputs, calling ref() on each, and then waiting for Common's destructor to call
@@ -238,7 +323,7 @@ protected:
*/
explicit SkImageFilter(int inputCount, SkReadBuffer& rb);
- virtual void flatten(SkWriteBuffer& wb) const SK_OVERRIDE;
+ void flatten(SkWriteBuffer&) const override;
/**
* This is the virtual which should be overridden by the derived class
@@ -267,14 +352,34 @@ protected:
// no inputs.
virtual bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*) const;
- /** Computes source bounds as the src bitmap bounds offset by srcOffset.
- * Apply the transformed crop rect to the bounds if any of the
- * corresponding edge flags are set. Intersects the result against the
- * context's clipBounds, and returns the result in "bounds". If there is
- * no intersection, returns false and leaves "bounds" unchanged.
+ // Helper function which invokes filter processing on the input at the
+ // specified "index". If the input is null, it leaves "result" and
+ // "offset" untouched, and returns true. If the input is non-null, it
+ // calls filterImage() on that input, and returns true on success.
+ // i.e., return !getInput(index) || getInput(index)->filterImage(...);
+ bool filterInput(int index, Proxy*, const SkBitmap& src, const Context&,
+ SkBitmap* result, SkIPoint* offset, bool relaxSizeConstraint = true) const;
+
+ /**
+ * Return true (and return a ref'd colorfilter) if this node in the DAG is just a
+ * colorfilter w/o CropRect constraints.
+ */
+ virtual bool onIsColorFilterNode(SkColorFilter** /*filterPtr*/) const {
+ return false;
+ }
+
+ /** Given a "src" bitmap and its "srcOffset", computes source and
+ * destination bounds for this filter. Initial bounds are the
+ * "src" bitmap bounds offset by "srcOffset". "dstBounds" are
+ * computed by transforming the crop rect by the context's CTM,
+ * applying it to the initial bounds, and intersecting the result
+ * with the context's clip bounds. "srcBounds" (if non-null) are
+ * computed by intersecting the initial bounds with "dstBounds", to
+ * ensure that we never sample outside of the crop rect (this restriction
+ * may be relaxed in the future).
*/
bool applyCropRect(const Context&, const SkBitmap& src, const SkIPoint& srcOffset,
- SkIRect* bounds) const;
+ SkIRect* dstBounds, SkIRect* srcBounds = nullptr) const;
/** Same as the above call, except that if the resulting crop rect is not
* entirely contained by the source bitmap's bounds, it creates a new
@@ -289,10 +394,10 @@ protected:
/**
* Returns true if the filter can be expressed a single-pass
- * GrEffect, used to process this filter on the GPU, or false if
+ * GrProcessor, used to process this filter on the GPU, or false if
* not.
*
- * If effect is non-NULL, a new GrEffect instance is stored
+ * If effect is non-NULL, a new GrProcessor instance is stored
* in it. The caller assumes ownership of the stage, and it is up to the
* caller to unref it.
*
@@ -302,16 +407,40 @@ protected:
* will be called with (NULL, NULL, SkMatrix::I()) to query for support,
* so returning "true" indicates support for all possible matrices.
*/
- virtual bool asNewEffect(GrEffect** effect,
- GrTexture*,
- const SkMatrix& matrix,
- const SkIRect& bounds) const;
+ virtual bool asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix&,
+ const SkIRect& bounds) const;
+
+ /**
+ * Returns true if this filter can cause transparent black pixels to become
+ * visible (ie., alpha > 0). The default implementation returns false. This
+ * function is non-recursive, i.e., only queries this filter and not its
+ * inputs.
+ */
+ virtual bool affectsTransparentBlack() const;
private:
+ friend class SkGraphics;
+ static void PurgeCache();
+
+ bool usesSrcInput() const { return fUsesSrcInput; }
+
typedef SkFlattenable INHERITED;
int fInputCount;
SkImageFilter** fInputs;
+ bool fUsesSrcInput;
CropRect fCropRect;
+ uint32_t fUniqueID; // Globally unique
};
+/**
+ * Helper to unflatten the common data, and return NULL if we fail.
+ */
+#define SK_IMAGEFILTER_UNFLATTEN_COMMON(localVar, expectedCount) \
+ Common localVar; \
+ do { \
+ if (!localVar.unflatten(buffer, expectedCount)) { \
+ return NULL; \
+ } \
+ } while (0)
+
#endif
diff --git a/gfx/skia/skia/include/core/SkImageGenerator.h b/gfx/skia/skia/include/core/SkImageGenerator.h
index 17477e37b3..66db5e4884 100644
--- a/gfx/skia/skia/include/core/SkImageGenerator.h
+++ b/gfx/skia/skia/include/core/SkImageGenerator.h
@@ -8,12 +8,19 @@
#ifndef SkImageGenerator_DEFINED
#define SkImageGenerator_DEFINED
-#include "SkImageInfo.h"
+#include "SkBitmap.h"
#include "SkColor.h"
+#include "SkImageInfo.h"
+class GrContext;
+class GrTexture;
+class GrTextureParams;
class SkBitmap;
class SkData;
class SkImageGenerator;
+class SkMatrix;
+class SkPaint;
+class SkPicture;
/**
* Takes ownership of SkImageGenerator. If this method fails for
@@ -24,29 +31,28 @@ class SkImageGenerator;
* If generator is NULL, will safely return false.
*
* If this fails or when the SkDiscardablePixelRef that is
- * installed into destination is destroyed, it will call
- * SkDELETE() on the generator. Therefore, generator should be
- * allocated with SkNEW() or SkNEW_ARGS().
+ * installed into destination is destroyed, it will
+ * delete the generator. Therefore, generator should be
+ * allocated with new.
*
* @param destination Upon success, this bitmap will be
* configured and have a pixelref installed.
*
* @return true iff successful.
*/
-SK_API bool SkInstallDiscardablePixelRef(SkImageGenerator*, SkBitmap* destination);
+SK_API bool SkDEPRECATED_InstallDiscardablePixelRef(SkImageGenerator*, SkBitmap* destination);
/**
- * Purges all unlocked discardable memory in Skia's global
- * discardable memory pool.
+ * On success, installs a discardable pixelref into destination, based on encoded data.
+ * Regardless of success or failure, the caller must still balance their ownership of encoded.
*/
-SK_API void SkPurgeGlobalDiscardableMemoryPool();
-
+SK_API bool SkDEPRECATED_InstallDiscardablePixelRef(SkData* encoded, SkBitmap* destination);
/**
* An interface that allows a purgeable PixelRef (such as a
* SkDiscardablePixelRef) to decode and re-decode an image as needed.
*/
-class SK_API SkImageGenerator {
+class SK_API SkImageGenerator : public SkNoncopyable {
public:
/**
* The PixelRef which takes ownership of this SkImageGenerator
@@ -54,13 +60,8 @@ public:
*/
virtual ~SkImageGenerator() { }
-#ifdef SK_SUPPORT_LEGACY_IMAGEGENERATORAPI
- virtual SkData* refEncodedData() { return this->onRefEncodedData(); }
- virtual bool getInfo(SkImageInfo* info) { return this->onGetInfo(info); }
- virtual bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes) {
- return this->onGetPixels(info, pixels, rowBytes, NULL, NULL);
- }
-#else
+ uint32_t uniqueID() const { return fUniqueID; }
+
/**
* Return a ref to the encoded (i.e. compressed) representation,
* of this data.
@@ -71,15 +72,9 @@ public:
SkData* refEncodedData() { return this->onRefEncodedData(); }
/**
- * Return some information about the image, allowing the owner of
- * this object to allocate pixels.
- *
- * Repeated calls to this function should give the same results,
- * allowing the PixelRef to be immutable.
- *
- * @return false if anything goes wrong.
+ * Return the ImageInfo associated with this generator.
*/
- bool getInfo(SkImageInfo* info);
+ const SkImageInfo& getInfo() const { return fInfo; }
/**
* Decode into the given pixels, a block of memory of size at
@@ -97,6 +92,10 @@ public:
* different output-configs, which the implementation can
* decide to support or not.
*
+ * A size that does not match getInfo() implies a request
+ * to scale. If the generator cannot perform this scale,
+ * it will return kInvalidScale.
+ *
* If info is kIndex8_SkColorType, then the caller must provide storage for up to 256
* SkPMColor values in ctable. On success the generator must copy N colors into that storage,
* (where N is the logical number of table entries) and set ctableCount to N.
@@ -104,17 +103,16 @@ public:
* If info is not kIndex8_SkColorType, then the last two parameters may be NULL. If ctableCount
* is not null, it will be set to 0.
*
- * @return false if anything goes wrong or if the image info is
- * unsupported.
+ * @return true on success.
*/
bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
SkPMColor ctable[], int* ctableCount);
/**
- * Simplified version of getPixels() that asserts that info is NOT kIndex8_SkColorType.
+ * Simplified version of getPixels() that asserts that info is NOT kIndex8_SkColorType and
+ * uses the default Options.
*/
bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes);
-#endif
/**
* If planes or rowBytes is NULL or if any entry in planes is NULL or if any entry in rowBytes
@@ -127,15 +125,140 @@ public:
* associated YUV data into those planes of memory supplied by the caller. It should validate
* that the sizes match what it expected. If the sizes do not match, it should return false.
*/
- bool getYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3]);
+ bool getYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],
+ SkYUVColorSpace* colorSpace);
+
+ /**
+ * If the generator can natively/efficiently return its pixels as a GPU image (backed by a
+ * texture) this will return that image. If not, this will return NULL.
+ *
+ * Regarding the GrContext parameter:
+ *
+ * The caller may pass NULL for the context. In that case the generator may assume that its
+ * internal context is current. If it has no internal context, then it should just return
+ * null.
+ *
+ * If the caller passes a non-null context, then the generator should only succeed if:
+ * - it has no intrinsic context, and will use the caller's
+ * - its internal context is the same
+ * - it can somehow convert its texture into one that is valid for the provided context.
+ *
+ * Regarding the GrTextureParams parameter:
+ *
+ * If the context (the provided one or the generator's intrinsic one) determines that to
+ * support the specified usage, it must return a different sized texture it may,
+ * so the caller must inspect the texture's width/height and compare them to the generator's
+ * getInfo() width/height. For readback usage use GrTextureParams::ClampNoFilter()
+ */
+ GrTexture* generateTexture(GrContext*, const SkIRect* subset = nullptr);
+
+ struct SupportedSizes {
+ SkISize fSizes[2];
+ };
+
+ /**
+ * Some generators can efficiently scale their contents. If this is supported, the generator
+ * may only support certain scaled dimensions. Call this with the desired scale factor,
+ * and it will return true if scaling is supported, and in supportedSizes[] it will return
+ * the nearest supported dimensions.
+ *
+ * If no native scaling is supported, or scale is invalid (e.g. scale <= 0 || scale > 1)
+ * this will return false, and the supportedsizes will be undefined.
+ */
+ bool computeScaledDimensions(SkScalar scale, SupportedSizes*);
+
+ /**
+ * Scale the generator's pixels to fit into scaledSize.
+ * This routine also support retrieving only a subset of the pixels. That subset is specified
+ * by the following rectangle (in the scaled space):
+ *
+ * subset = SkIRect::MakeXYWH(subsetOrigin.x(), subsetOrigin.y(),
+ * subsetPixels.width(), subsetPixels.height())
+ *
+ * If subset is not contained inside the scaledSize, this returns false.
+ *
+ * whole = SkIRect::MakeWH(scaledSize.width(), scaledSize.height())
+ * if (!whole.contains(subset)) {
+ * return false;
+ * }
+ *
+ * If the requested colortype/alphatype in pixels is not supported,
+ * or the requested scaledSize is not supported, or the generator encounters an error,
+ * this returns false.
+ */
+ bool generateScaledPixels(const SkISize& scaledSize, const SkIPoint& subsetOrigin,
+ const SkPixmap& subsetPixels);
+
+ bool generateScaledPixels(const SkPixmap& scaledPixels) {
+ return this->generateScaledPixels(SkISize::Make(scaledPixels.width(),
+ scaledPixels.height()),
+ SkIPoint::Make(0, 0), scaledPixels);
+ }
+
+ /**
+ * If the default image decoder system can interpret the specified (encoded) data, then
+ * this returns a new ImageGenerator for it. Otherwise this returns NULL. Either way
+ * the caller is still responsible for managing their ownership of the data.
+ */
+ static SkImageGenerator* NewFromEncoded(SkData*);
+
+ /** Return a new image generator backed by the specified picture. If the size is empty or
+ * the picture is NULL, this returns NULL.
+ * The optional matrix and paint arguments are passed to drawPicture() at rasterization
+ * time.
+ */
+ static SkImageGenerator* NewFromPicture(const SkISize&, const SkPicture*, const SkMatrix*,
+ const SkPaint*);
+
+ bool tryGenerateBitmap(SkBitmap* bm) {
+ return this->tryGenerateBitmap(bm, nullptr, nullptr);
+ }
+ bool tryGenerateBitmap(SkBitmap* bm, const SkImageInfo& info, SkBitmap::Allocator* allocator) {
+ return this->tryGenerateBitmap(bm, &info, allocator);
+ }
+ void generateBitmap(SkBitmap* bm) {
+ if (!this->tryGenerateBitmap(bm, nullptr, nullptr)) {
+ sk_throw();
+ }
+ }
+ void generateBitmap(SkBitmap* bm, const SkImageInfo& info) {
+ if (!this->tryGenerateBitmap(bm, &info, nullptr)) {
+ sk_throw();
+ }
+ }
protected:
+ SkImageGenerator(const SkImageInfo& info);
+
virtual SkData* onRefEncodedData();
- virtual bool onGetInfo(SkImageInfo* info);
- virtual bool onGetPixels(const SkImageInfo& info,
- void* pixels, size_t rowBytes,
+
+ virtual bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
SkPMColor ctable[], int* ctableCount);
virtual bool onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3]);
+ virtual bool onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],
+ SkYUVColorSpace* colorSpace);
+
+ virtual GrTexture* onGenerateTexture(GrContext*, const SkIRect*) {
+ return nullptr;
+ }
+
+ virtual bool onComputeScaledDimensions(SkScalar, SupportedSizes*) {
+ return false;
+ }
+ virtual bool onGenerateScaledPixels(const SkISize&, const SkIPoint&, const SkPixmap&) {
+ return false;
+ }
+
+ bool tryGenerateBitmap(SkBitmap* bm, const SkImageInfo* optionalInfo, SkBitmap::Allocator*);
+
+private:
+ const SkImageInfo fInfo;
+ const uint32_t fUniqueID;
+
+ // This is our default impl, which may be different on different platforms.
+ // It is called from NewFromEncoded() after it has checked for any runtime factory.
+ // The SkData will never be NULL, as that will have been checked by NewFromEncoded.
+ static SkImageGenerator* NewFromEncodedImpl(SkData*);
};
#endif // SkImageGenerator_DEFINED
diff --git a/gfx/skia/skia/include/core/SkImageInfo.h b/gfx/skia/skia/include/core/SkImageInfo.h
index 3d82dc805c..4b82ae6e2f 100644
--- a/gfx/skia/skia/include/core/SkImageInfo.h
+++ b/gfx/skia/skia/include/core/SkImageInfo.h
@@ -9,21 +9,17 @@
#define SkImageInfo_DEFINED
#include "SkMath.h"
+#include "SkRect.h"
#include "SkSize.h"
-class SkWriteBuffer;
class SkReadBuffer;
+class SkWriteBuffer;
/**
- * Describes how to interpret the alpha compoent of a pixel.
+ * Describes how to interpret the alpha component of a pixel.
*/
enum SkAlphaType {
- /**
- * All pixels should be treated as opaque, regardless of the value stored
- * in their alpha field. Used for legacy images that wrote 0 or garbarge
- * in their alpha field, but intended the RGB to be treated as opaque.
- */
- kIgnore_SkAlphaType,
+ kUnknown_SkAlphaType,
/**
* All pixels are stored as opaque. This differs slightly from kIgnore in
@@ -52,11 +48,7 @@ enum SkAlphaType {
};
static inline bool SkAlphaTypeIsOpaque(SkAlphaType at) {
- SK_COMPILE_ASSERT(kIgnore_SkAlphaType < kOpaque_SkAlphaType, bad_alphatype_order);
- SK_COMPILE_ASSERT(kPremul_SkAlphaType > kOpaque_SkAlphaType, bad_alphatype_order);
- SK_COMPILE_ASSERT(kUnpremul_SkAlphaType > kOpaque_SkAlphaType, bad_alphatype_order);
-
- return (unsigned)at <= kOpaque_SkAlphaType;
+ return kOpaque_SkAlphaType == at;
}
static inline bool SkAlphaTypeIsValid(unsigned value) {
@@ -80,19 +72,16 @@ enum SkColorType {
kRGBA_8888_SkColorType,
kBGRA_8888_SkColorType,
kIndex_8_SkColorType,
+ kGray_8_SkColorType,
- kLastEnum_SkColorType = kIndex_8_SkColorType,
+ kLastEnum_SkColorType = kGray_8_SkColorType,
#if SK_PMCOLOR_BYTE_ORDER(B,G,R,A)
kN32_SkColorType = kBGRA_8888_SkColorType,
#elif SK_PMCOLOR_BYTE_ORDER(R,G,B,A)
kN32_SkColorType = kRGBA_8888_SkColorType,
#else
-#error "SK_*32_SHFIT values must correspond to BGRA or RGBA byte order"
-#endif
-
-#ifdef SK_SUPPORT_LEGACY_N32_NAME
- kPMColor_SkColorType = kN32_SkColorType
+ #error "SK_*32_SHFIT values must correspond to BGRA or RGBA byte order"
#endif
};
@@ -105,9 +94,10 @@ static int SkColorTypeBytesPerPixel(SkColorType ct) {
4, // RGBA_8888
4, // BGRA_8888
1, // kIndex_8
+ 1, // kGray_8
};
- SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gSize) == (size_t)(kLastEnum_SkColorType + 1),
- size_mismatch_with_SkColorType_enum);
+ static_assert(SK_ARRAY_COUNT(gSize) == (size_t)(kLastEnum_SkColorType + 1),
+ "size_mismatch_with_SkColorType_enum");
SkASSERT((size_t)ct < SK_ARRAY_COUNT(gSize));
return gSize[ct];
@@ -121,6 +111,17 @@ static inline bool SkColorTypeIsValid(unsigned value) {
return value <= kLastEnum_SkColorType;
}
+static inline size_t SkColorTypeComputeOffset(SkColorType ct, int x, int y, size_t rowBytes) {
+ int shift = 0;
+ switch (SkColorTypeBytesPerPixel(ct)) {
+ case 4: shift = 2; break;
+ case 2: shift = 1; break;
+ case 1: shift = 0; break;
+ default: return 0;
+ }
+ return y * rowBytes + (x << shift);
+}
+
///////////////////////////////////////////////////////////////////////////////
/**
@@ -133,73 +134,92 @@ bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,
///////////////////////////////////////////////////////////////////////////////
/**
- * Describe an image's dimensions and pixel type.
+ * Describes the color space a YUV pixel.
*/
-struct SkImageInfo {
- int fWidth;
- int fHeight;
- SkColorType fColorType;
- SkAlphaType fAlphaType;
+enum SkYUVColorSpace {
+ /** Standard JPEG color space. */
+ kJPEG_SkYUVColorSpace,
+ /** SDTV standard Rec. 601 color space. Uses "studio swing" [16, 235] color
+ range. See http://en.wikipedia.org/wiki/Rec._601 for details. */
+ kRec601_SkYUVColorSpace,
+ /** HDTV standard Rec. 709 color space. Uses "studio swing" [16, 235] color
+ range. See http://en.wikipedia.org/wiki/Rec._709 for details. */
+ kRec709_SkYUVColorSpace,
- static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at) {
- SkImageInfo info = {
- width, height, ct, at
- };
- return info;
+ kLastEnum_SkYUVColorSpace = kRec709_SkYUVColorSpace
+};
+
+///////////////////////////////////////////////////////////////////////////////
+
+enum SkColorProfileType {
+ kLinear_SkColorProfileType,
+ kSRGB_SkColorProfileType,
+
+ kLastEnum_SkColorProfileType = kSRGB_SkColorProfileType
+};
+
+/**
+ * Describe an image's dimensions and pixel type.
+ * Used for both src images and render-targets (surfaces).
+ */
+struct SK_API SkImageInfo {
+public:
+ SkImageInfo()
+ : fWidth(0)
+ , fHeight(0)
+ , fColorType(kUnknown_SkColorType)
+ , fAlphaType(kUnknown_SkAlphaType)
+ , fProfileType(kLinear_SkColorProfileType)
+ {}
+
+ static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at,
+ SkColorProfileType pt = kLinear_SkColorProfileType) {
+ return SkImageInfo(width, height, ct, at, pt);
}
/**
* Sets colortype to the native ARGB32 type.
*/
- static SkImageInfo MakeN32(int width, int height, SkAlphaType at) {
- SkImageInfo info = {
- width, height, kN32_SkColorType, at
- };
- return info;
+ static SkImageInfo MakeN32(int width, int height, SkAlphaType at,
+ SkColorProfileType pt = kLinear_SkColorProfileType) {
+ return SkImageInfo(width, height, kN32_SkColorType, at, pt);
}
/**
* Sets colortype to the native ARGB32 type, and the alphatype to premul.
*/
- static SkImageInfo MakeN32Premul(int width, int height) {
- SkImageInfo info = {
- width, height, kN32_SkColorType, kPremul_SkAlphaType
- };
- return info;
+ static SkImageInfo MakeN32Premul(int width, int height,
+ SkColorProfileType pt = kLinear_SkColorProfileType) {
+ return SkImageInfo(width, height, kN32_SkColorType, kPremul_SkAlphaType, pt);
}
/**
* Sets colortype to the native ARGB32 type, and the alphatype to premul.
*/
- static SkImageInfo MakeN32Premul(const SkISize& size) {
- return MakeN32Premul(size.width(), size.height());
+ static SkImageInfo MakeN32Premul(const SkISize& size,
+ SkColorProfileType pt = kLinear_SkColorProfileType) {
+ return MakeN32Premul(size.width(), size.height(), pt);
}
static SkImageInfo MakeA8(int width, int height) {
- SkImageInfo info = {
- width, height, kAlpha_8_SkColorType, kPremul_SkAlphaType
- };
- return info;
+ return SkImageInfo(width, height, kAlpha_8_SkColorType, kPremul_SkAlphaType,
+ kLinear_SkColorProfileType);
}
static SkImageInfo MakeUnknown(int width, int height) {
- SkImageInfo info = {
- width, height, kUnknown_SkColorType, kIgnore_SkAlphaType
- };
- return info;
+ return SkImageInfo(width, height, kUnknown_SkColorType, kUnknown_SkAlphaType,
+ kLinear_SkColorProfileType);
}
static SkImageInfo MakeUnknown() {
- SkImageInfo info = {
- 0, 0, kUnknown_SkColorType, kIgnore_SkAlphaType
- };
- return info;
+ return SkImageInfo();
}
int width() const { return fWidth; }
int height() const { return fHeight; }
SkColorType colorType() const { return fColorType; }
SkAlphaType alphaType() const { return fAlphaType; }
+ SkColorProfileType profileType() const { return fProfileType; }
bool isEmpty() const { return fWidth <= 0 || fHeight <= 0; }
@@ -207,14 +227,26 @@ struct SkImageInfo {
return SkAlphaTypeIsOpaque(fAlphaType);
}
+ bool isLinear() const { return kLinear_SkColorProfileType == fProfileType; }
+ bool isSRGB() const { return kSRGB_SkColorProfileType == fProfileType; }
+
SkISize dimensions() const { return SkISize::Make(fWidth, fHeight); }
+ SkIRect bounds() const { return SkIRect::MakeWH(fWidth, fHeight); }
/**
* Return a new ImageInfo with the same colortype and alphatype as this info,
* but with the specified width and height.
*/
SkImageInfo makeWH(int newWidth, int newHeight) const {
- return SkImageInfo::Make(newWidth, newHeight, fColorType, fAlphaType);
+ return SkImageInfo::Make(newWidth, newHeight, fColorType, fAlphaType, fProfileType);
+ }
+
+ SkImageInfo makeAlphaType(SkAlphaType newAlphaType) const {
+ return SkImageInfo::Make(fWidth, fHeight, fColorType, newAlphaType, fProfileType);
+ }
+
+ SkImageInfo makeColorType(SkColorType newColorType) const {
+ return SkImageInfo::Make(fWidth, fHeight, newColorType, fAlphaType, fProfileType);
}
int bytesPerPixel() const {
@@ -229,6 +261,12 @@ struct SkImageInfo {
return (size_t)this->minRowBytes64();
}
+ size_t computeOffset(int x, int y, size_t rowBytes) const {
+ SkASSERT((unsigned)x < (unsigned)fWidth);
+ SkASSERT((unsigned)y < (unsigned)fHeight);
+ return SkColorTypeComputeOffset(fColorType, x, y, rowBytes);
+ }
+
bool operator==(const SkImageInfo& other) const {
return 0 == memcmp(this, &other, sizeof(other));
}
@@ -247,7 +285,11 @@ struct SkImageInfo {
}
size_t getSafeSize(size_t rowBytes) const {
- return (size_t)this->getSafeSize64(rowBytes);
+ int64_t size = this->getSafeSize64(rowBytes);
+ if (!sk_64_isS32(size)) {
+ return 0;
+ }
+ return sk_64_asS32(size);
}
bool validRowBytes(size_t rowBytes) const {
@@ -256,6 +298,21 @@ struct SkImageInfo {
}
SkDEBUGCODE(void validate() const;)
+
+private:
+ int fWidth;
+ int fHeight;
+ SkColorType fColorType;
+ SkAlphaType fAlphaType;
+ SkColorProfileType fProfileType;
+
+ SkImageInfo(int width, int height, SkColorType ct, SkAlphaType at, SkColorProfileType pt)
+ : fWidth(width)
+ , fHeight(height)
+ , fColorType(ct)
+ , fAlphaType(at)
+ , fProfileType(pt)
+ {}
};
#endif
diff --git a/gfx/skia/skia/include/core/SkInstCnt.h b/gfx/skia/skia/include/core/SkInstCnt.h
deleted file mode 100644
index e4b43d130b..0000000000
--- a/gfx/skia/skia/include/core/SkInstCnt.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright 2012 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkInstCnt_DEFINED
-#define SkInstCnt_DEFINED
-
-/*
- * The instance counting system consists of three macros that create the
- * instance counting machinery. A class is added to the system by adding:
- * SK_DECLARE_INST_COUNT at the top of its declaration for derived classes
- * SK_DECLARE_INST_COUNT_ROOT at the top of its declaration for a root class
- * At the end of an application a call to all the "root" objects'
- * CheckInstanceCount methods should be made
- */
-#include "SkTypes.h"
-
-#if SK_ENABLE_INST_COUNT
-// Static variables inside member functions below may be defined multiple times
-// if Skia is being used as a dynamic library. Instance counting should be on
-// only for static builds. See bug skia:2058.
-#if defined(SKIA_DLL)
-#error Instance counting works only when Skia is built as a static library.
-#endif
-
-#include "SkOnce.h"
-#include "SkTArray.h"
-#include "SkThread.h"
-extern bool gPrintInstCount;
-
-// The non-root classes just register themselves with their parent
-#define SK_DECLARE_INST_COUNT(className) \
- SK_DECLARE_INST_COUNT_INTERNAL(className, \
- INHERITED::AddInstChild(CheckInstanceCount);)
-
-// The root classes registers a function to print out the memory stats when
-// the app ends
-#define SK_DECLARE_INST_COUNT_ROOT(className) \
- SK_DECLARE_INST_COUNT_INTERNAL(className, atexit(exitPrint);)
-
-#define SK_DECLARE_INST_COUNT_INTERNAL(className, initStep) \
- class SkInstanceCountHelper { \
- public: \
- SkInstanceCountHelper() { \
- SK_DECLARE_STATIC_ONCE(once); \
- SkOnce(&once, init); \
- sk_atomic_inc(GetInstanceCountPtr()); \
- } \
- \
- static void init() { \
- initStep \
- } \
- \
- SkInstanceCountHelper(const SkInstanceCountHelper&) { \
- sk_atomic_inc(GetInstanceCountPtr()); \
- } \
- \
- ~SkInstanceCountHelper() { \
- sk_atomic_dec(GetInstanceCountPtr()); \
- } \
- \
- static int32_t* GetInstanceCountPtr() { \
- static int32_t gInstanceCount; \
- return &gInstanceCount; \
- } \
- \
- static SkTArray*& GetChildren() { \
- static SkTArray* gChildren; \
- return gChildren; \
- } \
- \
- static void create_mutex(SkMutex** mutex) { \
- *mutex = SkNEW(SkMutex); \
- } \
- static SkBaseMutex& GetChildrenMutex() { \
- static SkMutex* childrenMutex; \
- SK_DECLARE_STATIC_ONCE(once); \
- SkOnce(&once, className::SkInstanceCountHelper::create_mutex, &childrenMutex);\
- return *childrenMutex; \
- } \
- \
- } fInstanceCountHelper; \
- \
- static int32_t GetInstanceCount() { \
- return *SkInstanceCountHelper::GetInstanceCountPtr(); \
- } \
- \
- static void exitPrint() { \
- CheckInstanceCount(0, true); \
- } \
- \
- static int CheckInstanceCount(int level = 0, bool cleanUp = false) { \
- if (gPrintInstCount && 0 != GetInstanceCount()) { \
- SkDebugf("%*c Leaked %s: %d\n", \
- 4*level, ' ', #className, \
- GetInstanceCount()); \
- } \
- if (NULL == SkInstanceCountHelper::GetChildren()) { \
- return GetInstanceCount(); \
- } \
- SkTArray* children = \
- SkInstanceCountHelper::GetChildren(); \
- int childCount = children->count(); \
- int count = GetInstanceCount(); \
- for (int i = 0; i < childCount; ++i) { \
- count -= (*(*children)[i])(level+1, cleanUp); \
- } \
- SkASSERT(count >= 0); \
- if (gPrintInstCount && childCount > 0 && count > 0) { \
- SkDebugf("%*c Leaked ???: %d\n", 4*(level + 1), ' ', count); \
- } \
- if (cleanUp) { \
- delete children; \
- SkInstanceCountHelper::GetChildren() = NULL; \
- } \
- return GetInstanceCount(); \
- } \
- \
- static void AddInstChild(int (*childCheckInstCnt)(int, bool)) { \
- if (CheckInstanceCount != childCheckInstCnt) { \
- SkAutoMutexAcquire ama(SkInstanceCountHelper::GetChildrenMutex()); \
- if (NULL == SkInstanceCountHelper::GetChildren()) { \
- SkInstanceCountHelper::GetChildren() = \
- new SkTArray; \
- } \
- SkInstanceCountHelper::GetChildren()->push_back(childCheckInstCnt); \
- } \
- }
-
-#else
-// Typically SK_ENABLE_INST_COUNT=0. Make sure the class declares public typedef INHERITED by
-// causing a compile-time error if the typedef is missing. This way SK_ENABLE_INST_COUNT=1 stays
-// compiling.
-#define SK_DECLARE_INST_COUNT(className) static void AddInstChild() { INHERITED::AddInstChild(); }
-#define SK_DECLARE_INST_COUNT_ROOT(className) static void AddInstChild() { }
-#endif
-
-// Following are deprecated. They are defined only for backwards API compatibility.
-#define SK_DECLARE_INST_COUNT_TEMPLATE(className) SK_DECLARE_INST_COUNT(className)
-#define SK_DEFINE_INST_COUNT(className)
-#define SK_DEFINE_INST_COUNT_TEMPLATE(templateInfo, className)
-
-#endif // SkInstCnt_DEFINED
diff --git a/gfx/skia/skia/include/core/SkMallocPixelRef.h b/gfx/skia/skia/include/core/SkMallocPixelRef.h
index 63ed19ae3c..ab337b9241 100644
--- a/gfx/skia/skia/include/core/SkMallocPixelRef.h
+++ b/gfx/skia/skia/include/core/SkMallocPixelRef.h
@@ -16,7 +16,6 @@
*/
class SK_API SkMallocPixelRef : public SkPixelRef {
public:
- SK_DECLARE_INST_COUNT(SkMallocPixelRef)
/**
* Return a new SkMallocPixelRef with the provided pixel storage, rowBytes,
* and optional colortable. The caller is responsible for managing the
@@ -43,6 +42,12 @@ public:
static SkMallocPixelRef* NewAllocate(const SkImageInfo& info,
size_t rowBytes, SkColorTable*);
+ /**
+ * Identical to NewAllocate, except all pixel bytes are zeroed.
+ */
+ static SkMallocPixelRef* NewZeroed(const SkImageInfo& info,
+ size_t rowBytes, SkColorTable*);
+
/**
* Return a new SkMallocPixelRef with the provided pixel storage,
* rowBytes, and optional colortable. On destruction, ReleaseProc
@@ -50,6 +55,11 @@ public:
*
* This pixelref will ref() the specified colortable (if not NULL).
*
+ * If ReleaseProc is NULL, the pixels will never be released. This
+ * can be useful if the pixels were stack allocated. However, such an
+ * SkMallocPixelRef must not live beyond its pixels (e.g. by copying
+ * an SkBitmap pointing to it, or drawing to an SkPicture).
+ *
* Returns NULL on failure.
*/
typedef void (*ReleaseProc)(void* addr, void* context);
@@ -77,9 +87,12 @@ public:
class PRFactory : public SkPixelRefFactory {
public:
- virtual SkPixelRef* create(const SkImageInfo&,
- size_t rowBytes,
- SkColorTable*) SK_OVERRIDE;
+ SkPixelRef* create(const SkImageInfo&, size_t rowBytes, SkColorTable*) override;
+ };
+
+ class ZeroedPRFactory : public SkPixelRefFactory {
+ public:
+ SkPixelRef* create(const SkImageInfo&, size_t rowBytes, SkColorTable*) override;
};
protected:
@@ -88,11 +101,17 @@ protected:
bool ownPixels);
virtual ~SkMallocPixelRef();
- virtual bool onNewLockPixels(LockRec*) SK_OVERRIDE;
- virtual void onUnlockPixels() SK_OVERRIDE;
- virtual size_t getAllocatedSizeInBytes() const SK_OVERRIDE;
+ bool onNewLockPixels(LockRec*) override;
+ void onUnlockPixels() override;
+ size_t getAllocatedSizeInBytes() const override;
private:
+ // Uses alloc to implement NewAllocate or NewZeroed.
+ static SkMallocPixelRef* NewUsing(void*(*alloc)(size_t),
+ const SkImageInfo&,
+ size_t rowBytes,
+ SkColorTable*);
+
void* fStorage;
SkColorTable* fCTable;
size_t fRB;
diff --git a/gfx/skia/skia/include/core/SkMask.h b/gfx/skia/skia/include/core/SkMask.h
index 5cfef970c5..7be6aff614 100644
--- a/gfx/skia/skia/include/core/SkMask.h
+++ b/gfx/skia/skia/include/core/SkMask.h
@@ -23,11 +23,10 @@ struct SkMask {
k3D_Format, //!< 3 8bit per pixl planes: alpha, mul, add
kARGB32_Format, //!< SkPMColor
kLCD16_Format, //!< 565 alpha for r/g/b
- kLCD32_Format //!< 888 alpha for r/g/b
};
enum {
- kCountMaskFormats = kLCD32_Format + 1
+ kCountMaskFormats = kLCD16_Format + 1
};
uint8_t* fImage;
@@ -86,26 +85,13 @@ struct SkMask {
return row + (x - fBounds.fLeft);
}
- /**
- * Return the address of the specified 32bit mask. In the debug build,
- * this asserts that the mask's format is kLCD32_Format, and that (x,y)
- * are contained in the mask's fBounds.
- */
- uint32_t* getAddrLCD32(int x, int y) const {
- SkASSERT(kLCD32_Format == fFormat);
- SkASSERT(fBounds.contains(x, y));
- SkASSERT(fImage != NULL);
- uint32_t* row = (uint32_t*)(fImage + (y - fBounds.fTop) * fRowBytes);
- return row + (x - fBounds.fLeft);
- }
-
/**
* Return the address of the specified 32bit mask. In the debug build,
* this asserts that the mask's format is 32bits, and that (x,y)
* are contained in the mask's fBounds.
*/
uint32_t* getAddr32(int x, int y) const {
- SkASSERT(kLCD32_Format == fFormat || kARGB32_Format == fFormat);
+ SkASSERT(kARGB32_Format == fFormat);
SkASSERT(fBounds.contains(x, y));
SkASSERT(fImage != NULL);
uint32_t* row = (uint32_t*)(fImage + (y - fBounds.fTop) * fRowBytes);
@@ -116,7 +102,7 @@ struct SkMask {
* Returns the address of the specified pixel, computing the pixel-size
* at runtime based on the mask format. This will be slightly slower than
* using one of the routines where the format is implied by the name
- * e.g. getAddr8 or getAddrLCD32.
+ * e.g. getAddr8 or getAddr32.
*
* x,y must be contained by the mask's bounds (this is asserted in the
* debug build, but not checked in the release build.)
diff --git a/gfx/skia/skia/include/core/SkMaskFilter.h b/gfx/skia/skia/include/core/SkMaskFilter.h
index 39925129a7..1fe1d9adaf 100644
--- a/gfx/skia/skia/include/core/SkMaskFilter.h
+++ b/gfx/skia/skia/include/core/SkMaskFilter.h
@@ -15,10 +15,14 @@
#include "SkMask.h"
#include "SkPaint.h"
-class GrContext;
+class GrClip;
+class GrDrawContext;
class GrPaint;
+class GrRenderTarget;
+class GrTextureProvider;
class SkBitmap;
class SkBlitter;
+class SkCachedData;
class SkMatrix;
class SkPath;
class SkRasterClip;
@@ -38,8 +42,6 @@ class SkStrokeRec;
*/
class SK_API SkMaskFilter : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkMaskFilter)
-
/** Returns the format of the resulting mask that this subclass will return
when its filterMask() method is called.
*/
@@ -63,32 +65,44 @@ public:
#if SK_SUPPORT_GPU
/**
- * Returns true if the filter can be expressed a single-pass GrEffect without requiring an
+ * Returns true if the filter can be expressed a single-pass GrProcessor without requiring an
* explicit input mask. Per-pixel, the effect receives the incoming mask's coverage as
* the input color and outputs the filtered covereage value. This means that each pixel's
* filtered coverage must only depend on the unfiltered mask value for that pixel and not on
* surrounding values.
*
- * If effect is non-NULL, a new GrEffect instance is stored in it. The caller assumes ownership
- * of the effect and must unref it.
+ * If effect is non-NULL, a new GrProcessor instance is stored in it. The caller assumes
+ * ownership of the effect and must unref it.
*/
- virtual bool asNewEffect(GrEffect** effect,
- GrTexture*,
- const SkMatrix& ctm) const;
+ virtual bool asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix& ctm) const;
/**
- * If asNewEffect() fails the filter may be implemented on the GPU by a subclass overriding
- * filterMaskGPU (declared below). That code path requires constructing a src mask as input.
- * Since that is a potentially expensive operation, the subclass must also override this
- * function to indicate whether filterTextureMaskGPU would succeeed if the mask were to be
- * created.
+ * If asFragmentProcessor() fails the filter may be implemented on the GPU by a subclass
+ * overriding filterMaskGPU (declared below). That code path requires constructing a
+ * src mask as input. Since that is a potentially expensive operation, the subclass must also
+ * override this function to indicate whether filterTextureMaskGPU would succeeed if the mask
+ * were to be created.
*
* 'maskRect' returns the device space portion of the mask that the filter needs. The mask
- * passed into 'filterMaskGPU' should have the same extent as 'maskRect' but be translated
- * to the upper-left corner of the mask (i.e., (maskRect.fLeft, maskRect.fTop) appears at
- * (0, 0) in the mask).
+ * passed into 'filterMaskGPU' should have the same extent as 'maskRect' but be
+ * translated to the upper-left corner of the mask (i.e., (maskRect.fLeft, maskRect.fTop)
+ * appears at (0, 0) in the mask).
+ *
+ * Logically, how this works is:
+ * canFilterMaskGPU is called
+ * if (it returns true)
+ * the returned mask rect is used for quick rejecting
+ * either directFilterMaskGPU or directFilterRRectMaskGPU is then called
+ * if (neither of them handle the blur)
+ * the mask rect is used to generate the mask
+ * filterMaskGPU is called to filter the mask
+ *
+ * TODO: this should work as:
+ * if (canFilterMaskGPU(devShape, ...)) // rect, rrect, drrect, path
+ * filterMaskGPU(devShape, ...)
+ * this would hide the RRect special case and the mask generation
*/
- virtual bool canFilterMaskGPU(const SkRect& devBounds,
+ virtual bool canFilterMaskGPU(const SkRRect& devRRect,
const SkIRect& clipBounds,
const SkMatrix& ctm,
SkRect* maskRect) const;
@@ -97,16 +111,22 @@ public:
* Try to directly render the mask filter into the target. Returns
* true if drawing was successful.
*/
- virtual bool directFilterMaskGPU(GrContext* context,
+ virtual bool directFilterMaskGPU(GrTextureProvider* texProvider,
+ GrDrawContext* drawContext,
GrPaint* grp,
+ const GrClip&,
+ const SkMatrix& viewMatrix,
const SkStrokeRec& strokeRec,
const SkPath& path) const;
/**
* Try to directly render a rounded rect mask filter into the target. Returns
* true if drawing was successful.
*/
- virtual bool directFilterRRectMaskGPU(GrContext* context,
+ virtual bool directFilterRRectMaskGPU(GrTextureProvider* texProvider,
+ GrDrawContext* drawContext,
GrPaint* grp,
+ const GrClip&,
+ const SkMatrix& viewMatrix,
const SkStrokeRec& strokeRec,
const SkRRect& rrect) const;
@@ -155,8 +175,6 @@ public:
protected:
SkMaskFilter() {}
- // empty for now, but lets get our subclass to remember to init us for the future
- SkMaskFilter(SkReadBuffer& buffer) : INHERITED(buffer) {}
enum FilterReturn {
kFalse_FilterReturn,
@@ -164,10 +182,17 @@ protected:
kUnimplemented_FilterReturn
};
- struct NinePatch {
+ class NinePatch : ::SkNoncopyable {
+ public:
+ NinePatch() : fCache(NULL) {
+ fMask.fImage = NULL;
+ }
+ ~NinePatch();
+
SkMask fMask; // fBounds must have [0,0] in its top-left
SkIRect fOuterRect; // width/height must be >= fMask.fBounds'
SkIPoint fCenter; // identifies center row/col for stretching
+ SkCachedData* fCache;
};
/**
diff --git a/gfx/skia/skia/include/core/SkMath.h b/gfx/skia/skia/include/core/SkMath.h
index 014f014deb..e5069592d0 100644
--- a/gfx/skia/skia/include/core/SkMath.h
+++ b/gfx/skia/skia/include/core/SkMath.h
@@ -79,6 +79,9 @@ int SkCLZ_portable(uint32_t);
if (mask) {
DWORD index;
_BitScanReverse(&index, mask);
+ // Suppress this bogus /analyze warning. The check for non-zero
+ // guarantees that _BitScanReverse will succeed.
+#pragma warning(suppress : 6102) // Using 'index' from failed function call
return index ^ 0x1F;
} else {
return 32;
@@ -147,40 +150,12 @@ static inline int SkNextLog2(uint32_t value) {
* Returns true if value is a power of 2. Does not explicitly check for
* value <= 0.
*/
-static inline bool SkIsPow2(int value) {
+template inline bool SkIsPow2(T value) {
return (value & (value - 1)) == 0;
}
///////////////////////////////////////////////////////////////////////////////
-/**
- * SkMulS16(a, b) multiplies a * b, but requires that a and b are both int16_t.
- * With this requirement, we can generate faster instructions on some
- * architectures.
- */
-#ifdef SK_ARM_HAS_EDSP
- static inline int32_t SkMulS16(S16CPU x, S16CPU y) {
- SkASSERT((int16_t)x == x);
- SkASSERT((int16_t)y == y);
- int32_t product;
- asm("smulbb %0, %1, %2 \n"
- : "=r"(product)
- : "r"(x), "r"(y)
- );
- return product;
- }
-#else
- #ifdef SK_DEBUG
- static inline int32_t SkMulS16(S16CPU x, S16CPU y) {
- SkASSERT((int16_t)x == x);
- SkASSERT((int16_t)y == y);
- return x * y;
- }
- #else
- #define SkMulS16(x, y) ((x) * (y))
- #endif
-#endif
-
/**
* Return a*b/((1 << shift) - 1), rounding any fractional bits.
* Only valid if a and b are unsigned and <= 32767 and shift is > 0 and <= 8
@@ -189,7 +164,7 @@ static inline unsigned SkMul16ShiftRound(U16CPU a, U16CPU b, int shift) {
SkASSERT(a <= 32767);
SkASSERT(b <= 32767);
SkASSERT(shift > 0 && shift <= 8);
- unsigned prod = SkMulS16(a, b) + (1 << (shift - 1));
+ unsigned prod = a*b + (1 << (shift - 1));
return (prod + (prod >> shift)) >> shift;
}
@@ -200,7 +175,7 @@ static inline unsigned SkMul16ShiftRound(U16CPU a, U16CPU b, int shift) {
static inline U8CPU SkMulDiv255Round(U16CPU a, U16CPU b) {
SkASSERT(a <= 32767);
SkASSERT(b <= 32767);
- unsigned prod = SkMulS16(a, b) + 128;
+ unsigned prod = a*b + 128;
return (prod + (prod >> 8)) >> 8;
}
diff --git a/gfx/skia/skia/include/core/SkMatrix.h b/gfx/skia/skia/include/core/SkMatrix.h
index bfa03de7c5..97a53505ef 100644
--- a/gfx/skia/skia/include/core/SkMatrix.h
+++ b/gfx/skia/skia/include/core/SkMatrix.h
@@ -10,16 +10,11 @@
#ifndef SkMatrix_DEFINED
#define SkMatrix_DEFINED
-#include "SkDynamicAnnotations.h"
#include "SkRect.h"
+struct SkRSXform;
class SkString;
-// TODO: can we remove these 3 (need to check chrome/android)
-typedef SkScalar SkPersp;
-#define SkScalarToPersp(x) (x)
-#define SkPerspToScalar(x) (x)
-
/** \class SkMatrix
The SkMatrix class holds a 3x3 matrix for transforming coordinates.
@@ -27,8 +22,27 @@ typedef SkScalar SkPersp;
using either reset() - to construct an identity matrix, or one of the set
functions (e.g. setTranslate, setRotate, etc.).
*/
+SK_BEGIN_REQUIRE_DENSE
class SK_API SkMatrix {
public:
+ static SkMatrix SK_WARN_UNUSED_RESULT MakeScale(SkScalar sx, SkScalar sy) {
+ SkMatrix m;
+ m.setScale(sx, sy);
+ return m;
+ }
+
+ static SkMatrix SK_WARN_UNUSED_RESULT MakeScale(SkScalar scale) {
+ SkMatrix m;
+ m.setScale(scale, scale);
+ return m;
+ }
+
+ static SkMatrix SK_WARN_UNUSED_RESULT MakeTrans(SkScalar dx, SkScalar dy) {
+ SkMatrix m;
+ m.setTranslate(dx, dy);
+ return m;
+ }
+
/** Enum of bit fields for the mask return by getType().
Use this to identify the complexity of the matrix.
*/
@@ -60,6 +74,10 @@ public:
return this->getType() == 0;
}
+ bool isScaleTranslate() const {
+ return !(this->getType() & ~(kScale_Mask | kTranslate_Mask));
+ }
+
/** Returns true if will map a rectangle to another rectangle. This can be
true if the matrix is identity, scale-only, or rotates a multiple of
90 degrees.
@@ -81,12 +99,12 @@ public:
kPerspective_Mask);
}
- /** Returns true if the matrix contains only translation, rotation or uniform scale
+ /** Returns true if the matrix contains only translation, rotation/reflection or uniform scale
Returns false if other transformation types are included or is degenerate
*/
bool isSimilarity(SkScalar tol = SK_ScalarNearlyZero) const;
- /** Returns true if the matrix contains only translation, rotation or scale
+ /** Returns true if the matrix contains only translation, rotation/reflection or scale
(non-uniform scale is allowed).
Returns false if other transformation types are included or is degenerate
*/
@@ -132,8 +150,8 @@ public:
SkScalar getSkewX() const { return fMat[kMSkewX]; }
SkScalar getTranslateX() const { return fMat[kMTransX]; }
SkScalar getTranslateY() const { return fMat[kMTransY]; }
- SkPersp getPerspX() const { return fMat[kMPersp0]; }
- SkPersp getPerspY() const { return fMat[kMPersp1]; }
+ SkScalar getPerspX() const { return fMat[kMPersp0]; }
+ SkScalar getPerspY() const { return fMat[kMPersp1]; }
SkScalar& operator[](int index) {
SkASSERT((unsigned)index < 9);
@@ -153,12 +171,12 @@ public:
void setSkewX(SkScalar v) { this->set(kMSkewX, v); }
void setTranslateX(SkScalar v) { this->set(kMTransX, v); }
void setTranslateY(SkScalar v) { this->set(kMTransY, v); }
- void setPerspX(SkPersp v) { this->set(kMPersp0, v); }
- void setPerspY(SkPersp v) { this->set(kMPersp1, v); }
+ void setPerspX(SkScalar v) { this->set(kMPersp0, v); }
+ void setPerspY(SkScalar v) { this->set(kMPersp1, v); }
- void setAll(SkScalar scaleX, SkScalar skewX, SkScalar transX,
- SkScalar skewY, SkScalar scaleY, SkScalar transY,
- SkPersp persp0, SkPersp persp1, SkPersp persp2) {
+ void setAll(SkScalar scaleX, SkScalar skewX, SkScalar transX,
+ SkScalar skewY, SkScalar scaleY, SkScalar transY,
+ SkScalar persp0, SkScalar persp1, SkScalar persp2) {
fMat[kMScaleX] = scaleX;
fMat[kMSkewX] = skewX;
fMat[kMTransX] = transX;
@@ -171,6 +189,23 @@ public:
this->setTypeMask(kUnknown_Mask);
}
+ /**
+ * Copy the 9 scalars for this matrix into buffer, in the same order as the kMScaleX
+ * enum... scalex, skewx, transx, skewy, scaley, transy, persp0, persp1, persp2
+ */
+ void get9(SkScalar buffer[9]) const {
+ memcpy(buffer, fMat, 9 * sizeof(SkScalar));
+ }
+
+ /**
+ * Set this matrix to the 9 scalars from the buffer, in the same order as the kMScaleX
+ * enum... scalex, skewx, transx, skewy, scaley, transy, persp0, persp1, persp2
+ *
+ * Note: calling set9 followed by get9 may not return the exact same values. Since the matrix
+ * is used to map non-homogeneous coordinates, it is free to rescale the 9 values as needed.
+ */
+ void set9(const SkScalar buffer[9]);
+
/** Set the matrix to identity
*/
void reset();
@@ -211,6 +246,9 @@ public:
/** Set the matrix to rotate by the specified sine and cosine values.
*/
void setSinCos(SkScalar sinValue, SkScalar cosValue);
+
+ SkMatrix& setRSXform(const SkRSXform&);
+
/** Set the matrix to skew by sx and sy, with a pivot point at (px, py).
The pivot point is the coordinate that should remain unchanged by the
specified transformation.
@@ -332,6 +370,11 @@ public:
@return true if the matrix can be represented by the rectangle mapping.
*/
bool setRectToRect(const SkRect& src, const SkRect& dst, ScaleToFit stf);
+ static SkMatrix MakeRectToRect(const SkRect& src, const SkRect& dst, ScaleToFit stf) {
+ SkMatrix m;
+ m.setRectToRect(src, dst, stf);
+ return m;
+ }
/** Set the matrix such that the specified src points would map to the
specified dst points. count must be within [0..4].
@@ -349,7 +392,7 @@ public:
bool SK_WARN_UNUSED_RESULT invert(SkMatrix* inverse) const {
// Allow the trivial case to be inlined.
if (this->isIdentity()) {
- if (NULL != inverse) {
+ if (inverse) {
inverse->reset();
}
return true;
@@ -369,7 +412,12 @@ public:
and does not change the passed array.
@param affine The array to fill with affine values. Ignored if NULL.
*/
- bool asAffine(SkScalar affine[6]) const;
+ bool SK_WARN_UNUSED_RESULT asAffine(SkScalar affine[6]) const;
+
+ /** Set the matrix to the specified affine values.
+ * Note: these are passed in column major order.
+ */
+ void setAffine(const SkScalar affine[6]);
/** Apply this matrix to the array of points specified by src, and write
the transformed points into the array of points specified by dst.
@@ -381,7 +429,12 @@ public:
@param count The number of points in src to read, and then transform
into dst.
*/
- void mapPoints(SkPoint dst[], const SkPoint src[], int count) const;
+ 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);
+ }
/** Apply this matrix to the array of points, overwriting it with the
transformed values.
@@ -437,6 +490,12 @@ public:
this->getMapXYProc()(*this, x, y, result);
}
+ SkPoint mapXY(SkScalar x, SkScalar y) const {
+ SkPoint result;
+ this->getMapXYProc()(*this, x, y, &result);
+ return result;
+ }
+
/** Apply this matrix to the array of vectors specified by src, and write
the transformed vectors into the array of vectors specified by dst.
This is similar to mapPoints, but ignores any translation in the matrix.
@@ -460,6 +519,17 @@ public:
this->mapVectors(vecs, vecs, count);
}
+ void mapVector(SkScalar dx, SkScalar dy, SkVector* result) const {
+ SkVector vec = { dx, dy };
+ this->mapVectors(result, &vec, 1);
+ }
+
+ SkVector mapVector(SkScalar dx, SkScalar dy) const {
+ SkVector vec = { dx, dy };
+ this->mapVectors(&vec, &vec, 1);
+ return vec;
+ }
+
/** Apply this matrix to the src rectangle, and write the transformed
rectangle into dst. This is accomplished by transforming the 4 corners
of src, and then setting dst to the bounds of those points.
@@ -539,8 +609,8 @@ public:
return 0 == memcmp(fMat, m.fMat, sizeof(fMat));
}
- friend bool operator==(const SkMatrix& a, const SkMatrix& b);
- friend bool operator!=(const SkMatrix& a, const SkMatrix& b) {
+ friend SK_API bool operator==(const SkMatrix& a, const SkMatrix& b);
+ friend SK_API bool operator!=(const SkMatrix& a, const SkMatrix& b) {
return !(a == b);
}
@@ -560,8 +630,8 @@ public:
*/
size_t readFromMemory(const void* buffer, size_t length);
- SkDEVCODE(void dump() const;)
- SK_TO_STRING_NONVIRT()
+ void dump() const;
+ void toString(SkString*) const;
/**
* Calculates the minimum scaling factor of the matrix as computed from the SVD of the upper
@@ -586,6 +656,19 @@ public:
*/
bool getMinMaxScales(SkScalar scaleFactors[2]) const;
+ /**
+ * Attempt to decompose this matrix into a scale-only component and whatever remains, where
+ * the scale component is to be applied first.
+ *
+ * M -> Remaining * Scale
+ *
+ * On success, return true and assign the scale and remaining components (assuming their
+ * respective parameters are not null). On failure return false and ignore the parameters.
+ *
+ * Possible reasons to fail: perspective, one or more scale factors are zero.
+ */
+ bool decomposeScale(SkSize* scale, SkMatrix* remaining = NULL) const;
+
/**
* Return a reference to a const identity matrix
*/
@@ -644,7 +727,36 @@ private:
};
SkScalar fMat[9];
- mutable SkTRacy fTypeMask;
+ mutable uint32_t fTypeMask;
+
+ /** Are all elements of the matrix finite?
+ */
+ bool isFinite() const { return SkScalarsAreFinite(fMat, 9); }
+
+ static void ComputeInv(SkScalar dst[9], const SkScalar src[9], double invDet, bool isPersp);
+
+ void setScaleTranslate(SkScalar sx, SkScalar sy, SkScalar tx, SkScalar ty) {
+ fMat[kMScaleX] = sx;
+ fMat[kMSkewX] = 0;
+ fMat[kMTransX] = tx;
+
+ fMat[kMSkewY] = 0;
+ fMat[kMScaleY] = sy;
+ fMat[kMTransY] = ty;
+
+ fMat[kMPersp0] = 0;
+ fMat[kMPersp1] = 0;
+ fMat[kMPersp2] = 1;
+
+ unsigned mask = 0;
+ if (sx != 1 || sy != 1) {
+ mask |= kScale_Mask;
+ }
+ if (tx || ty) {
+ mask |= kTranslate_Mask;
+ }
+ this->setTypeMask(mask | kRectStaysRect_Mask);
+ }
uint8_t computeTypeMask() const;
uint8_t computePerspectiveTypeMask() const;
@@ -707,14 +819,14 @@ private:
static void Scale_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int);
static void ScaleTrans_pts(const SkMatrix&, SkPoint dst[], const SkPoint[],
int count);
- static void Rot_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int);
- static void RotTrans_pts(const SkMatrix&, SkPoint dst[], const SkPoint[],
- int count);
static void Persp_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int);
+ static void Affine_vpts(const SkMatrix&, SkPoint dst[], const SkPoint[], int);
+
static const MapPtsProc gMapPtsProcs[];
friend class SkPerspIter;
};
+SK_END_REQUIRE_DENSE
#endif
diff --git a/gfx/skia/skia/include/core/SkMetaData.h b/gfx/skia/skia/include/core/SkMetaData.h
index 5db437c980..c8ca7f1419 100644
--- a/gfx/skia/skia/include/core/SkMetaData.h
+++ b/gfx/skia/skia/include/core/SkMetaData.h
@@ -81,7 +81,7 @@ public:
bool hasData(const char name[], const void* data, size_t byteCount) const {
size_t len;
const void* ptr = this->findData(name, &len);
- return NULL != ptr && len == byteCount && !memcmp(ptr, data, len);
+ return ptr && len == byteCount && !memcmp(ptr, data, len);
}
void setS32(const char name[], int32_t value);
diff --git a/gfx/skia/skia/include/core/SkMultiPictureDraw.h b/gfx/skia/skia/include/core/SkMultiPictureDraw.h
new file mode 100644
index 0000000000..8d24e615e8
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkMultiPictureDraw.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkMultiPictureDraw_DEFINED
+#define SkMultiPictureDraw_DEFINED
+
+#include "SkMatrix.h"
+#include "SkTDArray.h"
+
+class SkCanvas;
+class SkPaint;
+class SkPicture;
+
+/** \class SkMultiPictureDraw
+
+ The MultiPictureDraw object accepts several picture/canvas pairs and
+ then attempts to optimally draw the pictures into the canvases, sharing
+ as many resources as possible.
+*/
+class SK_API SkMultiPictureDraw {
+public:
+ /**
+ * Create an object to optimize the drawing of multiple pictures.
+ * @param reserve Hint for the number of add calls expected to be issued
+ */
+ SkMultiPictureDraw(int reserve = 0);
+ ~SkMultiPictureDraw() { this->reset(); }
+
+ /**
+ * Add a canvas/picture pair for later rendering.
+ * @param canvas the canvas in which to draw picture
+ * @param picture the picture to draw into canvas
+ * @param matrix if non-NULL, applied to the CTM when drawing
+ * @param paint if non-NULL, draw picture to a temporary buffer
+ * and then apply the paint when the result is drawn
+ */
+ void add(SkCanvas* canvas,
+ const SkPicture* picture,
+ const SkMatrix* matrix = NULL,
+ const SkPaint* paint = NULL);
+
+ /**
+ * Perform all the previously added draws. This will reset the state
+ * of this object. If flush is true, all canvases are flushed after
+ * draw.
+ */
+ void draw(bool flush = false);
+
+ /**
+ * Abandon all buffered draws and reset to the initial state.
+ */
+ void reset();
+
+private:
+ struct DrawData {
+ SkCanvas* fCanvas; // reffed
+ const SkPicture* fPicture; // reffed
+ SkMatrix fMatrix;
+ SkPaint* fPaint; // owned
+
+ void init(SkCanvas*, const SkPicture*, const SkMatrix*, const SkPaint*);
+ void draw();
+
+ static void Reset(SkTDArray&);
+ };
+
+ SkTDArray fThreadSafeDrawData;
+ SkTDArray fGPUDrawData;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkOSFile.h b/gfx/skia/skia/include/core/SkOSFile.h
index 1ca11ee932..39a1646458 100644
--- a/gfx/skia/skia/include/core/SkOSFile.h
+++ b/gfx/skia/skia/include/core/SkOSFile.h
@@ -12,16 +12,10 @@
#ifndef SkOSFile_DEFINED
#define SkOSFile_DEFINED
+#include
+
#include "SkString.h"
-#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_IOS)
- #include
-#endif
-
-#include // ptrdiff_t
-
-struct SkFILE;
-
enum SkFILE_Flags {
kRead_SkFILE_Flag = 0x01,
kWrite_SkFILE_Flag = 0x02
@@ -33,30 +27,30 @@ const static char SkPATH_SEPARATOR = '\\';
const static char SkPATH_SEPARATOR = '/';
#endif
-SkFILE* sk_fopen(const char path[], SkFILE_Flags);
-void sk_fclose(SkFILE*);
+FILE* sk_fopen(const char path[], SkFILE_Flags);
+void sk_fclose(FILE*);
-size_t sk_fgetsize(SkFILE*);
+size_t sk_fgetsize(FILE*);
/** Return true if the file could seek back to the beginning
*/
-bool sk_frewind(SkFILE*);
+bool sk_frewind(FILE*);
-size_t sk_fread(void* buffer, size_t byteCount, SkFILE*);
-size_t sk_fwrite(const void* buffer, size_t byteCount, SkFILE*);
+size_t sk_fread(void* buffer, size_t byteCount, FILE*);
+size_t sk_fwrite(const void* buffer, size_t byteCount, FILE*);
-char* sk_fgets(char* str, int size, SkFILE* f);
+char* sk_fgets(char* str, int size, FILE* f);
-void sk_fflush(SkFILE*);
+void sk_fflush(FILE*);
-bool sk_fseek(SkFILE*, size_t);
-bool sk_fmove(SkFILE*, long);
-size_t sk_ftell(SkFILE*);
+bool sk_fseek(FILE*, size_t);
+bool sk_fmove(FILE*, long);
+size_t sk_ftell(FILE*);
/** Maps a file into memory. Returns the address and length on success, NULL otherwise.
* The mapping is read only.
* When finished with the mapping, free the returned pointer with sk_fmunmap.
*/
-void* sk_fmmap(SkFILE* f, size_t* length);
+void* sk_fmmap(FILE* f, size_t* length);
/** Maps a file descriptor into memory. Returns the address and length on success, NULL otherwise.
* The mapping is read only.
@@ -70,12 +64,12 @@ void* sk_fdmmap(int fd, size_t* length);
void sk_fmunmap(const void* addr, size_t length);
/** Returns true if the two point at the exact same filesystem object. */
-bool sk_fidentical(SkFILE* a, SkFILE* b);
+bool sk_fidentical(FILE* a, FILE* b);
/** Returns the underlying file descriptor for the given file.
* The return value will be < 0 on failure.
*/
-int sk_fileno(SkFILE* f);
+int sk_fileno(FILE* f);
/** Returns true if something (file, directory, ???) exists at this path,
* and has the specified access flags.
@@ -86,7 +80,7 @@ bool sk_exists(const char *path, SkFILE_Flags = (SkFILE_Flags)0);
bool sk_isdir(const char *path);
// Have we reached the end of the file?
-int sk_feof(SkFILE *);
+int sk_feof(FILE *);
// Create a new directory at this path; returns true if successful.
@@ -109,21 +103,16 @@ public:
*/
bool next(SkString* name, bool getDir = false);
+ static const size_t kStorageSize = 40;
private:
-#ifdef SK_BUILD_FOR_WIN
- HANDLE fHandle;
- uint16_t* fPath16;
-#elif defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX) || defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_IOS)
- DIR* fDIR;
- SkString fPath, fSuffix;
-#endif
+ SkAlignedSStorage fSelf;
};
};
/**
* Functions for modifying SkStrings which represent paths on the filesystem.
*/
-class SkOSPath {
+class SkOSPath {
public:
/**
* Assembles rootPath and relativePath into a single path, like this:
@@ -133,7 +122,7 @@ public:
*
* Uses SkPATH_SEPARATOR, to work on all platforms.
*/
- static SkString SkPathJoin(const char *rootPath, const char *relativePath);
+ static SkString Join(const char* rootPath, const char* relativePath);
/**
* Return the name of the file, ignoring the directory structure.
@@ -143,6 +132,17 @@ public:
* @return SkString The basename of the file - anything beyond the
* final slash, or the full name if there is no slash.
*/
- static SkString SkBasename(const char* fullPath);
+ static SkString Basename(const char* fullPath);
+
+ /**
+ * Given a qualified file name returns the directory.
+ * Behaves like python's os.path.dirname. If the fullPath is
+ * /dir/subdir/ the return will be /dir/subdir/
+ * @param fullPath Full path to the file.
+ * @return SkString The dir containing the file - anything preceding the
+ * final slash, or the full name if ending in a slash.
+ */
+ static SkString Dirname(const char* fullPath);
};
+
#endif
diff --git a/gfx/skia/skia/include/core/SkOnce.h b/gfx/skia/skia/include/core/SkOnce.h
deleted file mode 100644
index 87bb277800..0000000000
--- a/gfx/skia/skia/include/core/SkOnce.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright 2013 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkOnce_DEFINED
-#define SkOnce_DEFINED
-
-// Before trying SkOnce, see if SkLazyPtr or SkLazyFnPtr will work for you.
-// They're smaller and faster, if slightly less versatile.
-
-
-// SkOnce.h defines SK_DECLARE_STATIC_ONCE and SkOnce(), which you can use
-// together to create a threadsafe way to call a function just once. E.g.
-//
-// static void register_my_stuff(GlobalRegistry* registry) {
-// registry->register(...);
-// }
-// ...
-// void EnsureRegistered() {
-// SK_DECLARE_STATIC_ONCE(once);
-// SkOnce(&once, register_my_stuff, GetGlobalRegistry());
-// }
-//
-// No matter how many times you call EnsureRegistered(), register_my_stuff will be called just once.
-// OnceTest.cpp also should serve as a few other simple examples.
-
-#include "SkDynamicAnnotations.h"
-#include "SkThread.h"
-#include "SkTypes.h"
-
-// This must be used in a global or function scope, not as a class member.
-#define SK_DECLARE_STATIC_ONCE(name) static SkOnceFlag name
-
-class SkOnceFlag;
-
-inline void SkOnce(SkOnceFlag* once, void (*f)());
-
-template
-inline void SkOnce(SkOnceFlag* once, void (*f)(Arg), Arg arg);
-
-// If you've already got a lock and a flag to use, this variant lets you avoid an extra SkOnceFlag.
-template
-inline void SkOnce(bool* done, Lock* lock, void (*f)());
-
-template
-inline void SkOnce(bool* done, Lock* lock, void (*f)(Arg), Arg arg);
-
-// ---------------------- Implementation details below here. -----------------------------
-
-// This class has no constructor and must be zero-initialized (the macro above does this).
-class SkOnceFlag {
-public:
- bool* mutableDone() { return &fDone; }
-
- void acquire() {
- // To act as a mutex, this needs an acquire barrier on success.
- // sk_atomic_cas doesn't guarantee this ...
- while (!sk_atomic_cas(&fSpinlock, 0, 1)) {
- // spin
- }
- // ... so make sure to issue one of our own.
- SkAssertResult(sk_acquire_load(&fSpinlock));
- }
-
- void release() {
- // To act as a mutex, this needs a release barrier. sk_atomic_cas guarantees this.
- SkAssertResult(sk_atomic_cas(&fSpinlock, 1, 0));
- }
-
-private:
- bool fDone;
- int32_t fSpinlock;
-};
-
-// We've pulled a pretty standard double-checked locking implementation apart
-// into its main fast path and a slow path that's called when we suspect the
-// one-time code hasn't run yet.
-
-// This is the guts of the code, called when we suspect the one-time code hasn't been run yet.
-// This should be rarely called, so we separate it from SkOnce and don't mark it as inline.
-// (We don't mind if this is an actual function call, but odds are it'll be inlined anyway.)
-template
-static void sk_once_slow(bool* done, Lock* lock, void (*f)(Arg), Arg arg) {
- lock->acquire();
- if (!*done) {
- f(arg);
- // Also known as a store-store/load-store barrier, this makes sure that the writes
- // done before here---in particular, those done by calling f(arg)---are observable
- // before the writes after the line, *done = true.
- //
- // In version control terms this is like saying, "check in the work up
- // to and including f(arg), then check in *done=true as a subsequent change".
- //
- // We'll use this in the fast path to make sure f(arg)'s effects are
- // observable whenever we observe *done == true.
- sk_release_store(done, true);
- }
- lock->release();
-}
-
-// This is our fast path, called all the time. We do really want it to be inlined.
-template
-inline void SkOnce(bool* done, Lock* lock, void (*f)(Arg), Arg arg) {
- if (!SK_ANNOTATE_UNPROTECTED_READ(*done)) {
- sk_once_slow(done, lock, f, arg);
- }
- // Also known as a load-load/load-store barrier, this acquire barrier makes
- // sure that anything we read from memory---in particular, memory written by
- // calling f(arg)---is at least as current as the value we read from done.
- //
- // In version control terms, this is a lot like saying "sync up to the
- // commit where we wrote done = true".
- //
- // The release barrier in sk_once_slow guaranteed that done = true
- // happens after f(arg), so by syncing to done = true here we're
- // forcing ourselves to also wait until the effects of f(arg) are readble.
- SkAssertResult(sk_acquire_load(done));
-}
-
-template
-inline void SkOnce(SkOnceFlag* once, void (*f)(Arg), Arg arg) {
- return SkOnce(once->mutableDone(), once, f, arg);
-}
-
-// Calls its argument.
-// This lets us use functions that take no arguments with SkOnce methods above.
-// (We pass _this_ as the function and the no-arg function as its argument. Cute eh?)
-static void sk_once_no_arg_adaptor(void (*f)()) {
- f();
-}
-
-inline void SkOnce(SkOnceFlag* once, void (*func)()) {
- return SkOnce(once, sk_once_no_arg_adaptor, func);
-}
-
-template
-inline void SkOnce(bool* done, Lock* lock, void (*func)()) {
- return SkOnce(done, lock, sk_once_no_arg_adaptor, func);
-}
-
-#endif // SkOnce_DEFINED
diff --git a/gfx/skia/skia/include/core/SkPackBits.h b/gfx/skia/skia/include/core/SkPackBits.h
index f0614a0843..1e32ee0875 100644
--- a/gfx/skia/skia/include/core/SkPackBits.h
+++ b/gfx/skia/skia/include/core/SkPackBits.h
@@ -14,66 +14,33 @@
class SkPackBits {
public:
- /** Given the number of 16bit values that will be passed to Pack16,
- returns the worst-case size needed for the dst[] buffer.
- */
- static size_t ComputeMaxSize16(int count);
-
/** Given the number of 8bit values that will be passed to Pack8,
returns the worst-case size needed for the dst[] buffer.
*/
static size_t ComputeMaxSize8(int count);
- /** Write the src array into a packed format. The packing process may end
- up writing more bytes than it read, so dst[] must be large enough.
- @param src Input array of 16bit values
- @param count Number of entries in src[]
- @param dst Buffer (allocated by caller) to write the packed data
- into
- @return the number of bytes written to dst[]
- */
- static size_t Pack16(const uint16_t src[], int count, uint8_t dst[]);
-
/** Write the src array into a packed format. The packing process may end
up writing more bytes than it read, so dst[] must be large enough.
@param src Input array of 8bit values
- @param count Number of entries in src[]
+ @param srcSize Number of entries in src[]
@param dst Buffer (allocated by caller) to write the packed data
into
+ @param dstSize Number of bytes in the output buffer.
@return the number of bytes written to dst[]
*/
- static size_t Pack8(const uint8_t src[], int count, uint8_t dst[]);
-
- /** Unpack the data in src[], and expand it into dst[]. The src[] data was
- written by a previous call to Pack16.
- @param src Input data to unpack, previously created by Pack16.
- @param srcSize Number of bytes of src to unpack
- @param dst Buffer (allocated by caller) to expand the src[] into.
- @return the number of dst elements (not bytes) written into dst.
- */
- static int Unpack16(const uint8_t src[], size_t srcSize, uint16_t dst[]);
+ static size_t Pack8(const uint8_t src[], size_t srcSize, uint8_t dst[],
+ size_t dstSize);
/** Unpack the data in src[], and expand it into dst[]. The src[] data was
written by a previous call to Pack8.
@param src Input data to unpack, previously created by Pack8.
@param srcSize Number of bytes of src to unpack
@param dst Buffer (allocated by caller) to expand the src[] into.
+ @param dstSize Number of bytes in the output buffer.
@return the number of bytes written into dst.
*/
- static int Unpack8(const uint8_t src[], size_t srcSize, uint8_t dst[]);
-
- /** Unpack the data from src[], skip the first dstSkip bytes, then write
- dstWrite bytes into dst[]. The src[] data was written by a previous
- call to Pack8. Return the number of bytes actually writtten into dst[]
- @param src Input data to unpack, previously created by Pack8.
- @param dst Buffer (allocated by caller) to expand the src[] into.
- @param dstSkip Number of bytes of unpacked src to skip before writing
- into dst
- @param dstWrite Number of bytes of unpacked src to write into dst (after
- skipping dstSkip bytes)
- */
- static void Unpack8(uint8_t dst[], size_t dstSkip, size_t dstWrite,
- const uint8_t src[]);
+ static int Unpack8(const uint8_t src[], size_t srcSize, uint8_t dst[],
+ size_t dstSize);
};
#endif
diff --git a/gfx/skia/skia/include/core/SkPaint.h b/gfx/skia/skia/include/core/SkPaint.h
index 3874d98869..2090ed2337 100644
--- a/gfx/skia/skia/include/core/SkPaint.h
+++ b/gfx/skia/skia/include/core/SkPaint.h
@@ -1,5 +1,3 @@
-
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -7,26 +5,24 @@
* found in the LICENSE file.
*/
-
#ifndef SkPaint_DEFINED
#define SkPaint_DEFINED
#include "SkColor.h"
-#include "SkDrawLooper.h"
+#include "SkFilterQuality.h"
#include "SkMatrix.h"
#include "SkXfermode.h"
-#ifdef SK_BUILD_FOR_ANDROID
-#include "SkPaintOptionsAndroid.h"
-#endif
class SkAnnotation;
+class SkAutoDescriptor;
class SkAutoGlyphCache;
class SkColorFilter;
+class SkData;
class SkDescriptor;
-struct SkDeviceProperties;
+class SkDrawLooper;
class SkReadBuffer;
class SkWriteBuffer;
-struct SkGlyph;
+class SkGlyph;
struct SkRect;
class SkGlyphCache;
class SkImageFilter;
@@ -36,6 +32,7 @@ class SkPathEffect;
struct SkPoint;
class SkRasterizer;
class SkShader;
+class SkSurfaceProps;
class SkTypeface;
typedef const SkGlyph& (*SkDrawCacheProc)(SkGlyphCache*, const char**,
@@ -59,11 +56,20 @@ public:
SkPaint& operator=(const SkPaint&);
+ /** operator== may give false negatives: two paints that draw equivalently
+ may return false. It will never give false positives: two paints that
+ are not equivalent always return false.
+ */
SK_API friend bool operator==(const SkPaint& a, const SkPaint& b);
friend bool operator!=(const SkPaint& a, const SkPaint& b) {
return !(a == b);
}
+ /** getHash() is a shallow hash, with the same limitations as operator==.
+ * If operator== returns true for two paints, getHash() returns the same value for each.
+ */
+ uint32_t getHash() const;
+
void flatten(SkWriteBuffer&) const;
void unflatten(SkReadBuffer&);
@@ -110,8 +116,6 @@ public:
kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter
kVerticalText_Flag = 0x1000,
kGenA8FromLCD_Flag = 0x2000, // hack for GDI -- do not use if you can help it
- kDistanceFieldTextTEMP_Flag = 0x4000, //!< TEMPORARY mask to enable distance fields
- // currently overrides LCD and subpixel rendering
// when adding extra flags, note that the fFlags member is specified
// with a bit-width and you'll have to expand it.
@@ -278,56 +282,19 @@ public:
*/
void setDevKernText(bool devKernText);
- /** Helper for getFlags(), returns true if kDistanceFieldTextTEMP_Flag bit is set
- @return true if the distanceFieldText bit is set in the paint's flags.
- */
- bool isDistanceFieldTextTEMP() const {
- return SkToBool(this->getFlags() & kDistanceFieldTextTEMP_Flag);
- }
-
- /** Helper for setFlags(), setting or clearing the kDistanceFieldTextTEMP_Flag bit
- @param distanceFieldText true to set the kDistanceFieldTextTEMP_Flag bit in the paint's
- flags, false to clear it.
- */
- void setDistanceFieldTextTEMP(bool distanceFieldText);
-
- enum FilterLevel {
- kNone_FilterLevel,
- kLow_FilterLevel,
- kMedium_FilterLevel,
- kHigh_FilterLevel
- };
-
/**
* Return the filter level. This affects the quality (and performance) of
* drawing scaled images.
*/
- FilterLevel getFilterLevel() const {
- return (FilterLevel)fBitfields.fFilterLevel;
+ SkFilterQuality getFilterQuality() const {
+ return (SkFilterQuality)fBitfields.fFilterQuality;
}
/**
- * Set the filter level. This affects the quality (and performance) of
+ * Set the filter quality. This affects the quality (and performance) of
* drawing scaled images.
*/
- void setFilterLevel(FilterLevel);
-
- /**
- * If the predicate is true, set the filterLevel to Low, else set it to
- * None.
- */
- SK_ATTR_DEPRECATED("use setFilterLevel")
- void setFilterBitmap(bool doFilter) {
- this->setFilterLevel(doFilter ? kLow_FilterLevel : kNone_FilterLevel);
- }
-
- /**
- * Returns true if getFilterLevel() returns anything other than None.
- */
- SK_ATTR_DEPRECATED("use getFilterLevel")
- bool isFilterBitmap() const {
- return kNone_FilterLevel != this->getFilterLevel();
- }
+ void setFilterQuality(SkFilterQuality quality);
/** Styles apply to rect, oval, path, and text.
Bitmaps are always drawn in "fill", and lines are always drawn in
@@ -431,6 +398,15 @@ public:
/** Cap enum specifies the settings for the paint's strokecap. This is the
treatment that is applied to the beginning and end of each non-closed
contour (e.g. lines).
+
+ If the cap is round or square, the caps are drawn when the contour has
+ a zero length. Zero length contours can be created by following moveTo
+ with a lineTo at the same point, or a moveTo followed by a close.
+
+ A dash with an on interval of zero also creates a zero length contour.
+
+ The zero length contour draws the square cap without rotation, since
+ the no direction can be inferred.
*/
enum Cap {
kButt_Cap, //!< begin/end contours with no extension
@@ -487,11 +463,17 @@ public:
* @param src input path
* @param dst output path (may be the same as src)
* @param cullRect If not null, the dst path may be culled to this rect.
+ * @param resScale If > 1, increase precision, else if (0 < res < 1) reduce precision
+ * in favor of speed/size.
* @return true if the path should be filled, or false if it should be
* drawn with a hairline (width == 0)
*/
- bool getFillPath(const SkPath& src, SkPath* dst,
- const SkRect* cullRect = NULL) const;
+ bool getFillPath(const SkPath& src, SkPath* dst, const SkRect* cullRect,
+ SkScalar resScale = 1) const;
+
+ bool getFillPath(const SkPath& src, SkPath* dst) const {
+ return this->getFillPath(src, dst, NULL, 1);
+ }
/** Get the paint's shader object.
@@ -841,8 +823,7 @@ public:
to zero. Note: this does not look at the text-encoding setting in the
paint, only at the typeface.
*/
- void glyphsToUnichars(const uint16_t glyphs[], int count,
- SkUnichar text[]) const;
+ void glyphsToUnichars(const uint16_t glyphs[], int count, SkUnichar text[]) const;
/** Return the number of drawable units in the specified text buffer.
This looks at the current TextEncoding field of the paint. If you also
@@ -861,12 +842,9 @@ public:
* @param length Number of bytes of text to measure
* @param bounds If not NULL, returns the bounds of the text,
* relative to (0, 0).
- * @param scale If not 0, return width as if the canvas were scaled
- * by this value
* @return The advance width of the text
*/
- SkScalar measureText(const void* text, size_t length,
- SkRect* bounds, SkScalar scale = 0) const;
+ SkScalar measureText(const void* text, size_t length, SkRect* bounds) const;
/** Return the width of the text. This will return the vertical measure
* if isVerticalText() is true, in which case the returned value should
@@ -877,22 +855,9 @@ public:
* @return The advance width of the text
*/
SkScalar measureText(const void* text, size_t length) const {
- return this->measureText(text, length, NULL, 0);
+ return this->measureText(text, length, NULL);
}
- /** Specify the direction the text buffer should be processed in breakText()
- */
- enum TextBufferDirection {
- /** When measuring text for breakText(), begin at the start of the text
- buffer and proceed forward through the data. This is the default.
- */
- kForward_TextBufferDirection,
- /** When measuring text for breakText(), begin at the end of the text
- buffer and proceed backwards through the data.
- */
- kBackward_TextBufferDirection
- };
-
/** Return the number of bytes of text that were measured. If
* isVerticalText() is true, then the vertical advances are used for
* the measurement.
@@ -903,15 +868,11 @@ public:
* widths are <= maxWidth are measured.
* @param measuredWidth Optional. If non-null, this returns the actual
* width of the measured text.
- * @param tbd Optional. The direction the text buffer should be
- * traversed during measuring.
* @return The number of bytes of text that were measured. Will be
* <= length.
*/
size_t breakText(const void* text, size_t length, SkScalar maxWidth,
- SkScalar* measuredWidth = NULL,
- TextBufferDirection tbd = kForward_TextBufferDirection)
- const;
+ SkScalar* measuredWidth = NULL) const;
/** Return the advances for the text. These will be vertical advances if
* isVerticalText() returns true.
@@ -938,19 +899,13 @@ public:
void getPosTextPath(const void* text, size_t length,
const SkPoint pos[], SkPath* path) const;
-#ifdef SK_BUILD_FOR_ANDROID
- uint32_t getGenerationID() const;
- void setGenerationID(uint32_t generationID);
-
- /** Returns the base glyph count for the strike associated with this paint
- */
- unsigned getBaseGlyphCount(SkUnichar text) const;
-
- const SkPaintOptionsAndroid& getPaintOptionsAndroid() const {
- return fPaintOptionsAndroid;
- }
- void setPaintOptionsAndroid(const SkPaintOptionsAndroid& options);
-#endif
+ /**
+ * Return a rectangle that represents the union of the bounds of all
+ * of the glyphs, but each one positioned at (0,0). This may be conservatively large, and
+ * will not take into account any hinting, but will respect any text-scale-x or text-skew-x
+ * on this paint.
+ */
+ SkRect getFontBounds() const;
// returns true if the paint's settings (e.g. xfermode + alpha) resolve to
// mean that we need not draw at all (e.g. SrcOver + 0-alpha)
@@ -963,12 +918,7 @@ public:
bounds (i.e. there is nothing complex like a patheffect that would make
the bounds computation expensive.
*/
- bool canComputeFastBounds() const {
- if (this->getLooper()) {
- return this->getLooper()->canComputeFastBounds(*this);
- }
- return !this->getRasterizer();
- }
+ bool canComputeFastBounds() const;
/** Only call this if canComputeFastBounds() returned true. This takes a
raw rectangle (the raw bounds of a shape), and adjusts it for stylistic
@@ -1035,11 +985,6 @@ public:
SK_TO_STRING_NONVIRT()
- struct FlatteningTraits {
- static void Flatten(SkWriteBuffer& buffer, const SkPaint& paint);
- static void Unflatten(SkReadBuffer& buffer, SkPaint* paint);
- };
-
private:
SkTypeface* fTypeface;
SkPathEffect* fPathEffect;
@@ -1068,28 +1013,38 @@ private:
unsigned fStyle : 2;
unsigned fTextEncoding : 2; // 3 values
unsigned fHinting : 2;
- unsigned fFilterLevel : 2;
+ unsigned fFilterQuality : 2;
//unsigned fFreeBits : 2;
} fBitfields;
uint32_t fBitfieldsUInt;
};
- uint32_t fDirtyBits;
SkDrawCacheProc getDrawCacheProc() const;
- SkMeasureCacheProc getMeasureCacheProc(TextBufferDirection dir,
- bool needFullMetrics) const;
+ SkMeasureCacheProc getMeasureCacheProc(bool needFullMetrics) const;
SkScalar measure_text(SkGlyphCache*, const char* text, size_t length,
int* count, SkRect* bounds) const;
- SkGlyphCache* detachCache(const SkDeviceProperties* deviceProperties, const SkMatrix*,
+ /*
+ * Allocs an SkDescriptor on the heap and return it to the caller as a refcnted
+ * SkData. Caller is responsible for managing the lifetime of this object.
+ */
+ void getScalerContextDescriptor(SkAutoDescriptor*, const SkSurfaceProps& surfaceProps,
+ const SkMatrix*, bool ignoreGamma) const;
+
+ SkGlyphCache* detachCache(const SkSurfaceProps* surfaceProps, const SkMatrix*,
bool ignoreGamma) const;
- void descriptorProc(const SkDeviceProperties* deviceProperties, const SkMatrix* deviceMatrix,
+ void descriptorProc(const SkSurfaceProps* surfaceProps, const SkMatrix* deviceMatrix,
void (*proc)(SkTypeface*, const SkDescriptor*, void*),
- void* context, bool ignoreGamma = false) const;
+ void* context, bool ignoreGamma) const;
- static void Term();
+ /*
+ * The luminance color is used to determine which Gamma Canonical color to map to. This is
+ * really only used by backends which want to cache glyph masks, and need some way to know if
+ * they need to generate new masks based off a given color.
+ */
+ SkColor computeLuminanceColor() const;
enum {
/* This is the size we use when we ask for a glyph's path. We then
@@ -1133,21 +1088,17 @@ private:
friend class SkAutoGlyphCacheNoGamma;
friend class SkCanvas;
friend class SkDraw;
- friend class SkGraphics; // So Term() can be called.
friend class SkPDFDevice;
friend class GrBitmapTextContext;
+ friend class GrAtlasTextContext;
friend class GrDistanceFieldTextContext;
friend class GrStencilAndCoverTextContext;
+ friend class GrPathRendering;
+ friend class GrTextContext;
+ friend class GrGLPathRendering;
+ friend class SkScalerContext;
friend class SkTextToPathIter;
friend class SkCanonicalizePaint;
-
-#ifdef SK_BUILD_FOR_ANDROID
- SkPaintOptionsAndroid fPaintOptionsAndroid;
-
- // In order for the == operator to work properly this must be the last field
- // in the struct so that we can do a memcmp to this field's offset.
- uint32_t fGenerationID;
-#endif
};
#endif
diff --git a/gfx/skia/skia/include/core/SkPaintOptionsAndroid.h b/gfx/skia/skia/include/core/SkPaintOptionsAndroid.h
deleted file mode 100644
index ab84ec050e..0000000000
--- a/gfx/skia/skia/include/core/SkPaintOptionsAndroid.h
+++ /dev/null
@@ -1,130 +0,0 @@
-
-/*
- * Copyright 2012 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkPaintOptionsAndroid_DEFINED
-#define SkPaintOptionsAndroid_DEFINED
-
-#include "SkTypes.h"
-#include "SkString.h"
-
-class SkReadBuffer;
-class SkWriteBuffer;
-
-/** \class SkLanguage
-
- The SkLanguage class represents a human written language, and is used by
- text draw operations to determine which glyph to draw when drawing
- characters with variants (ie Han-derived characters).
-*/
-class SkLanguage {
-public:
- SkLanguage() { }
- SkLanguage(const SkString& tag) : fTag(tag) { }
- SkLanguage(const char* tag) : fTag(tag) { }
- SkLanguage(const char* tag, size_t len) : fTag(tag, len) { }
- SkLanguage(const SkLanguage& b) : fTag(b.fTag) { }
-
- /** Gets a BCP 47 language identifier for this SkLanguage.
- @return a BCP 47 language identifier representing this language
- */
- const SkString& getTag() const { return fTag; }
-
- /** Performs BCP 47 fallback to return an SkLanguage one step more general.
- @return an SkLanguage one step more general
- */
- SkLanguage getParent() const;
-
- bool operator==(const SkLanguage& b) const {
- return fTag == b.fTag;
- }
- bool operator!=(const SkLanguage& b) const {
- return fTag != b.fTag;
- }
- SkLanguage& operator=(const SkLanguage& b) {
- fTag = b.fTag;
- return *this;
- }
-
-private:
- //! BCP 47 language identifier
- SkString fTag;
-};
-
-class SkPaintOptionsAndroid {
-public:
- SkPaintOptionsAndroid() {
- fFontVariant = kDefault_Variant;
- fUseFontFallbacks = false;
- }
-
- SkPaintOptionsAndroid& operator=(const SkPaintOptionsAndroid& b) {
- fLanguage = b.fLanguage;
- fFontVariant = b.fFontVariant;
- fUseFontFallbacks = b.fUseFontFallbacks;
- return *this;
- }
-
- bool operator==(const SkPaintOptionsAndroid& b) const {
- return !(*this != b);
- }
-
- bool operator!=(const SkPaintOptionsAndroid& b) const {
- return fLanguage != b.fLanguage ||
- fFontVariant != b.fFontVariant ||
- fUseFontFallbacks != b.fUseFontFallbacks;
- }
-
- void flatten(SkWriteBuffer&) const;
- void unflatten(SkReadBuffer&);
-
- /** Return the paint's language value used for drawing text.
- @return the paint's language value used for drawing text.
- */
- const SkLanguage& getLanguage() const { return fLanguage; }
-
- /** Set the paint's language value used for drawing text.
- @param language set the paint's language value for drawing text.
- */
- void setLanguage(const SkLanguage& language) { fLanguage = language; }
- void setLanguage(const char* languageTag) { fLanguage = SkLanguage(languageTag); }
-
-
- enum FontVariant {
- kDefault_Variant = 0x01,
- kCompact_Variant = 0x02,
- kElegant_Variant = 0x04,
- kLast_Variant = kElegant_Variant,
- };
-
- /** Return the font variant
- @return the font variant used by this paint object
- */
- FontVariant getFontVariant() const { return fFontVariant; }
-
- /** Set the font variant
- @param fontVariant set the paint's font variant for choosing fonts
- */
- void setFontVariant(FontVariant fontVariant) {
- SkASSERT((unsigned)fontVariant <= kLast_Variant);
- fFontVariant = fontVariant;
- }
-
- bool isUsingFontFallbacks() const { return fUseFontFallbacks; }
-
- void setUseFontFallbacks(bool useFontFallbacks) {
- fUseFontFallbacks = useFontFallbacks;
- }
-
-private:
- SkLanguage fLanguage;
- FontVariant fFontVariant;
- bool fUseFontFallbacks;
-};
-
-#endif // #ifndef SkPaintOptionsAndroid_DEFINED
diff --git a/gfx/skia/skia/include/core/SkPatch.h b/gfx/skia/skia/include/core/SkPatch.h
deleted file mode 100644
index 2354423aba..0000000000
--- a/gfx/skia/skia/include/core/SkPatch.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright 2014 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkPatch_DEFINED
-#define SkPatch_DEFINED
-
-#include "SkColor.h"
-#include "SkPreConfig.h"
-#include "SkPoint.h"
-
-/**
- * Class that represents a coons patch.
- */
-class SK_API SkPatch {
-
-public:
- /**
- * Structure that holds the vertex data related to the tessellation of a SkPatch. It is passed
- * as a parameter to the function getVertexData which sets the points, colors and texture
- * coordinates of the vertices and the indices for them to be drawn as triangles.
- */
- struct VertexData {
- int fVertexCount, fIndexCount;
- SkPoint* fPoints;
- SkPoint* fTexCoords;
- uint32_t* fColors;
- uint16_t* fIndices;
-
- VertexData()
- : fVertexCount(0)
- , fIndexCount(0)
- , fPoints(NULL)
- , fTexCoords(NULL)
- , fColors(NULL)
- , fIndices(NULL) { }
-
- ~VertexData() {
- SkDELETE_ARRAY(fPoints);
- SkDELETE_ARRAY(fTexCoords);
- SkDELETE_ARRAY(fColors);
- SkDELETE_ARRAY(fIndices);
- }
- };
-
- enum CubicCtrlPts {
- kTopP0_CubicCtrlPts = 0,
- kTopP1_CubicCtrlPts = 1,
- kTopP2_CubicCtrlPts = 2,
- kTopP3_CubicCtrlPts = 3,
-
- kRightP0_CubicCtrlPts = 3,
- kRightP1_CubicCtrlPts = 4,
- kRightP2_CubicCtrlPts = 5,
- kRightP3_CubicCtrlPts = 6,
-
- kBottomP0_CubicCtrlPts = 9,
- kBottomP1_CubicCtrlPts = 8,
- kBottomP2_CubicCtrlPts = 7,
- kBottomP3_CubicCtrlPts = 6,
-
- kLeftP0_CubicCtrlPts = 0,
- kLeftP1_CubicCtrlPts = 11,
- kLeftP2_CubicCtrlPts = 10,
- kLeftP3_CubicCtrlPts = 9,
- };
-
- /**
- * Points are in the following order:
- * (top curve)
- * 0 1 2 3
- * (left curve) 11 4 (right curve)
- * 10 5
- * 9 8 7 6
- * (bottom curve)
- * Used pointer to an array to guarantee that this method receives an array of 4 SkColors
- */
- SkPatch(SkPoint points[12], SkColor colors[4]);
-
- /**
- * Function that evaluates the coons patch interpolation.
- * data refers to the pointer of the PatchData struct in which the tessellation data is set.
- * divisions defines the number of steps in which the SkPatch is going to be subdivided per
- * axis.
- */
- bool getVertexData(SkPatch::VertexData* data, int divisions);
-
- void getTopPoints(SkPoint points[4]) {
- points[0] = fCtrlPoints[kTopP0_CubicCtrlPts];
- points[1] = fCtrlPoints[kTopP1_CubicCtrlPts];
- points[2] = fCtrlPoints[kTopP2_CubicCtrlPts];
- points[3] = fCtrlPoints[kTopP3_CubicCtrlPts];
- }
-
- void getBottomPoints(SkPoint points[4]) {
- points[0] = fCtrlPoints[kBottomP0_CubicCtrlPts];
- points[1] = fCtrlPoints[kBottomP1_CubicCtrlPts];
- points[2] = fCtrlPoints[kBottomP2_CubicCtrlPts];
- points[3] = fCtrlPoints[kBottomP3_CubicCtrlPts];
- }
-
- void getLeftPoints(SkPoint points[4]) {
- points[0] = fCtrlPoints[kLeftP0_CubicCtrlPts];
- points[1] = fCtrlPoints[kLeftP1_CubicCtrlPts];
- points[2] = fCtrlPoints[kLeftP2_CubicCtrlPts];
- points[3] = fCtrlPoints[kLeftP3_CubicCtrlPts];
- }
-
- void getRightPoints(SkPoint points[4]) {
- points[0] = fCtrlPoints[kRightP0_CubicCtrlPts];
- points[1] = fCtrlPoints[kRightP1_CubicCtrlPts];
- points[2] = fCtrlPoints[kRightP2_CubicCtrlPts];
- points[3] = fCtrlPoints[kRightP3_CubicCtrlPts];
- }
-
-private:
- SkPoint fCtrlPoints[12];
- SkPMColor fCornerColors[4];
-};
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkPath.h b/gfx/skia/skia/include/core/SkPath.h
index bccc8d52c9..33db8ac249 100644
--- a/gfx/skia/skia/include/core/SkPath.h
+++ b/gfx/skia/skia/include/core/SkPath.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,11 +5,9 @@
* found in the LICENSE file.
*/
-
#ifndef SkPath_DEFINED
#define SkPath_DEFINED
-#include "SkInstCnt.h"
#include "SkMatrix.h"
#include "SkPathRef.h"
#include "SkTDArray.h"
@@ -30,8 +27,6 @@ class SkWStream;
*/
class SK_API SkPath {
public:
- SK_DECLARE_INST_COUNT_ROOT(SkPath);
-
SkPath();
SkPath(const SkPath&);
~SkPath();
@@ -42,6 +37,11 @@ public:
return !(a == b);
}
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ /** Returns true if the caller is the only owner of the underlying path data */
+ bool unique() const { return fPathRef->unique(); }
+#endif
+
enum FillType {
/** Specifies that "inside" is computed by a non-zero sum of signed
edge crossings
@@ -154,6 +154,17 @@ public:
*/
bool isOval(SkRect* rect) const { return fPathRef->isOval(rect); }
+ /** Returns true if the path is a round rect.
+ *
+ * @param rrect Returns the bounding rect and radii of this round rect.
+ *
+ * @return true if this path is a round rect.
+ * Tracking whether a path is a round rect is considered an
+ * optimization for performance and so some paths that are in
+ * fact round rects can report false.
+ */
+ bool isRRect(SkRRect* rrect) const { return fPathRef->isRRect(rrect); }
+
/** Clear any lines and curves from the path, making it empty. This frees up
internal storage associated with those segments.
On Android, does not change fSourcePath.
@@ -185,12 +196,29 @@ public:
return fPathRef->isFinite();
}
+ /** Returns true if the path is volatile (i.e. should not be cached by devices.)
+ */
+ bool isVolatile() const {
+ return SkToBool(fIsVolatile);
+ }
+
+ /** Specify whether this path is volatile. Paths are not volatile by
+ default. Temporary paths that are discarded or modified after use should be
+ marked as volatile. This provides a hint to the device that the path
+ should not be cached. Providing this hint when appropriate can
+ improve performance by avoiding unnecessary overhead and resource
+ consumption on the device.
+ */
+ void setIsVolatile(bool isVolatile) {
+ fIsVolatile = isVolatile;
+ }
+
/** Test a line for zero length
@return true if the line is of zero length; otherwise false.
*/
- static bool IsLineDegenerate(const SkPoint& p1, const SkPoint& p2) {
- return p1.equalsWithinTolerance(p2);
+ static bool IsLineDegenerate(const SkPoint& p1, const SkPoint& p2, bool exact) {
+ return exact ? p1 == p2 : p1.equalsWithinTolerance(p2);
}
/** Test a quad for zero length
@@ -198,8 +226,8 @@ public:
@return true if the quad is of zero length; otherwise false.
*/
static bool IsQuadDegenerate(const SkPoint& p1, const SkPoint& p2,
- const SkPoint& p3) {
- return p1.equalsWithinTolerance(p2) &&
+ const SkPoint& p3, bool exact) {
+ return exact ? p1 == p2 && p2 == p3 : p1.equalsWithinTolerance(p2) &&
p2.equalsWithinTolerance(p3);
}
@@ -208,8 +236,8 @@ public:
@return true if the cubic is of zero length; otherwise false.
*/
static bool IsCubicDegenerate(const SkPoint& p1, const SkPoint& p2,
- const SkPoint& p3, const SkPoint& p4) {
- return p1.equalsWithinTolerance(p2) &&
+ const SkPoint& p3, const SkPoint& p4, bool exact) {
+ return exact ? p1 == p2 && p2 == p3 && p3 == p4 : p1.equalsWithinTolerance(p2) &&
p2.equalsWithinTolerance(p3) &&
p3.equalsWithinTolerance(p4);
}
@@ -222,16 +250,6 @@ public:
*/
bool isLine(SkPoint line[2]) const;
- /** Returns true if the path specifies a rectangle. If so, and if rect is
- not null, set rect to the bounds of the path. If the path does not
- specify a rectangle, return false and ignore rect.
-
- @param rect If not null, returns the bounds of the path if it specifies
- a rectangle
- @return true if the path specifies a rectangle
- */
- bool isRect(SkRect* rect) const;
-
/** Return the number of points in the path
*/
int countPoints() const;
@@ -266,10 +284,12 @@ public:
//! Swap contents of this and other. Guaranteed not to throw
void swap(SkPath& other);
- /** Returns the bounds of the path's points. If the path contains 0 or 1
- points, the bounds is set to (0,0,0,0), and isEmpty() will return true.
- Note: this bounds may be larger than the actual shape, since curves
- do not extend as far as their control points.
+ /**
+ * Returns the bounds of the path's points. If the path contains zero points/verbs, this
+ * will return the "empty" rect [0, 0, 0, 0].
+ * Note: this bounds may be larger than the actual shape, since curves
+ * do not extend as far as their control points. Additionally this bound encompases all points,
+ * even isolated moveTos either preceeding or following the last non-degenerate contour.
*/
const SkRect& getBounds() const {
return fPathRef->getBounds();
@@ -450,26 +470,23 @@ public:
void rCubicTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2,
SkScalar x3, SkScalar y3);
- /** Append the specified arc to the path as a new contour. If the start of
- the path is different from the path's current last point, then an
- automatic lineTo() is added to connect the current contour to the start
- of the arc. However, if the path is empty, then we call moveTo() with
- the first point of the arc. The sweep angle is treated mod 360.
+ /**
+ * Append the specified arc to the path. If the start of the arc is different from the path's
+ * current last point, then an automatic lineTo() is added to connect the current contour
+ * to the start of the arc. However, if the path is empty, then we call moveTo() with
+ * the first point of the arc. The sweep angle is treated mod 360.
+ *
+ * @param oval The bounding oval defining the shape and size of the arc
+ * @param startAngle Starting angle (in degrees) where the arc begins
+ * @param sweepAngle Sweep angle (in degrees) measured clockwise. This is treated mod 360.
+ * @param forceMoveTo If true, always begin a new contour with the arc
+ */
+ void arcTo(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle, bool forceMoveTo);
- @param oval The bounding oval defining the shape and size of the arc
- @param startAngle Starting angle (in degrees) where the arc begins
- @param sweepAngle Sweep angle (in degrees) measured clockwise. This is
- treated mod 360.
- @param forceMoveTo If true, always begin a new contour with the arc
- */
- void arcTo(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
- bool forceMoveTo);
-
- /** Append a line and arc to the current path. This is the same as the
- PostScript call "arct".
- */
- void arcTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2,
- SkScalar radius);
+ /**
+ * Append a line and arc to the current path. This is the same as the PostScript call "arct".
+ */
+ void arcTo(SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2, SkScalar radius);
/** Append a line and arc to the current path. This is the same as the
PostScript call "arct".
@@ -484,25 +501,12 @@ public:
void close();
enum Direction {
- /** Direction either has not been or could not be computed */
- kUnknown_Direction,
/** clockwise direction for adding closed contours */
kCW_Direction,
/** counter-clockwise direction for adding closed contours */
kCCW_Direction,
};
- /**
- * Return the opposite of the specified direction. kUnknown is its own
- * opposite.
- */
- static Direction OppositeDirection(Direction dir) {
- static const Direction gOppositeDir[] = {
- kUnknown_Direction, kCCW_Direction, kCW_Direction
- };
- return gOppositeDir[dir];
- }
-
/**
* Returns whether or not a fill type is inverted
*
@@ -512,10 +516,10 @@ public:
* kInverseEvenOdd_FillType -> true
*/
static bool IsInverseFillType(FillType fill) {
- SK_COMPILE_ASSERT(0 == kWinding_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(1 == kEvenOdd_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(2 == kInverseWinding_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(3 == kInverseEvenOdd_FillType, fill_type_mismatch);
+ static_assert(0 == kWinding_FillType, "fill_type_mismatch");
+ static_assert(1 == kEvenOdd_FillType, "fill_type_mismatch");
+ static_assert(2 == kInverseWinding_FillType, "fill_type_mismatch");
+ static_assert(3 == kInverseEvenOdd_FillType, "fill_type_mismatch");
return (fill & 2) != 0;
}
@@ -528,65 +532,39 @@ public:
* kInverseEvenOdd_FillType -> kEvenOdd_FillType
*/
static FillType ConvertToNonInverseFillType(FillType fill) {
- SK_COMPILE_ASSERT(0 == kWinding_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(1 == kEvenOdd_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(2 == kInverseWinding_FillType, fill_type_mismatch);
- SK_COMPILE_ASSERT(3 == kInverseEvenOdd_FillType, fill_type_mismatch);
+ static_assert(0 == kWinding_FillType, "fill_type_mismatch");
+ static_assert(1 == kEvenOdd_FillType, "fill_type_mismatch");
+ static_assert(2 == kInverseWinding_FillType, "fill_type_mismatch");
+ static_assert(3 == kInverseEvenOdd_FillType, "fill_type_mismatch");
return (FillType)(fill & 1);
}
/**
- * Tries to quickly compute the direction of the first non-degenerate
- * contour. If it can be computed, return true and set dir to that
- * direction. If it cannot be (quickly) determined, return false and ignore
- * the dir parameter. If the direction was determined, it is cached to make
- * subsequent calls return quickly.
+ * Chop a conic into N quads, stored continguously in pts[], where
+ * N = 1 << pow2. The amount of storage needed is (1 + 2 * N)
*/
- bool cheapComputeDirection(Direction* dir) const;
+ static int ConvertConicToQuads(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
+ SkScalar w, SkPoint pts[], int pow2);
/**
- * Returns true if the path's direction can be computed via
- * cheapComputDirection() and if that computed direction matches the
- * specified direction. If dir is kUnknown, returns true if the direction
- * cannot be computed.
+ * Returns true if the path specifies a rectangle.
+ *
+ * If this returns false, then all output parameters are ignored, and left
+ * unchanged. If this returns true, then each of the output parameters
+ * are checked for NULL. If they are not, they return their value.
+ *
+ * @param rect If not null, set to the bounds of the rectangle.
+ * Note : this bounds may be smaller than the path's bounds, since it is just
+ * the bounds of the "drawable" parts of the path. e.g. a trailing MoveTo would
+ * be ignored in this rect, but not by the path's bounds
+ * @param isClosed If not null, set to true if the path is closed
+ * @param direction If not null, set to the rectangle's direction
+ * @return true if the path specifies a rectangle
*/
- bool cheapIsDirection(Direction dir) const {
- Direction computedDir = kUnknown_Direction;
- (void)this->cheapComputeDirection(&computedDir);
- return computedDir == dir;
- }
+ bool isRect(SkRect* rect, bool* isClosed = NULL, Direction* direction = NULL) const;
- enum PathAsRect {
- /** The path can not draw the same as its bounds. */
- kNone_PathAsRect,
- /** The path draws the same as its bounds when filled. */
- kFill_PathAsRect,
- /** The path draws the same as its bounds when stroked or filled. */
- kStroke_PathAsRect,
- };
-
- /** Returns kFill_PathAsRect or kStroke_PathAsRect if drawing the path (either filled or
- stroked) will be equivalent to filling/stroking the path's bounding rect. If
- either is true, and direction is not null, sets the direction of the contour. If the
- path is not drawn equivalent to a rect, returns kNone_PathAsRect and ignores direction.
-
- @param direction If not null, set to the contour's direction when it is drawn as a rect
- @return the path's PathAsRect type
- */
- PathAsRect asRect(Direction* direction = NULL) const;
-
- /** Returns true if the path specifies a rectangle. If so, and if isClosed is
- not null, set isClosed to true if the path is closed. Also, if returning true
- and direction is not null, return the rect direction. If the path does not
- specify a rectangle, return false and ignore isClosed and direction.
-
- @param isClosed If not null, set to true if the path is closed
- @param direction If not null, set to the rectangle's direction
- @return true if the path specifies a rectangle
- */
- bool isRect(bool* isClosed, Direction* direction) const;
-
- /** Returns true if the path specifies a pair of nested rectangles. If so, and if
+ /** Returns true if the path specifies a pair of nested rectangles, or would draw a
+ pair of nested rectangles when filled. If so, and if
rect is not null, set rect[0] to the outer rectangle and rect[1] to the inner
rectangle. If so, and dirs is not null, set dirs[0] to the direction of
the outer rectangle and dirs[1] to the direction of the inner rectangle. If
@@ -597,16 +575,32 @@ public:
@param dirs If not null, returns the direction of the rects
@return true if the path describes a pair of nested rectangles
*/
- bool isNestedRects(SkRect rect[2], Direction dirs[2] = NULL) const;
+ bool isNestedFillRects(SkRect rect[2], Direction dirs[2] = NULL) const;
/**
* Add a closed rectangle contour to the path
* @param rect The rectangle to add as a closed contour to the path
- * @param dir The direction to wind the rectangle's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the rectangle's contour.
+ *
+ * Note: the contour initial point index is 0 (as defined below).
*/
void addRect(const SkRect& rect, Direction dir = kCW_Direction);
+ /**
+ * Add a closed rectangle contour to the path
+ * @param rect The rectangle to add as a closed contour to the path
+ * @param dir The direction to wind the rectangle's contour.
+ * @param start Initial point of the contour (initial moveTo), expressed as
+ * a corner index, starting in the upper-left position, clock-wise:
+ *
+ * 0 1
+ * *-------*
+ * | |
+ * *-------*
+ * 3 2
+ */
+ void addRect(const SkRect& rect, Direction dir, unsigned start);
+
/**
* Add a closed rectangle contour to the path
*
@@ -618,8 +612,9 @@ public:
* to the path
* @param bottom The bottom of a rectangle to add as a closed contour to
* the path
- * @param dir The direction to wind the rectangle's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the rectangle's contour.
+ *
+ * Note: the contour initial point index is 0 (as defined above).
*/
void addRect(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom,
Direction dir = kCW_Direction);
@@ -628,11 +623,31 @@ public:
* Add a closed oval contour to the path
*
* @param oval The bounding oval to add as a closed contour to the path
- * @param dir The direction to wind the oval's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the oval's contour.
+ *
+ * Note: the contour initial point index is 1 (as defined below).
*/
void addOval(const SkRect& oval, Direction dir = kCW_Direction);
+ /**
+ * Add a closed oval contour to the path
+ *
+ * @param oval The bounding oval to add as a closed contour to the path
+ * @param dir The direction to wind the oval's contour.
+ * @param start Initial point of the contour (initial moveTo), expressed
+ * as an ellipse vertex index, starting at the top, clock-wise
+ * (90/0/270/180deg order):
+ *
+ * 0
+ * -*-
+ * | |
+ * 3 * * 1
+ * | |
+ * -*-
+ * 2
+ */
+ void addOval(const SkRect& oval, Direction dir, unsigned start);
+
/**
* Add a closed circle contour to the path
*
@@ -642,8 +657,7 @@ public:
* closed contour to the path
* @param radius The radius of a circle to add as a closed contour to the
* path
- * @param dir The direction to wind the circle's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the circle's contour.
*/
void addCircle(SkScalar x, SkScalar y, SkScalar radius,
Direction dir = kCW_Direction);
@@ -661,8 +675,7 @@ public:
* @param rect The bounds of a round-rectangle to add as a closed contour
* @param rx The x-radius of the rounded corners on the round-rectangle
* @param ry The y-radius of the rounded corners on the round-rectangle
- * @param dir The direction to wind the rectangle's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the rectangle's contour.
*/
void addRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry,
Direction dir = kCW_Direction);
@@ -673,8 +686,7 @@ public:
* bottom-right, bottom-left.
* @param rect The bounds of a round-rectangle to add as a closed contour
* @param radii Array of 8 scalars, 4 [X,Y] pairs for each corner
- * @param dir The direction to wind the rectangle's contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The direction to wind the rectangle's contour.
* Note: The radii here now go through the same constraint handling as the
* SkRRect radii (i.e., either radii at a corner being 0 implies a
* sqaure corner and oversized radii are proportionally scaled down).
@@ -685,11 +697,31 @@ public:
/**
* Add an SkRRect contour to the path
* @param rrect The rounded rect to add as a closed contour
- * @param dir The winding direction for the new contour. Cannot be
- * kUnknown_Direction.
+ * @param dir The winding direction for the new contour.
+ *
+ * Note: the contour initial point index is either 6 (for dir == kCW_Direction)
+ * or 7 (for dir == kCCW_Direction), as defined below.
+ *
*/
void addRRect(const SkRRect& rrect, Direction dir = kCW_Direction);
+ /**
+ * Add an SkRRect contour to the path
+ * @param rrect The rounded rect to add as a closed contour
+ * @param dir The winding direction for the new contour.
+ * @param start Initial point of the contour (initial moveTo), expressed as
+ * an index of the radii minor/major points, ordered clock-wise:
+ *
+ * 0 1
+ * *----*
+ * 7 * * 2
+ * | |
+ * 6 * * 3
+ * *----*
+ * 5 4
+ */
+ void addRRect(const SkRRect& rrect, Direction dir, unsigned start);
+
/**
* Add a new contour made of just lines. This is just a fast version of
* the following:
@@ -848,11 +880,15 @@ public:
@param pts The points representing the current verb and/or segment
@param doConsumeDegerates If true, first scan for segments that are
deemed degenerate (too short) and skip those.
+ @param exact if doConsumeDegenerates is true and exact is true, skip only
+ degenerate elements with lengths exactly equal to zero. If exact
+ is false, skip degenerate elements with lengths close to zero. If
+ doConsumeDegenerates is false, exact has no effect.
@return The verb for the current segment
*/
- Verb next(SkPoint pts[4], bool doConsumeDegerates = true) {
+ Verb next(SkPoint pts[4], bool doConsumeDegerates = true, bool exact = false) {
if (doConsumeDegerates) {
- this->consumeDegenerateSegments();
+ this->consumeDegenerateSegments(exact);
}
return this->doNext(pts);
}
@@ -892,7 +928,7 @@ public:
inline const SkPoint& cons_moveTo();
Verb autoClose(SkPoint pts[2]);
- void consumeDegenerateSegments();
+ void consumeDegenerateSegments(bool exact);
Verb doNext(SkPoint pts[4]);
};
@@ -900,10 +936,14 @@ public:
*/
class SK_API RawIter {
public:
- RawIter();
- RawIter(const SkPath&);
+ RawIter() {}
+ RawIter(const SkPath& path) {
+ setPath(path);
+ }
- void setPath(const SkPath&);
+ void setPath(const SkPath& path) {
+ fRawIter.setPathRef(*path.fPathRef.get());
+ }
/** Return the next verb in this iteration of the path. When all
segments have been visited, return kDone_Verb.
@@ -912,17 +952,17 @@ public:
This must not be NULL.
@return The verb for the current segment
*/
- Verb next(SkPoint pts[4]);
+ Verb next(SkPoint pts[4]) {
+ return (Verb) fRawIter.next(pts);
+ }
- SkScalar conicWeight() const { return *fConicWeights; }
+ SkScalar conicWeight() const {
+ return fRawIter.conicWeight();
+ }
private:
- const SkPoint* fPts;
- const uint8_t* fVerbs;
- const uint8_t* fVerbStop;
- const SkScalar* fConicWeights;
- SkPoint fMoveTo;
- SkPoint fLastPt;
+ SkPathRef::Iter fRawIter;
+ friend class SkPath;
};
/**
@@ -931,8 +971,9 @@ public:
*/
bool contains(SkScalar x, SkScalar y) const;
- void dump(SkWStream* , bool forceClose) const;
+ void dump(SkWStream* , bool forceClose, bool dumpAsHex) const;
void dump() const;
+ void dumpHex() const;
/**
* Write the path to the buffer, and return the number of bytes written.
@@ -955,37 +996,39 @@ public:
*/
uint32_t getGenerationID() const;
-#ifdef SK_BUILD_FOR_ANDROID
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
static const int kPathRefGenIDBitCnt = 30; // leave room for the fill type (skbug.com/1762)
- const SkPath* getSourcePath() const;
- void setSourcePath(const SkPath* path);
#else
static const int kPathRefGenIDBitCnt = 32;
#endif
SkDEBUGCODE(void validate() const;)
+ SkDEBUGCODE(void experimentalValidateRef() const { fPathRef->validate(); } )
private:
enum SerializationOffsets {
// 1 free bit at 29
kUnused1_SerializationShift = 28, // 1 free bit
kDirection_SerializationShift = 26, // requires 2 bits
- kUnused2_SerializationShift = 25, // 1 free bit
+ kIsVolatile_SerializationShift = 25, // requires 1 bit
// 1 free bit at 24
kConvexity_SerializationShift = 16, // requires 8 bits
kFillType_SerializationShift = 8, // requires 8 bits
- // 8 free bits at 0
+ // low-8-bits are version
};
- SkAutoTUnref fPathRef;
+ enum SerializationVersions {
+ kPathPrivFirstDirection_Version = 1,
- int fLastMoveToIndex;
- uint8_t fFillType;
- mutable uint8_t fConvexity;
- mutable uint8_t fDirection;
-#ifdef SK_BUILD_FOR_ANDROID
- const SkPath* fSourcePath;
-#endif
+ kCurrent_Version = 1
+ };
+
+ SkAutoTUnref fPathRef;
+ int fLastMoveToIndex;
+ uint8_t fFillType;
+ mutable uint8_t fConvexity;
+ mutable SkAtomic fFirstDirection;// SkPathPriv::FirstDirection
+ mutable SkBool8 fIsVolatile;
/** Resets all fields other than fPathRef to their initial 'empty' values.
* Assumes the caller has already emptied fPathRef.
@@ -1000,7 +1043,7 @@ private:
void copyFields(const SkPath& that);
friend class Iter;
-
+ friend class SkPathPriv;
friend class SkPathStroker;
/* Append, in reverse order, the first contour of path, ignoring path's
@@ -1040,11 +1083,14 @@ private:
ed.setBounds(rect);
}
+ void setPt(int index, SkScalar x, SkScalar y);
+
friend class SkAutoPathBoundsUpdate;
friend class SkAutoDisableOvalCheck;
friend class SkAutoDisableDirectionCheck;
friend class SkBench_AddPathTest; // perf test reversePathTo
friend class PathTest_Private; // unit test reversePathTo
+ friend class ForceIsRRect_Private; // unit test isRRect
};
#endif
diff --git a/gfx/skia/skia/include/core/SkPathEffect.h b/gfx/skia/skia/include/core/SkPathEffect.h
index 562025351e..36e67e1de0 100644
--- a/gfx/skia/skia/include/core/SkPathEffect.h
+++ b/gfx/skia/skia/include/core/SkPathEffect.h
@@ -14,10 +14,10 @@
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRect.h"
-#include "SkStrokeRec.h"
#include "SkTDArray.h"
class SkPath;
+class SkStrokeRec;
/** \class SkPathEffect
@@ -29,8 +29,6 @@ class SkPath;
*/
class SK_API SkPathEffect : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkPathEffect)
-
/**
* Given a src path (input) and a stroke-rec (input and output), apply
* this effect to the src path, returning the new path in dst, and return
@@ -131,11 +129,16 @@ public:
virtual DashType asADash(DashInfo* info) const;
+ SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkPathEffect)
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ /// Override for subclasses as appropriate.
+ virtual bool exposedInAndroidJavaAPI() const { return false; }
+#endif
+
protected:
SkPathEffect() {}
- SkPathEffect(SkReadBuffer& buffer) : INHERITED(buffer) {}
private:
// illegal
@@ -157,12 +160,14 @@ public:
protected:
SkPairPathEffect(SkPathEffect* pe0, SkPathEffect* pe1);
- SkPairPathEffect(SkReadBuffer&);
- virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
+
+ void flatten(SkWriteBuffer&) const override;
// these are visible to our subclasses
SkPathEffect* fPE0, *fPE1;
+ SK_TO_STRING_OVERRIDE()
+
private:
typedef SkPathEffect INHERITED;
};
@@ -180,18 +185,21 @@ public:
and decremented in the destructor.
*/
static SkComposePathEffect* Create(SkPathEffect* outer, SkPathEffect* inner) {
- return SkNEW_ARGS(SkComposePathEffect, (outer, inner));
+ return new SkComposePathEffect(outer, inner);
}
virtual bool filterPath(SkPath* dst, const SkPath& src,
- SkStrokeRec*, const SkRect*) const SK_OVERRIDE;
+ SkStrokeRec*, const SkRect*) const override;
+ SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkComposePathEffect)
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ bool exposedInAndroidJavaAPI() const override { return true; }
+#endif
+
protected:
- SkComposePathEffect(SkPathEffect* outer, SkPathEffect* inner)
- : INHERITED(outer, inner) {}
- explicit SkComposePathEffect(SkReadBuffer& buffer) : INHERITED(buffer) {}
+ SkComposePathEffect(SkPathEffect* outer, SkPathEffect* inner) : INHERITED(outer, inner) {}
private:
// illegal
@@ -214,18 +222,21 @@ public:
and decremented in the destructor.
*/
static SkSumPathEffect* Create(SkPathEffect* first, SkPathEffect* second) {
- return SkNEW_ARGS(SkSumPathEffect, (first, second));
+ return new SkSumPathEffect(first, second);
}
virtual bool filterPath(SkPath* dst, const SkPath& src,
- SkStrokeRec*, const SkRect*) const SK_OVERRIDE;
+ SkStrokeRec*, const SkRect*) const override;
+ SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkSumPathEffect)
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ bool exposedInAndroidJavaAPI() const override { return true; }
+#endif
+
protected:
- SkSumPathEffect(SkPathEffect* first, SkPathEffect* second)
- : INHERITED(first, second) {}
- explicit SkSumPathEffect(SkReadBuffer& buffer) : INHERITED(buffer) {}
+ SkSumPathEffect(SkPathEffect* first, SkPathEffect* second) : INHERITED(first, second) {}
private:
// illegal
diff --git a/gfx/skia/skia/include/core/SkPathMeasure.h b/gfx/skia/skia/include/core/SkPathMeasure.h
index bc46b4a38b..f6e606f0c0 100644
--- a/gfx/skia/skia/include/core/SkPathMeasure.h
+++ b/gfx/skia/skia/include/core/SkPathMeasure.h
@@ -11,6 +11,8 @@
#include "SkPath.h"
#include "SkTDArray.h"
+struct SkConic;
+
class SK_API SkPathMeasure : SkNoncopyable {
public:
SkPathMeasure();
@@ -101,6 +103,7 @@ private:
void buildSegments();
SkScalar compute_quad_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, int ptIndex);
+ SkScalar compute_conic_segs(const SkConic&, SkScalar distance, int mint, int maxt, int ptIndex);
SkScalar compute_cubic_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, int ptIndex);
const Segment* distanceToSegment(SkScalar distance, SkScalar* t);
diff --git a/gfx/skia/skia/include/core/SkPathRef.h b/gfx/skia/skia/include/core/SkPathRef.h
index ba68fcba3c..86f55c9bca 100644
--- a/gfx/skia/skia/include/core/SkPathRef.h
+++ b/gfx/skia/skia/include/core/SkPathRef.h
@@ -9,9 +9,9 @@
#ifndef SkPathRef_DEFINED
#define SkPathRef_DEFINED
-#include "SkDynamicAnnotations.h"
#include "SkMatrix.h"
#include "SkPoint.h"
+#include "SkRRect.h"
#include "SkRect.h"
#include "SkRefCnt.h"
#include "SkTDArray.h"
@@ -37,8 +37,6 @@ class SkWBuffer;
class SK_API SkPathRef : public ::SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkPathRef);
-
class Editor {
public:
Editor(SkAutoTUnref* pathRef,
@@ -103,12 +101,39 @@ public:
void setIsOval(bool isOval) { fPathRef->setIsOval(isOval); }
+ void setIsRRect(bool isRRect) { fPathRef->setIsRRect(isRRect); }
+
void setBounds(const SkRect& rect) { fPathRef->setBounds(rect); }
private:
SkPathRef* fPathRef;
};
+ class SK_API Iter {
+ public:
+ Iter();
+ Iter(const SkPathRef&);
+
+ void setPathRef(const SkPathRef&);
+
+ /** Return the next verb in this iteration of the path. When all
+ segments have been visited, return kDone_Verb.
+
+ @param pts The points representing the current verb and/or segment
+ This must not be NULL.
+ @return The verb for the current segment
+ */
+ uint8_t next(SkPoint pts[4]);
+
+ SkScalar conicWeight() const { return *fConicWeights; }
+
+ private:
+ const SkPoint* fPts;
+ const uint8_t* fVerbs;
+ const uint8_t* fVerbStop;
+ const SkScalar* fConicWeights;
+ };
+
public:
/**
* Gets a path ref with no verbs or points.
@@ -144,13 +169,21 @@ public:
* fact ovals can report false.
*/
bool isOval(SkRect* rect) const {
- if (fIsOval && NULL != rect) {
- *rect = getBounds();
+ if (fIsOval && rect) {
+ *rect = this->getBounds();
}
return SkToBool(fIsOval);
}
+ bool isRRect(SkRRect* rrect) const {
+ if (fIsRRect && rrect) {
+ *rrect = this->getRRect();
+ }
+ return SkToBool(fIsRRect);
+ }
+
+
bool hasComputedBounds() const {
return !fBoundsIsDirty;
}
@@ -167,6 +200,8 @@ public:
return fBounds;
}
+ SkRRect getRRect() const;
+
/**
* Transforms a path ref by a matrix, allocating a new one only if necessary.
*/
@@ -183,19 +218,7 @@ public:
*/
static void Rewind(SkAutoTUnref* pathRef);
- virtual ~SkPathRef() {
- SkDEBUGCODE(this->validate();)
- sk_free(fPoints);
-
- SkDEBUGCODE(fPoints = NULL;)
- SkDEBUGCODE(fVerbs = NULL;)
- SkDEBUGCODE(fVerbCnt = 0x9999999;)
- SkDEBUGCODE(fPointCnt = 0xAAAAAAA;)
- SkDEBUGCODE(fPointCnt = 0xBBBBBBB;)
- SkDEBUGCODE(fGenerationID = 0xEEEEEEEE;)
- SkDEBUGCODE(fEditorsAttached = 0x7777777;)
- }
-
+ virtual ~SkPathRef();
int countPoints() const { SkDEBUGCODE(this->validate();) return fPointCnt; }
int countVerbs() const { SkDEBUGCODE(this->validate();) return fVerbCnt; }
int countWeights() const { SkDEBUGCODE(this->validate();) return fConicWeights.count(); }
@@ -254,8 +277,18 @@ public:
*/
uint32_t genID() const;
+ struct GenIDChangeListener {
+ virtual ~GenIDChangeListener() {}
+ virtual void onChange() = 0;
+ };
+
+ void addGenIDChangeListener(GenIDChangeListener* listener);
+
+ SkDEBUGCODE(void validate() const;)
+
private:
enum SerializationOffsets {
+ kIsRRect_SerializationShift = 26, // requires 1 bit
kIsFinite_SerializationShift = 25, // requires 1 bit
kIsOval_SerializationShift = 24, // requires 1 bit
kSegmentMask_SerializationShift = 0 // requires 4 bits
@@ -271,6 +304,7 @@ private:
fGenerationID = kEmptyGenID;
fSegmentMask = 0;
fIsOval = false;
+ fIsRRect = false;
SkDEBUGCODE(fEditorsAttached = 0;)
SkDEBUGCODE(this->validate();)
}
@@ -279,13 +313,7 @@ private:
// Return true if the computed bounds are finite.
static bool ComputePtBounds(SkRect* bounds, const SkPathRef& ref) {
- int count = ref.countPoints();
- if (count <= 1) { // we ignore just 1 point (moveto)
- bounds->setEmpty();
- return count ? ref.points()->isFinite() : true;
- } else {
- return bounds->setBoundsCheck(ref.points(), count);
- }
+ return bounds->setBoundsCheck(ref.points(), ref.countPoints());
}
// called, if dirty, by getBounds()
@@ -293,9 +321,9 @@ private:
SkDEBUGCODE(this->validate();)
// TODO(mtklein): remove fBoundsIsDirty and fIsFinite,
// using an inverted rect instead of fBoundsIsDirty and always recalculating fIsFinite.
- //SkASSERT(fBoundsIsDirty);
+ SkASSERT(fBoundsIsDirty);
- fIsFinite = ComputePtBounds(fBounds.get(), *this);
+ fIsFinite = ComputePtBounds(&fBounds, *this);
fBoundsIsDirty = false;
}
@@ -303,7 +331,7 @@ private:
SkASSERT(rect.fLeft <= rect.fRight && rect.fTop <= rect.fBottom);
fBounds = rect;
fBoundsIsDirty = false;
- fIsFinite = fBounds->isFinite();
+ fIsFinite = fBounds.isFinite();
}
/** Makes additional room but does not change the counts or change the genID */
@@ -324,6 +352,7 @@ private:
fSegmentMask = 0;
fIsOval = false;
+ fIsRRect = false;
size_t newSize = sizeof(uint8_t) * verbCount + sizeof(SkPoint) * pointCount;
size_t newReserve = sizeof(uint8_t) * reserveVerbs + sizeof(SkPoint) * reservePoints;
@@ -416,31 +445,35 @@ private:
return reinterpret_cast(fVerbs) - reinterpret_cast(fPoints);
}
- SkDEBUGCODE(void validate() const;)
-
/**
* Called the first time someone calls CreateEmpty to actually create the singleton.
*/
- static SkPathRef* CreateEmptyImpl();
+ friend SkPathRef* sk_create_empty_pathref();
void setIsOval(bool isOval) { fIsOval = isOval; }
+ void setIsRRect(bool isRRect) { fIsRRect = isRRect; }
+
+ // called only by the editor. Note that this is not a const function.
SkPoint* getPoints() {
SkDEBUGCODE(this->validate();)
fIsOval = false;
+ fIsRRect = false;
return fPoints;
}
+ const SkPoint* getPoints() const {
+ SkDEBUGCODE(this->validate();)
+ return fPoints;
+ }
+
+ void callGenIDChangeListeners();
+
enum {
kMinSize = 256,
};
- mutable SkTRacyReffable fBounds;
- mutable SkTRacy fBoundsIsDirty;
- mutable SkTRacy fIsFinite; // only meaningful if bounds are valid
-
- SkBool8 fIsOval;
- uint8_t fSegmentMask;
+ mutable SkRect fBounds;
SkPoint* fPoints; // points to begining of the allocation
uint8_t* fVerbs; // points just past the end of the allocation (verbs grow backwards)
@@ -455,7 +488,17 @@ private:
mutable uint32_t fGenerationID;
SkDEBUGCODE(int32_t fEditorsAttached;) // assert that only one editor in use at any time.
+ SkTDArray fGenIDChangeListeners; // pointers are owned
+
+ mutable uint8_t fBoundsIsDirty;
+ mutable SkBool8 fIsFinite; // only meaningful if bounds are valid
+
+ SkBool8 fIsOval;
+ SkBool8 fIsRRect;
+ uint8_t fSegmentMask;
+
friend class PathRefTest_Private;
+ friend class ForceIsRRect_Private; // unit test isRRect
typedef SkRefCnt INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkPicture.h b/gfx/skia/skia/include/core/SkPicture.h
index 21ebef32cd..720747e9a3 100644
--- a/gfx/skia/skia/include/core/SkPicture.h
+++ b/gfx/skia/skia/include/core/SkPicture.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2007 The Android Open Source Project
*
@@ -6,72 +5,33 @@
* found in the LICENSE file.
*/
-
#ifndef SkPicture_DEFINED
#define SkPicture_DEFINED
-#include "SkBitmap.h"
-#include "SkDrawPictureCallback.h"
#include "SkImageDecoder.h"
#include "SkRefCnt.h"
-#include "SkTDArray.h"
+#include "SkTypes.h"
-#if SK_SUPPORT_GPU
class GrContext;
-#endif
-
-class SkBBHFactory;
-class SkBBoxHierarchy;
+class SkBigPicture;
+class SkBitmap;
class SkCanvas;
-class SkData;
class SkPictureData;
-class SkPictureRecord;
+class SkPixelSerializer;
+class SkRefCntSet;
class SkStream;
+class SkTypefacePlayback;
class SkWStream;
-
struct SkPictInfo;
-class SkRecord;
-
/** \class SkPicture
- The SkPicture class records the drawing commands made to a canvas, to
- be played back at a later time.
+ An SkPicture records drawing commands made to a canvas to be played back at a later time.
+ This base class handles serialization and a few other miscellany.
*/
class SK_API SkPicture : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkPicture)
-
- // AccelData provides a base class for device-specific acceleration
- // data. It is added to the picture via a call to a device's optimize
- // method.
- class AccelData : public SkRefCnt {
- public:
- typedef uint8_t Domain;
- typedef uint32_t Key;
-
- AccelData(Key key) : fKey(key) { }
-
- const Key& getKey() const { return fKey; }
-
- // This entry point allows user's to get a unique domain prefix
- // for their keys
- static Domain GenerateDomain();
- private:
- Key fKey;
-
- typedef SkRefCnt INHERITED;
- };
-
-#ifdef SK_SUPPORT_LEGACY_DEFAULT_PICTURE_CTOR
- SkPicture();
-#endif
-
- /** PRIVATE / EXPERIMENTAL -- do not call */
- void EXPERIMENTAL_addAccelData(const AccelData*) const;
-
- /** PRIVATE / EXPERIMENTAL -- do not call */
- const AccelData* EXPERIMENTAL_getAccelData(AccelData::Key) const;
+ virtual ~SkPicture();
/**
* Function signature defining a function that sets up an SkBitmap from encoded data. On
@@ -88,7 +48,7 @@ public:
/**
* Recreate a picture that was serialized into a stream.
- * @param SkStream Serialized picture data.
+ * @param SkStream Serialized picture data. Ownership is unchanged by this call.
* @param proc Function pointer for installing pixelrefs on SkBitmaps representing the
* encoded bitmap data from the stream.
* @return A new SkPicture representing the serialized data, or NULL if the stream is
@@ -107,59 +67,45 @@ public:
*/
static SkPicture* CreateFromBuffer(SkReadBuffer&);
- virtual ~SkPicture();
-
-#ifdef SK_SUPPORT_LEGACY_PICTURE_CLONE
/**
- * Creates a thread-safe clone of the picture that is ready for playback.
- */
- SkPicture* clone() const;
-#endif
+ * Subclasses of this can be passed to playback(). During the playback
+ * of the picture, this callback will periodically be invoked. If its
+ * abort() returns true, then picture playback will be interrupted.
+ *
+ * The resulting drawing is undefined, as there is no guarantee how often the
+ * callback will be invoked. If the abort happens inside some level of nested
+ * calls to save(), restore will automatically be called to return the state
+ * to the same level it was before the playback call was made.
+ */
+ class SK_API AbortCallback {
+ public:
+ AbortCallback() {}
+ virtual ~AbortCallback() {}
+ virtual bool abort() = 0;
+ };
- /** Replays the drawing commands on the specified canvas.
+ /** Replays the drawing commands on the specified canvas. Note that
+ this has the effect of unfurling this picture into the destination
+ canvas. Using the SkCanvas::drawPicture entry point gives the destination
+ canvas the option of just taking a ref.
@param canvas the canvas receiving the drawing commands.
+ @param callback a callback that allows interruption of playback
*/
- void draw(SkCanvas* canvas, SkDrawPictureCallback* = NULL) const;
+ virtual void playback(SkCanvas*, AbortCallback* = NULL) const = 0;
- /** Return the width of the picture's recording canvas. This
- value reflects what was passed to setSize(), and does not necessarily
- reflect the bounds of what has been recorded into the picture.
- @return the width of the picture's recording canvas
- */
- int width() const { return fWidth; }
+ /** Return a cull rect for this picture.
+ Ops recorded into this picture that attempt to draw outside the cull might not be drawn.
+ */
+ virtual SkRect cullRect() const = 0;
- /** Return the height of the picture's recording canvas. This
- value reflects what was passed to setSize(), and does not necessarily
- reflect the bounds of what has been recorded into the picture.
- @return the height of the picture's recording canvas
- */
- int height() const { return fHeight; }
-
- /** Return a non-zero, unique value representing the picture. This call is
- only valid when not recording. Between a beginRecording/endRecording
- pair it will just return 0 (the invalid ID). Each beginRecording/
- endRecording pair will cause a different generation ID to be returned.
- */
+ /** Returns a non-zero value unique among all pictures. */
uint32_t uniqueID() const;
/**
- * Function to encode an SkBitmap to an SkData. A function with this
- * signature can be passed to serialize() and SkWriteBuffer.
- * Returning NULL will tell the SkWriteBuffer to use
- * SkBitmap::flatten() to store the bitmap.
- *
- * @param pixelRefOffset DEPRECATED -- caller assumes it will return 0.
- * @return SkData If non-NULL, holds encoded data representing the passed
- * in bitmap. The caller is responsible for calling unref().
+ * Serialize to a stream. If non NULL, serializer will be used to serialize
+ * bitmaps and images in the picture.
*/
- typedef SkData* (*EncodeBitmap)(size_t* pixelRefOffset, const SkBitmap& bm);
-
- /**
- * Serialize to a stream. If non NULL, encoder will be used to encode
- * any bitmaps in the picture.
- * encoder will never be called with a NULL pixelRefOffset.
- */
- void serialize(SkWStream*, EncodeBitmap encoder = NULL) const;
+ void serialize(SkWStream*, SkPixelSerializer* = NULL) const;
/**
* Serialize to a buffer.
@@ -170,7 +116,21 @@ public:
* Returns true if any bitmaps may be produced when this SkPicture
* is replayed.
*/
- bool willPlayBackBitmaps() const;
+ virtual bool willPlayBackBitmaps() const = 0;
+
+ /** Return the approximate number of operations in this picture. This
+ * number may be greater or less than the number of SkCanvas calls
+ * recorded: some calls may be recorded as more than one operation, or some
+ * calls may be optimized away.
+ */
+ virtual int approximateOpCount() const = 0;
+
+ /** Return true if this picture contains text.
+ */
+ virtual bool hasText() const = 0;
+
+ /** Returns the approximate byte size of this picture, not including large ref'd objects. */
+ virtual size_t approximateBytesUsed() const = 0;
/** Return true if the SkStream/Buffer represents a serialized picture, and
fills out SkPictInfo. After this function returns, the data source is not
@@ -181,116 +141,67 @@ public:
If false is returned, SkPictInfo is unmodified.
*/
static bool InternalOnly_StreamIsSKP(SkStream*, SkPictInfo*);
- static bool InternalOnly_BufferIsSKP(SkReadBuffer&, SkPictInfo*);
+ static bool InternalOnly_BufferIsSKP(SkReadBuffer*, SkPictInfo*);
- /** Return true if the picture is suitable for rendering on the GPU.
- */
+ /** Return true if the picture is suitable for rendering on the GPU. */
+ bool suitableForGpuRasterization(GrContext*, const char** whyNot = NULL) const;
-#if SK_SUPPORT_GPU
- bool suitableForGpuRasterization(GrContext*, const char ** = NULL) const;
-#endif
+ // Sent via SkMessageBus from destructor.
+ struct DeletionMessage { int32_t fUniqueID; }; // TODO: -> uint32_t?
- class DeletionListener : public SkRefCnt {
- public:
- virtual void onDeletion(uint32_t pictureID) = 0;
- };
+ // Returns NULL if this is not an SkBigPicture.
+ virtual const SkBigPicture* asSkBigPicture() const { return NULL; }
- // Takes ref on listener.
- void addDeletionListener(DeletionListener* listener) const;
+ // Global setting to enable or disable security precautions for serialization.
+ static void SetPictureIOSecurityPrecautionsEnabled_Dangerous(bool set);
+ static bool PictureIOSecurityPrecautionsEnabled();
private:
- // V2 : adds SkPixelRef's generation ID.
- // V3 : PictInfo tag at beginning, and EOF tag at the end
- // V4 : move SkPictInfo to be the header
- // V5 : don't read/write FunctionPtr on cross-process (we can detect that)
- // V6 : added serialization of SkPath's bounds (and packed its flags tighter)
- // V7 : changed drawBitmapRect(IRect) to drawBitmapRectToRect(Rect)
- // V8 : Add an option for encoding bitmaps
- // V9 : Allow the reader and writer of an SKP disagree on whether to support
- // SK_SUPPORT_HINTING_SCALE_FACTOR
- // V10: add drawRRect, drawOval, clipRRect
- // V11: modify how readBitmap and writeBitmap store their info.
- // V12: add conics to SkPath, use new SkPathRef flattening
- // V13: add flag to drawBitmapRectToRect
- // parameterize blurs by sigma rather than radius
- // V14: Add flags word to PathRef serialization
- // V15: Remove A1 bitmap config (and renumber remaining configs)
- // V16: Move SkPath's isOval flag to SkPathRef
- // V17: SkPixelRef now writes SkImageInfo
- // V18: SkBitmap now records x,y for its pixelref origin, instead of offset.
- // V19: encode matrices and regions into the ops stream
- // V20: added bool to SkPictureImageFilter's serialization (to allow SkPicture serialization)
- // V21: add pushCull, popCull
- // V22: SK_PICT_FACTORY_TAG's size is now the chunk size in bytes
- // V23: SkPaint::FilterLevel became a real enum
- // V24: SkTwoPointConicalGradient now has fFlipped flag for gradient flipping
- // V25: SkDashPathEffect now only writes phase and interval array when flattening
- // V26: Removed boolean from SkColorShader for inheriting color from SkPaint.
- // V27: Remove SkUnitMapper from gradients (and skia).
- // V28: No longer call bitmap::flatten inside SkWriteBuffer::writeBitmap.
- // V29: Removed SaveFlags parameter from save().
- // V30: Remove redundant SkMatrix from SkLocalMatrixShader.
+ // Subclass whitelist.
+ SkPicture();
+ friend class SkBigPicture;
+ friend class SkEmptyPicture;
+ template friend class SkMiniPicture;
- // Note: If the picture version needs to be increased then please follow the
- // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw
+ void serialize(SkWStream*, SkPixelSerializer*, SkRefCntSet* typefaces) const;
+ static SkPicture* CreateFromStream(SkStream*,
+ InstallPixelRefProc proc,
+ SkTypefacePlayback*);
+ friend class SkPictureData;
+
+ virtual int numSlowPaths() const = 0;
+ friend struct SkPathCounter;
+
+ // V35: Store SkRect (rather then width & height) in header
+ // V36: Remove (obsolete) alphatype from SkColorTable
+ // V37: Added shadow only option to SkDropShadowImageFilter (last version to record CLEAR)
+ // V38: Added PictureResolution option to SkPictureImageFilter
+ // V39: Added FilterLevel option to SkPictureImageFilter
+ // V40: Remove UniqueID serialization from SkImageFilter.
+ // V41: Added serialization of SkBitmapSource's filterQuality parameter
+ // V42: Added a bool to SkPictureShader serialization to indicate did-we-serialize-a-picture?
+ // V43: Added DRAW_IMAGE and DRAW_IMAGE_RECT opt codes to serialized data
// Only SKPs within the min/current picture version range (inclusive) can be read.
- static const uint32_t MIN_PICTURE_VERSION = 19;
- static const uint32_t CURRENT_PICTURE_VERSION = 30;
+ static const uint32_t MIN_PICTURE_VERSION = 35; // Produced by Chrome M39.
+ static const uint32_t CURRENT_PICTURE_VERSION = 43;
- mutable uint32_t fUniqueID;
+ static_assert(MIN_PICTURE_VERSION <= 41,
+ "Remove kFontFileName and related code from SkFontDescriptor.cpp.");
- // TODO: make SkPictureData const when clone method goes away
- SkAutoTDelete fData;
- int fWidth, fHeight;
- mutable SkAutoTUnref fAccelData;
+ static_assert(MIN_PICTURE_VERSION <= 42,
+ "Remove COMMENT API handlers from SkPicturePlayback.cpp");
- mutable SkTDArray fDeletionListeners; // pointers are refed
+ static_assert(MIN_PICTURE_VERSION <= 43,
+ "Remove SkBitmapSourceDeserializer.");
- void needsNewGenID() { fUniqueID = SK_InvalidGenID; }
- void callDeletionListeners();
-
- // Create a new SkPicture from an existing SkPictureData. The new picture
- // takes ownership of 'data'.
- SkPicture(SkPictureData* data, int width, int height);
-
- SkPicture(int width, int height, const SkPictureRecord& record, bool deepCopyOps);
-
- // An OperationList encapsulates a set of operation offsets into the picture byte
- // stream along with the CTMs needed for those operation.
- class OperationList : ::SkNoncopyable {
- public:
- // The following three entry points should only be accessed if
- // 'valid' returns true.
- int numOps() const { return fOps.count(); }
- // The offset in the picture of the operation to execute.
- uint32_t offset(int index) const;
- // The CTM that must be installed for the operation to behave correctly
- const SkMatrix& matrix(int index) const;
-
- SkTDArray fOps;
- };
-
- /** PRIVATE / EXPERIMENTAL -- do not call
- Return the operations required to render the content inside 'queryRect'.
- */
- const OperationList* EXPERIMENTAL_getActiveOps(const SkIRect& queryRect) const;
-
- void createHeader(SkPictInfo* info) const;
static bool IsValidPictInfo(const SkPictInfo& info);
+ static SkPicture* Forwardport(const SkPictInfo&, const SkPictureData*);
- friend class SkPictureData; // to access OperationList
- friend class SkPictureRecorder; // just for SkPicture-based constructor
- friend class SkGpuDevice; // for EXPERIMENTAL_getActiveOps/OperationList
- friend class GrGatherCanvas; // needs to know if old or new picture
- friend class SkPicturePlayback; // to get fData & OperationList
- friend class SkPictureReplacementPlayback; // to access OperationList
+ SkPictInfo createHeader() const;
+ SkPictureData* backport() const;
- typedef SkRefCnt INHERITED;
-
- SkPicture(int width, int height, SkRecord*); // Takes ownership.
- SkAutoTDelete fRecord;
- bool fRecordWillPlayBackBitmaps; // TODO: const
+ mutable uint32_t fUniqueID;
};
#endif
diff --git a/gfx/skia/skia/include/core/SkPictureRecorder.h b/gfx/skia/skia/include/core/SkPictureRecorder.h
index bd22d55606..6f95860b70 100644
--- a/gfx/skia/skia/include/core/SkPictureRecorder.h
+++ b/gfx/skia/skia/include/core/SkPictureRecorder.h
@@ -8,6 +8,7 @@
#ifndef SkPictureRecorder_DEFINED
#define SkPictureRecorder_DEFINED
+#include "../private/SkMiniRecorder.h"
#include "SkBBHFactory.h"
#include "SkPicture.h"
#include "SkRefCnt.h"
@@ -19,6 +20,7 @@ namespace android {
#endif
class SkCanvas;
+class SkDrawable;
class SkPictureRecord;
class SkRecord;
class SkRecorder;
@@ -28,42 +30,75 @@ public:
SkPictureRecorder();
~SkPictureRecorder();
+ enum RecordFlags {
+ // This flag indicates that, if some BHH is being computed, saveLayer
+ // information should also be extracted at the same time.
+ kComputeSaveLayerInfo_RecordFlag = 0x01,
+
+ // If you call drawPicture() or drawDrawable() on the recording canvas, this flag forces
+ // that object to playback its contents immediately rather than reffing the object.
+ kPlaybackDrawPicture_RecordFlag = 0x02,
+ };
+
/** Returns the canvas that records the drawing commands.
- @param width the base width for the picture, as if the recording
- canvas' bitmap had this width.
- @param height the base width for the picture, as if the recording
- canvas' bitmap had this height.
+ @param bounds the cull rect used when recording this picture. Any drawing the falls outside
+ of this rect is undefined, and may be drawn or it may not.
@param bbhFactory factory to create desired acceleration structure
@param recordFlags optional flags that control recording.
@return the canvas.
*/
- SkCanvas* beginRecording(int width, int height,
+ SkCanvas* beginRecording(const SkRect& bounds,
SkBBHFactory* bbhFactory = NULL,
uint32_t recordFlags = 0);
- /** Same as beginRecording(), using a new faster backend. */
- SkCanvas* EXPERIMENTAL_beginRecording(int width, int height,
- SkBBHFactory* bbhFactory = NULL);
+ SkCanvas* beginRecording(SkScalar width, SkScalar height,
+ SkBBHFactory* bbhFactory = NULL,
+ uint32_t recordFlags = 0) {
+ return this->beginRecording(SkRect::MakeWH(width, height), bbhFactory, recordFlags);
+ }
/** Returns the recording canvas if one is active, or NULL if recording is
not active. This does not alter the refcnt on the canvas (if present).
*/
SkCanvas* getRecordingCanvas();
- /** Signal that the caller is done recording. This invalidates the canvas
- returned by beginRecording/getRecordingCanvas, and returns the
- created SkPicture. Note that the returned picture has its creation
- ref which the caller must take ownership of.
- */
- SkPicture* endRecording();
+ /**
+ * Signal that the caller is done recording. This invalidates the canvas returned by
+ * beginRecording/getRecordingCanvas. Ownership of the object is passed to the caller, who
+ * must call unref() when they are done using it.
+ *
+ * The returned picture is immutable. If during recording drawables were added to the canvas,
+ * these will have been "drawn" into a recording canvas, so that this resulting picture will
+ * reflect their current state, but will not contain a live reference to the drawables
+ * themselves.
+ */
+ SkPicture* SK_WARN_UNUSED_RESULT endRecordingAsPicture();
- /** Enable/disable all the picture recording optimizations (i.e.,
- those in SkPictureRecord). It is mainly intended for testing the
- existing optimizations (i.e., to actually have the pattern
- appear in an .skp we have to disable the optimization). Call right
- after 'beginRecording'.
- */
- void internalOnly_EnableOpts(bool enableOpts);
+ /**
+ * Signal that the caller is done recording, and update the cull rect to use for bounding
+ * box hierarchy (BBH) generation. The behavior is the same as calling
+ * endRecordingAsPicture(), except that this method updates the cull rect initially passed
+ * into beginRecording.
+ * @param cullRect the new culling rectangle to use as the overall bound for BBH generation
+ * and subsequent culling operations.
+ * @return the picture containing the recorded content.
+ */
+ SkPicture* SK_WARN_UNUSED_RESULT endRecordingAsPicture(const SkRect& cullRect);
+
+ /**
+ * Signal that the caller is done recording. This invalidates the canvas returned by
+ * beginRecording/getRecordingCanvas. Ownership of the object is passed to the caller, who
+ * must call unref() when they are done using it.
+ *
+ * Unlike endRecordingAsPicture(), which returns an immutable picture, the returned drawable
+ * may contain live references to other drawables (if they were added to the recording canvas)
+ * and therefore this drawable will reflect the current state of those nested drawables anytime
+ * it is drawn or a new picture is snapped from it (by calling drawable->newPictureSnapshot()).
+ */
+ SkDrawable* SK_WARN_UNUSED_RESULT endRecordingAsDrawable();
+
+ // Legacy API -- use endRecordingAsPicture instead.
+ SkPicture* SK_WARN_UNUSED_RESULT endRecording() { return this->endRecordingAsPicture(); }
private:
void reset();
@@ -77,15 +112,13 @@ private:
friend class SkPictureRecorderReplayTester; // for unit testing
void partialReplay(SkCanvas* canvas) const;
- int fWidth;
- int fHeight;
-
- // One of these two canvases will be non-NULL.
- SkAutoTUnref fPictureRecord; // beginRecording()
- SkAutoTUnref fRecorder; // EXPERIMENTAL_beginRecording()
-
- // Used by EXPERIMENTAL_beginRecording().
- SkAutoTDelete fRecord;
+ bool fActivelyRecording;
+ uint32_t fFlags;
+ SkRect fCullRect;
+ SkAutoTUnref fBBH;
+ SkAutoTUnref fRecorder;
+ SkAutoTUnref fRecord;
+ SkMiniRecorder fMiniRecorder;
typedef SkNoncopyable INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkPixelRef.h b/gfx/skia/skia/include/core/SkPixelRef.h
index afab7fad9e..4591ed82bf 100644
--- a/gfx/skia/skia/include/core/SkPixelRef.h
+++ b/gfx/skia/skia/include/core/SkPixelRef.h
@@ -8,36 +8,23 @@
#ifndef SkPixelRef_DEFINED
#define SkPixelRef_DEFINED
+#include "../private/SkAtomics.h"
#include "SkBitmap.h"
-#include "SkDynamicAnnotations.h"
-#include "SkRefCnt.h"
-#include "SkString.h"
+#include "SkFilterQuality.h"
#include "SkImageInfo.h"
+#include "../private/SkMutex.h"
+#include "SkPixmap.h"
+#include "SkRefCnt.h"
#include "SkSize.h"
+#include "SkString.h"
#include "SkTDArray.h"
-//#define xed
-
-#ifdef SK_DEBUG
- /**
- * Defining SK_IGNORE_PIXELREF_SETPRELOCKED will force all pixelref
- * subclasses to correctly handle lock/unlock pixels. For performance
- * reasons, simple malloc-based subclasses call setPreLocked() to skip
- * the overhead of implementing these calls.
- *
- * This build-flag disables that optimization, to add in debugging our
- * call-sites, to ensure that they correctly balance their calls of
- * lock and unlock.
- */
-// #define SK_IGNORE_PIXELREF_SETPRELOCKED
-#endif
-
class SkColorTable;
class SkData;
struct SkIRect;
-class SkMutex;
class GrTexture;
+class SkDiscardableMemory;
/** \class SkPixelRef
@@ -49,10 +36,7 @@ class GrTexture;
*/
class SK_API SkPixelRef : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkPixelRef)
-
explicit SkPixelRef(const SkImageInfo&);
- SkPixelRef(const SkImageInfo&, SkBaseMutex* mutex);
virtual ~SkPixelRef();
const SkImageInfo& info() const {
@@ -75,6 +59,8 @@ public:
* Calling lockPixels returns a LockRec struct (on success).
*/
struct LockRec {
+ LockRec() : fPixels(NULL), fColorTable(NULL) {}
+
void* fPixels;
SkColorTable* fColorTable;
size_t fRowBytes;
@@ -86,11 +72,7 @@ public:
}
};
- /**
- * Returns true if the lockcount > 0
- */
- bool isLocked() const { return fLockCount > 0; }
-
+ SkDEBUGCODE(bool isLocked() const { return fLockCount > 0; })
SkDEBUGCODE(int getLockCount() const { return fLockCount; })
/**
@@ -127,6 +109,18 @@ public:
*/
uint32_t getGenerationID() const;
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ /** Returns a non-zero, unique value corresponding to this SkPixelRef.
+ Unlike the generation ID, this ID remains the same even when the pixels
+ are changed. IDs are not reused (until uint32_t wraps), so it is safe
+ to consider this ID unique even after this SkPixelRef is deleted.
+
+ Can be used as a key which uniquely identifies this SkPixelRef
+ regardless of changes to its pixels or deletion of this object.
+ */
+ uint32_t getStableID() const { return fStableID; }
+#endif
+
/**
* Call this if you have changed the contents of the pixels. This will in-
* turn cause a different generation ID value to be returned from
@@ -144,7 +138,7 @@ public:
/** Returns true if this pixelref is marked as immutable, meaning that the
contents of its pixels will not change for the lifetime of the pixelref.
*/
- bool isImmutable() const { return fIsImmutable; }
+ bool isImmutable() const { return fMutability != kMutable; }
/** Marks this pixelref is immutable, meaning that the contents of its
pixels will not change for the lifetime of the pixelref. This state can
@@ -185,36 +179,31 @@ public:
return this->onRefEncodedData();
}
- /**
- * Experimental -- tells the caller if it is worth it to call decodeInto().
- * Just an optimization at this point, to avoid checking the cache first.
- * We may remove/change this call in the future.
- */
- bool implementsDecodeInto() {
- return this->onImplementsDecodeInto();
- }
+ struct LockRequest {
+ SkISize fSize;
+ SkFilterQuality fQuality;
+ };
- /**
- * Return a decoded instance of this pixelRef in bitmap. If this cannot be
- * done, return false and the bitmap parameter is ignored/unchanged.
- *
- * pow2 is the requeste power-of-two downscale that the caller needs. This
- * can be ignored, and the "original" size can be returned, but if the
- * underlying codec can efficiently return a smaller size, that should be
- * done. Some examples:
- *
- * To request the "base" version (original scale), pass 0 for pow2
- * To request 1/2 scale version (1/2 width, 1/2 height), pass 1 for pow2
- * To request 1/4 scale version (1/4 width, 1/4 height), pass 2 for pow2
- * ...
- *
- * If this returns true, then bitmap must be "locked" such that
- * bitmap->getPixels() will return the correct address.
- */
- bool decodeInto(int pow2, SkBitmap* bitmap) {
- SkASSERT(pow2 >= 0);
- return this->onDecodeInto(pow2, bitmap);
- }
+ struct LockResult {
+ LockResult() : fPixels(NULL), fCTable(NULL) {}
+
+ void (*fUnlockProc)(void* ctx);
+ void* fUnlockContext;
+
+ const void* fPixels;
+ SkColorTable* fCTable; // should be NULL unless colortype is kIndex8
+ size_t fRowBytes;
+ SkISize fSize;
+
+ void unlock() {
+ if (fUnlockProc) {
+ fUnlockProc(fUnlockContext);
+ fUnlockProc = NULL; // can't unlock twice!
+ }
+ }
+ };
+
+ bool requestLock(const LockRequest&, LockResult*);
/** Are we really wrapping a texture instead of a bitmap?
*/
@@ -227,9 +216,13 @@ public:
* If all planes and rowBytes are not NULL, then it should copy the associated Y,U,V data
* into those planes of memory supplied by the caller. It should validate that the sizes
* match what it expected. If the sizes do not match, it should return false.
+ *
+ * If colorSpace is not NULL, the YUV color space of the data should be stored in the address
+ * it points at.
*/
- bool getYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3]) {
- return this->onGetYUV8Planes(sizes, planes, rowBytes);
+ bool getYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],
+ SkYUVColorSpace* colorSpace) {
+ return this->onGetYUV8Planes(sizes, planes, rowBytes, colorSpace);
}
bool readPixels(SkBitmap* dst, const SkIRect* subset = NULL);
@@ -237,32 +230,17 @@ public:
/**
* Makes a deep copy of this PixelRef, respecting the requested config.
* @param colorType Desired colortype.
+ * @param profileType Desired colorprofiletype.
* @param subset Subset of this PixelRef to copy. Must be fully contained within the bounds of
* of this PixelRef.
* @return A new SkPixelRef, or NULL if either there is an error (e.g. the destination could
* not be created with the given config), or this PixelRef does not support deep
* copies.
*/
- virtual SkPixelRef* deepCopy(SkColorType colortype, const SkIRect* subset) {
+ virtual SkPixelRef* deepCopy(SkColorType, SkColorProfileType, const SkIRect* /*subset*/) {
return NULL;
}
-#ifdef SK_BUILD_FOR_ANDROID
- /**
- * Acquire a "global" ref on this object.
- * The default implementation just calls ref(), but subclasses can override
- * this method to implement additional behavior.
- */
- virtual void globalRef(void* data=NULL);
-
- /**
- * Release a "global" ref on this object.
- * The default implementation just calls unref(), but subclasses can override
- * this method to implement additional behavior.
- */
- virtual void globalUnref();
-#endif
-
// Register a listener that may be called the next time our generation ID changes.
//
// We'll only call the listener if we're confident that we are the only SkPixelRef with this
@@ -279,6 +257,19 @@ public:
// Takes ownership of listener.
void addGenIDChangeListener(GenIDChangeListener* listener);
+ // Call when this pixelref is part of the key to a resourcecache entry. This allows the cache
+ // to know automatically those entries can be purged when this pixelref is changed or deleted.
+ void notifyAddedToCache() {
+ fAddedToCache.store(true);
+ }
+
+ virtual SkDiscardableMemory* diagnostic_only_getDiscardable() const { return NULL; }
+
+ /**
+ * Returns true if the pixels are generated on-the-fly (when required).
+ */
+ bool isLazyGenerated() const { return this->onIsLazyGenerated(); }
+
protected:
/**
* On success, returns true and fills out the LockRec for the pixels. On
@@ -302,11 +293,6 @@ protected:
/** Default impl returns true */
virtual bool onLockPixelsAreWritable() const;
- // returns false;
- virtual bool onImplementsDecodeInto();
- // returns false;
- virtual bool onDecodeInto(int pow2, SkBitmap* bitmap);
-
/**
* For pixelrefs that don't have access to their raw pixels, they may be
* able to make a copy of them (e.g. if the pixels are on the GPU).
@@ -318,8 +304,12 @@ protected:
// default impl returns NULL.
virtual SkData* onRefEncodedData();
+ // default impl does nothing.
+ virtual void onNotifyPixelsChanged();
+
// default impl returns false.
- virtual bool onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3]);
+ virtual bool onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],
+ SkYUVColorSpace* colorSpace);
/**
* Returns the size (in bytes) of the internally allocated memory.
@@ -331,10 +321,14 @@ protected:
*/
virtual size_t getAllocatedSizeInBytes() const;
+ virtual bool onRequestLock(const LockRequest&, LockResult*);
+
+ virtual bool onIsLazyGenerated() const { return false; }
+
/** Return the mutex associated with this pixelref. This value is assigned
in the constructor, and cannot change during the lifetime of the object.
*/
- SkBaseMutex* mutex() const { return fMutex; }
+ SkBaseMutex* mutex() const { return &fMutex; }
// only call from constructor. Flags this to always be locked, removing
// the need to grab the mutex and call onLockPixels/onUnlockPixels.
@@ -342,7 +336,7 @@ protected:
void setPreLocked(void*, size_t rowBytes, SkColorTable*);
private:
- SkBaseMutex* fMutex; // must remain in scope for the life of this object
+ mutable SkMutex fMutex;
// mostly const. fInfo.fAlpahType can be changed at runtime.
const SkImageInfo fInfo;
@@ -351,28 +345,51 @@ private:
LockRec fRec;
int fLockCount;
- mutable SkTRacy fGenerationID;
- mutable SkTRacy fUniqueGenerationID;
+ bool lockPixelsInsideMutex();
+
+ // Bottom bit indicates the Gen ID is unique.
+ bool genIDIsUnique() const { return SkToBool(fTaggedGenID.load() & 1); }
+ mutable SkAtomic fTaggedGenID;
+
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ const uint32_t fStableID;
+#endif
SkTDArray fGenIDChangeListeners; // pointers are owned
SkString fURI;
- // can go from false to true, but never from true to false
- bool fIsImmutable;
+ // Set true by caches when they cache content that's derived from the current pixels.
+ SkAtomic fAddedToCache;
+
+ enum {
+ kMutable, // PixelRefs begin mutable.
+ kTemporarilyImmutable, // Considered immutable, but can revert to mutable.
+ kImmutable, // Once set to this state, it never leaves.
+ } fMutability : 8; // easily fits inside a byte
+
// only ever set in constructor, const after that
- bool fPreLocked;
+ bool fPreLocked;
void needsNewGenID();
void callGenIDChangeListeners();
- void setMutex(SkBaseMutex* mutex);
+ void setTemporarilyImmutable();
+ void restoreMutability();
+ friend class SkSurface_Raster; // For the two methods above.
+
+ bool isPreLocked() const { return fPreLocked; }
+ friend class SkImage_Raster;
// When copying a bitmap to another with the same shape and config, we can safely
// clone the pixelref generation ID too, which makes them equivalent under caching.
friend class SkBitmap; // only for cloneGenID
void cloneGenID(const SkPixelRef&);
+ void setImmutableWithID(uint32_t genID);
+ friend class SkImage_Gpu;
+ friend class SkImageCacherator;
+
typedef SkRefCnt INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkPixelSerializer.h b/gfx/skia/skia/include/core/SkPixelSerializer.h
new file mode 100644
index 0000000000..d089209909
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkPixelSerializer.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkPixelSerializer_DEFINED
+#define SkPixelSerializer_DEFINED
+
+#include "SkRefCnt.h"
+
+class SkData;
+struct SkImageInfo;
+
+/**
+ * Interface for serializing pixels, e.g. SkBitmaps in an SkPicture.
+ */
+class SkPixelSerializer : public SkRefCnt {
+public:
+ virtual ~SkPixelSerializer() {}
+
+ /**
+ * Call to determine if the client wants to serialize the encoded data. If
+ * false, serialize another version (e.g. the result of encodePixels).
+ */
+ bool useEncodedData(const void* data, size_t len) {
+ return this->onUseEncodedData(data, len);
+ }
+
+ /**
+ * Call to get the client's version of encoding these pixels. If it
+ * returns NULL, serialize the raw pixels.
+ */
+ SkData* encodePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes) {
+ return this->onEncodePixels(info, pixels, rowBytes);
+ }
+
+protected:
+ /**
+ * Return true if you want to serialize the encoded data, false if you want
+ * another version serialized (e.g. the result of encodePixels).
+ */
+ virtual bool onUseEncodedData(const void* data, size_t len) = 0;
+
+ /**
+ * If you want to encode these pixels, return the encoded data as an SkData
+ * Return null if you want to serialize the raw pixels.
+ */
+ virtual SkData* onEncodePixels(const SkImageInfo&, const void* pixels, size_t rowBytes) = 0;
+};
+#endif // SkPixelSerializer_DEFINED
diff --git a/gfx/skia/skia/include/core/SkPixmap.h b/gfx/skia/skia/include/core/SkPixmap.h
new file mode 100644
index 0000000000..da97025cab
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkPixmap.h
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkPixmap_DEFINED
+#define SkPixmap_DEFINED
+
+#include "SkColor.h"
+#include "SkFilterQuality.h"
+#include "SkImageInfo.h"
+
+class SkColorTable;
+struct SkMask;
+
+/**
+ * Pairs SkImageInfo with actual pixels and rowbytes. This class does not try to manage the
+ * lifetime of the pixel memory (nor the colortable if provided).
+ */
+class SK_API SkPixmap {
+public:
+ SkPixmap()
+ : fPixels(NULL), fCTable(NULL), fRowBytes(0), fInfo(SkImageInfo::MakeUnknown(0, 0))
+ {}
+
+ SkPixmap(const SkImageInfo& info, const void* addr, size_t rowBytes,
+ SkColorTable* ctable = NULL)
+ : fPixels(addr), fCTable(ctable), fRowBytes(rowBytes), fInfo(info)
+ {
+ if (kIndex_8_SkColorType == info.colorType()) {
+ SkASSERT(ctable);
+ } else {
+ SkASSERT(NULL == ctable);
+ }
+ }
+
+ void reset();
+ void reset(const SkImageInfo& info, const void* addr, size_t rowBytes,
+ SkColorTable* ctable = NULL);
+ void reset(const SkImageInfo& info) {
+ this->reset(info, NULL, 0, NULL);
+ }
+
+ /**
+ * If supported, set this pixmap to point to the pixels in the specified mask and return true.
+ * On failure, return false and set this pixmap to empty.
+ */
+ bool SK_WARN_UNUSED_RESULT reset(const SkMask&);
+
+ /**
+ * Computes the intersection of area and this pixmap. If that intersection is non-empty,
+ * set subset to that intersection and return true.
+ *
+ * On failure, return false and ignore the subset parameter.
+ */
+ bool SK_WARN_UNUSED_RESULT extractSubset(SkPixmap* subset, const SkIRect& area) const;
+
+ const SkImageInfo& info() const { return fInfo; }
+ size_t rowBytes() const { return fRowBytes; }
+ const void* addr() const { return fPixels; }
+ SkColorTable* ctable() const { return fCTable; }
+
+ int width() const { return fInfo.width(); }
+ int height() const { return fInfo.height(); }
+ SkColorType colorType() const { return fInfo.colorType(); }
+ SkAlphaType alphaType() const { return fInfo.alphaType(); }
+ bool isOpaque() const { return fInfo.isOpaque(); }
+
+ SkIRect bounds() const { return SkIRect::MakeWH(this->width(), this->height()); }
+
+ uint64_t getSize64() const { return sk_64_mul(fInfo.height(), fRowBytes); }
+ uint64_t getSafeSize64() const { return fInfo.getSafeSize64(fRowBytes); }
+ size_t getSafeSize() const { return fInfo.getSafeSize(fRowBytes); }
+
+ const uint32_t* addr32() const {
+ SkASSERT(4 == SkColorTypeBytesPerPixel(fInfo.colorType()));
+ return reinterpret_cast(fPixels);
+ }
+
+ const uint16_t* addr16() const {
+ SkASSERT(2 == SkColorTypeBytesPerPixel(fInfo.colorType()));
+ return reinterpret_cast(fPixels);
+ }
+
+ const uint8_t* addr8() const {
+ SkASSERT(1 == SkColorTypeBytesPerPixel(fInfo.colorType()));
+ return reinterpret_cast(fPixels);
+ }
+
+ const uint32_t* addr32(int x, int y) const {
+ SkASSERT((unsigned)x < (unsigned)fInfo.width());
+ SkASSERT((unsigned)y < (unsigned)fInfo.height());
+ return (const uint32_t*)((const char*)this->addr32() + y * fRowBytes + (x << 2));
+ }
+ const uint16_t* addr16(int x, int y) const {
+ SkASSERT((unsigned)x < (unsigned)fInfo.width());
+ SkASSERT((unsigned)y < (unsigned)fInfo.height());
+ return (const uint16_t*)((const char*)this->addr16() + y * fRowBytes + (x << 1));
+ }
+ const uint8_t* addr8(int x, int y) const {
+ SkASSERT((unsigned)x < (unsigned)fInfo.width());
+ SkASSERT((unsigned)y < (unsigned)fInfo.height());
+ return (const uint8_t*)((const char*)this->addr8() + y * fRowBytes + (x << 0));
+ }
+ const void* addr(int x, int y) const {
+ return (const char*)fPixels + fInfo.computeOffset(x, y, fRowBytes);
+ }
+
+ // Writable versions
+
+ void* writable_addr() const { return const_cast(fPixels); }
+ uint32_t* writable_addr32(int x, int y) const {
+ return const_cast(this->addr32(x, y));
+ }
+ uint16_t* writable_addr16(int x, int y) const {
+ return const_cast(this->addr16(x, y));
+ }
+ uint8_t* writable_addr8(int x, int y) const {
+ return const_cast(this->addr8(x, y));
+ }
+
+ // copy methods
+
+ bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
+ int srcX, int srcY) const;
+ bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes) const {
+ return this->readPixels(dstInfo, dstPixels, dstRowBytes, 0, 0);
+ }
+ bool readPixels(const SkPixmap& dst, int srcX, int srcY) const {
+ return this->readPixels(dst.info(), dst.writable_addr(), dst.rowBytes(), srcX, srcY);
+ }
+ bool readPixels(const SkPixmap& dst) const {
+ return this->readPixels(dst.info(), dst.writable_addr(), dst.rowBytes(), 0, 0);
+ }
+
+ /**
+ * Copy the pixels from this pixmap into the dst pixmap, converting as needed into dst's
+ * colortype/alphatype. If the conversion cannot be performed, false is returned.
+ *
+ * If dst's dimensions differ from the src dimension, the image will be scaled, applying the
+ * specified filter-quality.
+ */
+ bool scalePixels(const SkPixmap& dst, SkFilterQuality) const;
+
+ /**
+ * Returns true if pixels were written to (e.g. if colorType is kUnknown_SkColorType, this
+ * will return false). If subset does not intersect the bounds of this pixmap, returns false.
+ */
+ bool erase(SkColor, const SkIRect& subset) const;
+
+ bool erase(SkColor color) const { return this->erase(color, this->bounds()); }
+
+private:
+ const void* fPixels;
+ SkColorTable* fCTable;
+ size_t fRowBytes;
+ SkImageInfo fInfo;
+};
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+
+class SK_API SkAutoPixmapStorage : public SkPixmap {
+public:
+ SkAutoPixmapStorage();
+ ~SkAutoPixmapStorage();
+
+ /**
+ * Try to allocate memory for the pixels needed to match the specified Info. On success
+ * return true and fill out the pixmap to point to that memory. The storage will be freed
+ * when this object is destroyed, or if another call to tryAlloc() or alloc() is made.
+ *
+ * On failure, return false and reset() the pixmap to empty.
+ */
+ bool tryAlloc(const SkImageInfo&);
+
+ /**
+ * Allocate memory for the pixels needed to match the specified Info and fill out the pixmap
+ * to point to that memory. The storage will be freed when this object is destroyed,
+ * or if another call to tryAlloc() or alloc() is made.
+ *
+ * If the memory cannot be allocated, calls sk_throw().
+ */
+ void alloc(const SkImageInfo&);
+
+ // We wrap these so we can clear our internal storage
+
+ void reset() {
+ this->freeStorage();
+ this->INHERITED::reset();
+ }
+ void reset(const SkImageInfo& info, const void* addr, size_t rb, SkColorTable* ctable = NULL) {
+ this->freeStorage();
+ this->INHERITED::reset(info, addr, rb, ctable);
+ }
+ void reset(const SkImageInfo& info) {
+ this->freeStorage();
+ this->INHERITED::reset(info);
+ }
+ bool SK_WARN_UNUSED_RESULT reset(const SkMask& mask) {
+ this->freeStorage();
+ return this->INHERITED::reset(mask);
+ }
+
+private:
+ void* fStorage;
+
+ void freeStorage() {
+ sk_free(fStorage);
+ fStorage = NULL;
+ }
+
+ typedef SkPixmap INHERITED;
+};
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+
+class SK_API SkAutoPixmapUnlock : ::SkNoncopyable {
+public:
+ SkAutoPixmapUnlock() : fUnlockProc(NULL), fIsLocked(false) {}
+ SkAutoPixmapUnlock(const SkPixmap& pm, void (*unlock)(void*), void* ctx)
+ : fUnlockProc(unlock), fUnlockContext(ctx), fPixmap(pm), fIsLocked(true)
+ {}
+ ~SkAutoPixmapUnlock() { this->unlock(); }
+
+ /**
+ * Return the currently locked pixmap. Undefined if it has been unlocked.
+ */
+ const SkPixmap& pixmap() const {
+ SkASSERT(this->isLocked());
+ return fPixmap;
+ }
+
+ bool isLocked() const { return fIsLocked; }
+
+ /**
+ * Unlocks the pixmap. Can safely be called more than once as it will only call the underlying
+ * unlock-proc once.
+ */
+ void unlock() {
+ if (fUnlockProc) {
+ SkASSERT(fIsLocked);
+ fUnlockProc(fUnlockContext);
+ fUnlockProc = NULL;
+ fIsLocked = false;
+ }
+ }
+
+ /**
+ * If there is a currently locked pixmap, unlock it, then copy the specified pixmap
+ * and (optional) unlock proc/context.
+ */
+ void reset(const SkPixmap& pm, void (*unlock)(void*), void* ctx);
+
+private:
+ void (*fUnlockProc)(void*);
+ void* fUnlockContext;
+ SkPixmap fPixmap;
+ bool fIsLocked;
+
+ friend class SkBitmap;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkPngChunkReader.h b/gfx/skia/skia/include/core/SkPngChunkReader.h
new file mode 100644
index 0000000000..f424dd8cfc
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkPngChunkReader.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkPngChunkReader_DEFINED
+#define SkPngChunkReader_DEFINED
+
+#include "SkTypes.h"
+#include "SkRefCnt.h"
+
+/**
+ * SkPngChunkReader
+ *
+ * Base class for optional callbacks to retrieve meta/chunk data out of a PNG
+ * encoded image as it is being decoded.
+ * Used by SkImageDecoder and SkCodec.
+ */
+class SkPngChunkReader : public SkRefCnt {
+public:
+ /**
+ * This will be called by the decoder when it sees an unknown chunk.
+ *
+ * Use by SkCodec:
+ * Depending on the location of the unknown chunks, this callback may be
+ * called by
+ * - the factory (NewFromStream/NewFromData)
+ * - getPixels
+ * - startScanlineDecode
+ * - the first call to getScanlines/skipScanlines
+ * The callback may be called from a different thread (e.g. if the SkCodec
+ * is passed to another thread), and it may be called multiple times, if
+ * the SkCodec is used multiple times.
+ *
+ * @param tag Name for this type of chunk.
+ * @param data Data to be interpreted by the subclass.
+ * @param length Number of bytes of data in the chunk.
+ * @return true to continue decoding, or false to indicate an error, which
+ * will cause the decoder to not return the image.
+ */
+ virtual bool readChunk(const char tag[], const void* data, size_t length) = 0;
+};
+#endif // SkPngChunkReader_DEFINED
diff --git a/gfx/skia/skia/include/core/SkPoint.h b/gfx/skia/skia/include/core/SkPoint.h
index 8a0480ae73..52d01ae88c 100644
--- a/gfx/skia/skia/include/core/SkPoint.h
+++ b/gfx/skia/skia/include/core/SkPoint.h
@@ -212,7 +212,16 @@ struct SK_API SkPoint {
v[2].set(r, b);
v[3].set(r, t);
}
- void setRectFan(SkScalar l, SkScalar t, SkScalar r, SkScalar b, size_t stride);
+
+ void setRectFan(SkScalar l, SkScalar t, SkScalar r, SkScalar b, size_t stride) {
+ SkASSERT(stride >= sizeof(SkPoint));
+
+ ((SkPoint*)((intptr_t)this + 0 * stride))->set(l, t);
+ ((SkPoint*)((intptr_t)this + 1 * stride))->set(l, b);
+ ((SkPoint*)((intptr_t)this + 2 * stride))->set(r, b);
+ ((SkPoint*)((intptr_t)this + 3 * stride))->set(r, t);
+ }
+
static void Offset(SkPoint points[], int count, const SkPoint& offset) {
Offset(points, count, offset.fX, offset.fY);
@@ -249,25 +258,25 @@ struct SK_API SkPoint {
/** Set the point (vector) to be unit-length in the same direction as it
already points. If the point has a degenerate length (i.e. nearly 0)
- then return false and do nothing; otherwise return true.
+ then set it to (0,0) and return false; otherwise return true.
*/
bool normalize();
/** Set the point (vector) to be unit-length in the same direction as the
x,y params. If the vector (x,y) has a degenerate length (i.e. nearly 0)
- then return false and do nothing, otherwise return true.
+ then set it to (0,0) and return false, otherwise return true.
*/
bool setNormalize(SkScalar x, SkScalar y);
/** Scale the point (vector) to have the specified length, and return that
length. If the original length is degenerately small (nearly zero),
- do nothing and return false, otherwise return true.
+ set it to (0,0) and return false, otherwise return true.
*/
bool setLength(SkScalar length);
/** Set the point (vector) to have the specified length in the same
direction as (x,y). If the vector (x,y) has a degenerate length
- (i.e. nearly 0) then return false and do nothing, otherwise return true.
+ (i.e. nearly 0) then set it to (0,0) and return false, otherwise return true.
*/
bool setLength(SkScalar x, SkScalar y, SkScalar length);
@@ -339,6 +348,16 @@ struct SK_API SkPoint {
fY -= v.fY;
}
+ SkPoint operator*(SkScalar scale) const {
+ return Make(fX * scale, fY * scale);
+ }
+
+ SkPoint& operator*=(SkScalar scale) {
+ fX *= scale;
+ fY *= scale;
+ return *this;
+ }
+
/**
* Returns true if both X and Y are finite (not infinity or NaN)
*/
@@ -414,7 +433,7 @@ struct SK_API SkPoint {
static SkScalar Length(SkScalar x, SkScalar y);
/** Normalize pt, returning its previous length. If the prev length is too
- small (degenerate), return 0 and leave pt unchanged. This uses the same
+ small (degenerate), set pt to (0,0) and return 0. This uses the same
tolerance as CanNormalize.
Note that this method may be significantly more expensive than
diff --git a/gfx/skia/skia/include/core/SkPoint3.h b/gfx/skia/skia/include/core/SkPoint3.h
new file mode 100644
index 0000000000..af24a8df58
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkPoint3.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkPoint3_DEFINED
+#define SkPoint3_DEFINED
+
+#include "SkScalar.h"
+
+struct SK_API SkPoint3 {
+ SkScalar fX, fY, fZ;
+
+ static SkPoint3 Make(SkScalar x, SkScalar y, SkScalar z) {
+ SkPoint3 pt;
+ pt.set(x, y, z);
+ return pt;
+ }
+
+ SkScalar x() const { return fX; }
+ SkScalar y() const { return fY; }
+ SkScalar z() const { return fZ; }
+
+ void set(SkScalar x, SkScalar y, SkScalar z) { fX = x; fY = y; fZ = z; }
+
+ friend bool operator==(const SkPoint3& a, const SkPoint3& b) {
+ return a.fX == b.fX && a.fY == b.fY && a.fZ == b.fZ;
+ }
+
+ friend bool operator!=(const SkPoint3& a, const SkPoint3& b) {
+ return !(a == b);
+ }
+
+ /** Returns the Euclidian distance from (0,0,0) to (x,y,z)
+ */
+ static SkScalar Length(SkScalar x, SkScalar y, SkScalar z);
+
+ /** Return the Euclidian distance from (0,0,0) to the point
+ */
+ SkScalar length() const { return SkPoint3::Length(fX, fY, fZ); }
+
+ /** Set the point (vector) to be unit-length in the same direction as it
+ already points. If the point has a degenerate length (i.e., nearly 0)
+ then set it to (0,0,0) and return false; otherwise return true.
+ */
+ bool normalize();
+
+ /** Return a new point whose X, Y and Z coordinates are scaled.
+ */
+ SkPoint3 makeScale(SkScalar scale) const {
+ SkPoint3 p;
+ p.set(scale * fX, scale * fY, scale * fZ);
+ return p;
+ }
+
+ /** Scale the point's coordinates by scale.
+ */
+ void scale(SkScalar value) {
+ fX *= value;
+ fY *= value;
+ fZ *= value;
+ }
+
+ /** Return a new point whose X, Y and Z coordinates are the negative of the
+ original point's
+ */
+ SkPoint3 operator-() const {
+ SkPoint3 neg;
+ neg.fX = -fX;
+ neg.fY = -fY;
+ neg.fZ = -fZ;
+ return neg;
+ }
+
+ /** Returns a new point whose coordinates are the difference between
+ a and b (i.e., a - b)
+ */
+ friend SkPoint3 operator-(const SkPoint3& a, const SkPoint3& b) {
+ SkPoint3 v;
+ v.set(a.fX - b.fX, a.fY - b.fY, a.fZ - b.fZ);
+ return v;
+ }
+
+ /** Returns a new point whose coordinates are the sum of a and b (a + b)
+ */
+ friend SkPoint3 operator+(const SkPoint3& a, const SkPoint3& b) {
+ SkPoint3 v;
+ v.set(a.fX + b.fX, a.fY + b.fY, a.fZ + b.fZ);
+ return v;
+ }
+
+ /** Add v's coordinates to the point's
+ */
+ void operator+=(const SkPoint3& v) {
+ fX += v.fX;
+ fY += v.fY;
+ fZ += v.fZ;
+ }
+
+ /** Subtract v's coordinates from the point's
+ */
+ void operator-=(const SkPoint3& v) {
+ fX -= v.fX;
+ fY -= v.fY;
+ fZ -= v.fZ;
+ }
+
+ /** Returns the dot product of a and b, treating them as 3D vectors
+ */
+ static SkScalar DotProduct(const SkPoint3& a, const SkPoint3& b) {
+ return a.fX * b.fX + a.fY * b.fY + a.fZ * b.fZ;
+ }
+
+ SkScalar dot(const SkPoint3& vec) const {
+ return DotProduct(*this, vec);
+ }
+};
+
+typedef SkPoint3 SkVector3;
+typedef SkPoint3 SkColor3f;
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkPostConfig.h b/gfx/skia/skia/include/core/SkPostConfig.h
index d513d20633..d23eddf2e6 100644
--- a/gfx/skia/skia/include/core/SkPostConfig.h
+++ b/gfx/skia/skia/include/core/SkPostConfig.h
@@ -5,10 +5,12 @@
* found in the LICENSE file.
*/
+// IWYU pragma: private, include "SkTypes.h"
+
#ifndef SkPostConfig_DEFINED
#define SkPostConfig_DEFINED
-#if defined(SK_BUILD_FOR_WIN32) || defined(SK_BUILD_FOR_WINCE)
+#if defined(SK_BUILD_FOR_WIN32)
# define SK_BUILD_FOR_WIN
#endif
@@ -24,13 +26,12 @@
/**
* Matrix calculations may be float or double.
- * The default is double, as that is faster given our impl uses doubles
- * for intermediate calculations.
+ * The default is float, as that's what Chromium's using.
*/
#if defined(SK_MSCALAR_IS_DOUBLE) && defined(SK_MSCALAR_IS_FLOAT)
# error "cannot define both SK_MSCALAR_IS_DOUBLE and SK_MSCALAR_IS_FLOAT"
#elif !defined(SK_MSCALAR_IS_DOUBLE) && !defined(SK_MSCALAR_IS_FLOAT)
-# define SK_MSCALAR_IS_DOUBLE
+# define SK_MSCALAR_IS_FLOAT
#endif
#if defined(SK_CPU_LENDIAN) && defined(SK_CPU_BENDIAN)
@@ -68,6 +69,15 @@
# endif
#endif
+// As usual, there are two ways to increase alignment... the MSVC way and the everyone-else way.
+#ifndef SK_STRUCT_ALIGN
+ #ifdef _MSC_VER
+ #define SK_STRUCT_ALIGN(N) __declspec(align(N))
+ #else
+ #define SK_STRUCT_ALIGN(N) __attribute__((aligned(N)))
+ #endif
+#endif
+
#if !defined(SK_SUPPORT_GPU)
# define SK_SUPPORT_GPU 1
#endif
@@ -88,23 +98,10 @@
# endif
#endif
-#if defined(SK_ZLIB_INCLUDE) && defined(SK_SYSTEM_ZLIB)
-# error "cannot define both SK_ZLIB_INCLUDE and SK_SYSTEM_ZLIB"
-#elif defined(SK_ZLIB_INCLUDE) || defined(SK_SYSTEM_ZLIB)
-# define SK_HAS_ZLIB
-#endif
-
///////////////////////////////////////////////////////////////////////////////
-#ifndef SkNEW
-# define SkNEW(type_name) (new type_name)
-# define SkNEW_ARGS(type_name, args) (new type_name args)
-# define SkNEW_ARRAY(type_name, count) (new type_name[(count)])
-# define SkNEW_PLACEMENT(buf, type_name) (new (buf) type_name)
-# define SkNEW_PLACEMENT_ARGS(buf, type_name, args) (new (buf) type_name args)
-# define SkDELETE(obj) (delete (obj))
-# define SkDELETE_ARRAY(array) (delete[] (array))
-#endif
+// TODO(mdempsky): Move elsewhere as appropriate.
+#include
#ifndef SK_CRASH
# ifdef SK_BUILD_FOR_WIN
@@ -120,23 +117,6 @@
///////////////////////////////////////////////////////////////////////////////
-/**
- * SK_ENABLE_INST_COUNT controlls printing how many reference counted objects
- * are still held on exit.
- * Defaults to 1 in DEBUG and 0 in RELEASE.
- */
-#ifndef SK_ENABLE_INST_COUNT
-# ifdef SK_DEBUG
-// Only enabled for static builds, because instance counting relies on static
-// variables in functions defined in header files.
-# define SK_ENABLE_INST_COUNT !defined(SKIA_DLL)
-# else
-# define SK_ENABLE_INST_COUNT 0
-# endif
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-
#ifdef SK_BUILD_FOR_WIN
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
@@ -167,8 +147,23 @@
#
#endif
+#if defined(GOOGLE3)
+ // Used as argument to DumpStackTrace in SK_ALWAYSBREAK.
+ void SkDebugfForDumpStackTrace(const char* data, void* unused);
+#endif
+
#ifndef SK_ALWAYSBREAK
-# ifdef SK_DEBUG
+# if defined(GOOGLE3)
+ void DumpStackTrace(int skip_count, void w(const char*, void*),
+ void* arg);
+# define SK_ALWAYSBREAK(cond) do { \
+ if (cond) break; \
+ SkNO_RETURN_HINT(); \
+ SkDebugf("%s:%d: failed assertion \"%s\"\n", __FILE__, __LINE__, #cond); \
+ DumpStackTrace(0, SkDebugfForDumpStackTrace, nullptr); \
+ SK_CRASH(); \
+ } while (false)
+# elif defined(SK_DEBUG)
# define SK_ALWAYSBREAK(cond) do { \
if (cond) break; \
SkNO_RETURN_HINT(); \
@@ -229,26 +224,7 @@
SK_ ## C3 ## 32_SHIFT == 24)
#endif
-//////////////////////////////////////////////////////////////////////
-
-// TODO: rebaseline as needed so we can remove this flag entirely.
-// - all platforms have int64_t now
-// - we have slightly different fixed math results because of this check
-// since we don't define this for linux/android
-#if defined(SK_BUILD_FOR_WIN32) || defined(SK_BUILD_FOR_MAC)
-# ifndef SkLONGLONG
-# define SkLONGLONG int64_t
-# endif
-#endif
-
//////////////////////////////////////////////////////////////////////////////////////////////
-#ifndef SK_BUILD_FOR_WINCE
-# include
-# include
-#else
-# define _CMNINTRIN_DECLARE_ONLY
-# include "cmnintrin.h"
-#endif
#if defined SK_DEBUG && defined SK_BUILD_FOR_WIN32
# ifdef free
@@ -293,29 +269,6 @@
//////////////////////////////////////////////////////////////////////
-#ifndef SK_OVERRIDE
-# if defined(_MSC_VER)
-# define SK_OVERRIDE override
-# elif defined(__clang__)
- // Using __attribute__((override)) on clang does not appear to always work.
- // Clang defaults to C++03 and warns about using override. Squelch that. Intentionally no
- // push/pop here so all users of SK_OVERRIDE ignore the warning too. This is like passing
- // -Wno-c++11-extensions, except that GCC won't die (because it won't see this pragma).
-# pragma clang diagnostic ignored "-Wc++11-extensions"
-#
-# if __has_feature(cxx_override_control)
-# define SK_OVERRIDE override
-# elif defined(__has_extension) && __has_extension(cxx_override_control)
-# define SK_OVERRIDE override
-# endif
-# endif
-# ifndef SK_OVERRIDE
-# define SK_OVERRIDE
-# endif
-#endif
-
-//////////////////////////////////////////////////////////////////////
-
#if !defined(SK_UNUSED)
# define SK_UNUSED SK_ATTRIBUTE(unused)
#endif
@@ -347,14 +300,25 @@
# endif
#endif
+#if defined(SK_BUILD_FOR_WIN) && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
+ #define SK_VECTORCALL __vectorcall
+#elif defined(SK_CPU_ARM32)
+ #define SK_VECTORCALL __attribute__((pcs("aapcs-vfp")))
+#else
+ #define SK_VECTORCALL
+#endif
+
//////////////////////////////////////////////////////////////////////
-#if defined(__clang__) || defined(__GNUC__)
-# define SK_PREFETCH(ptr) __builtin_prefetch(ptr)
-# define SK_WRITE_PREFETCH(ptr) __builtin_prefetch(ptr, 1)
+#if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
+ #define SK_PREFETCH(ptr) _mm_prefetch(reinterpret_cast(ptr), _MM_HINT_T0)
+ #define SK_WRITE_PREFETCH(ptr) _mm_prefetch(reinterpret_cast(ptr), _MM_HINT_T0)
+#elif defined(__GNUC__)
+ #define SK_PREFETCH(ptr) __builtin_prefetch(ptr)
+ #define SK_WRITE_PREFETCH(ptr) __builtin_prefetch(ptr, 1)
#else
-# define SK_PREFETCH(ptr)
-# define SK_WRITE_PREFETCH(ptr)
+ #define SK_PREFETCH(ptr)
+ #define SK_WRITE_PREFETCH(ptr)
#endif
//////////////////////////////////////////////////////////////////////
@@ -385,33 +349,14 @@
//////////////////////////////////////////////////////////////////////
-#ifndef SK_ATOMICS_PLATFORM_H
-# if defined(_MSC_VER)
-# define SK_ATOMICS_PLATFORM_H "../../src/ports/SkAtomics_win.h"
+#ifndef SK_EGL
+# if defined(SK_BUILD_FOR_ANDROID)
+# define SK_EGL 1
# else
-# define SK_ATOMICS_PLATFORM_H "../../src/ports/SkAtomics_sync.h"
+# define SK_EGL 0
# endif
#endif
-#ifndef SK_MUTEX_PLATFORM_H
-# if defined(SK_BUILD_FOR_WIN)
-# define SK_MUTEX_PLATFORM_H "../../src/ports/SkMutex_win.h"
-# else
-# define SK_MUTEX_PLATFORM_H "../../src/ports/SkMutex_pthread.h"
-# endif
-#endif
-
-#ifndef SK_BARRIERS_PLATFORM_H
-# if SK_HAS_COMPILER_FEATURE(thread_sanitizer)
-# define SK_BARRIERS_PLATFORM_H "../../src/ports/SkBarriers_tsan.h"
-# elif defined(SK_CPU_ARM32) || defined(SK_CPU_ARM64)
-# define SK_BARRIERS_PLATFORM_H "../../src/ports/SkBarriers_arm.h"
-# else
-# define SK_BARRIERS_PLATFORM_H "../../src/ports/SkBarriers_x86.h"
-# endif
-#endif
-
-
//////////////////////////////////////////////////////////////////////
#if defined(SK_GAMMA_EXPONENT) && defined(SK_GAMMA_SRGB)
@@ -422,4 +367,10 @@
# define SK_GAMMA_EXPONENT (2.2f)
#endif
+//////////////////////////////////////////////////////////////////////
+
+#ifndef GR_TEST_UTILS
+# define GR_TEST_UTILS 1
+#endif
+
#endif // SkPostConfig_DEFINED
diff --git a/gfx/skia/skia/include/core/SkPreConfig.h b/gfx/skia/skia/include/core/SkPreConfig.h
index c7331113dc..a1a3037b94 100644
--- a/gfx/skia/skia/include/core/SkPreConfig.h
+++ b/gfx/skia/skia/include/core/SkPreConfig.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,42 +5,32 @@
* found in the LICENSE file.
*/
+// IWYU pragma: private, include "SkTypes.h"
#ifndef SkPreConfig_DEFINED
#define SkPreConfig_DEFINED
-#ifdef WEBKIT_VERSION_MIN_REQUIRED
- #include "config.h"
-#endif
-
// Allows embedders that want to disable macros that take arguments to just
// define that symbol to be one of these
-//
#define SK_NOTHING_ARG1(arg1)
#define SK_NOTHING_ARG2(arg1, arg2)
#define SK_NOTHING_ARG3(arg1, arg2, arg3)
//////////////////////////////////////////////////////////////////////
-#if !defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_PALM) && !defined(SK_BUILD_FOR_WINCE) && !defined(SK_BUILD_FOR_WIN32) && !defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_SDL) && !defined(SK_BUILD_FOR_BREW) && !defined(SK_BUILD_FOR_NACL)
+#if !defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_WIN32) && !defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC)
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif
- #if defined(PALMOS_SDK_VERSION)
- #define SK_BUILD_FOR_PALM
- #elif defined(UNDER_CE)
- #define SK_BUILD_FOR_WINCE
- #elif defined(WIN32)
- #define SK_BUILD_FOR_WIN32
- #elif defined(__SYMBIAN32__)
+ #if defined(WIN32) || defined(__SYMBIAN32__)
#define SK_BUILD_FOR_WIN32
#elif defined(ANDROID)
#define SK_BUILD_FOR_ANDROID
- #elif defined(linux) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
- defined(__sun) || defined(__NetBSD__) || defined(__DragonFly__) || \
- defined(__GLIBC__) || defined(__GNU__)
+ #elif defined(linux) || defined(__linux) || defined(__FreeBSD__) || \
+ defined(__OpenBSD__) || defined(__sun) || defined(__NetBSD__) || \
+ defined(__DragonFly__) || defined(__GLIBC__) || defined(__GNU__)
#define SK_BUILD_FOR_UNIX
#elif TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#define SK_BUILD_FOR_IOS
@@ -125,12 +114,18 @@
#define SK_CPU_SSE_LEVEL_SSSE3 31
#define SK_CPU_SSE_LEVEL_SSE41 41
#define SK_CPU_SSE_LEVEL_SSE42 42
+#define SK_CPU_SSE_LEVEL_AVX 51
+#define SK_CPU_SSE_LEVEL_AVX2 52
// Are we in GCC?
#ifndef SK_CPU_SSE_LEVEL
// These checks must be done in descending order to ensure we set the highest
// available SSE level.
- #if defined(__SSE4_2__)
+ #if defined(__AVX2__)
+ #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2
+ #elif defined(__AVX__)
+ #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX
+ #elif defined(__SSE4_2__)
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE42
#elif defined(__SSE4_1__)
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE41
@@ -147,9 +142,13 @@
#ifndef SK_CPU_SSE_LEVEL
// These checks must be done in descending order to ensure we set the highest
// available SSE level. 64-bit intel guarantees at least SSE2 support.
- #if defined(_M_X64) || defined(_M_AMD64)
- #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2
- #elif defined (_M_IX86_FP)
+ #if defined(__AVX2__)
+ #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2
+ #elif defined(__AVX__)
+ #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX
+ #elif defined(_M_X64) || defined(_M_AMD64)
+ #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2
+ #elif defined(_M_IX86_FP)
#if _M_IX86_FP >= 2
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2
#elif _M_IX86_FP == 1
@@ -183,12 +182,6 @@
#else
#define SK_ARM_ARCH 3
#endif
-
- #if defined(__thumb2__) && (SK_ARM_ARCH >= 6) \
- || !defined(__thumb__) && ((SK_ARM_ARCH > 5) || defined(__ARM_ARCH_5E__) \
- || defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__))
- #define SK_ARM_HAS_EDSP
- #endif
#endif
#endif
@@ -197,6 +190,12 @@
#define SK_CPU_ARM64
#endif
+// All 64-bit ARM chips have NEON. Many 32-bit ARM chips do too.
+// TODO: Why don't we want NEON on iOS?
+#if !defined(SK_ARM_HAS_NEON) && !defined(SK_BUILD_FOR_IOS) && defined(__ARM_NEON)
+ #define SK_ARM_HAS_NEON
+#endif
+
//////////////////////////////////////////////////////////////////////
#if !defined(SKIA_IMPLEMENTATION)
diff --git a/gfx/skia/skia/include/core/SkRRect.h b/gfx/skia/skia/include/core/SkRRect.h
index d3f48cd484..8d8cdbf02c 100644
--- a/gfx/skia/skia/include/core/SkRRect.h
+++ b/gfx/skia/skia/include/core/SkRRect.h
@@ -52,9 +52,6 @@ public:
* by type(). The subtypes become progressively less restrictive.
*/
enum Type {
- // !< Internal indicator that the sub type must be computed.
- kUnknown_Type = -1,
-
// !< The RR is empty
kEmpty_Type,
@@ -90,12 +87,7 @@ public:
*/
Type getType() const {
SkDEBUGCODE(this->validate();)
-
- if (kUnknown_Type == fType) {
- this->computeType();
- }
- SkASSERT(kUnknown_Type != fType);
- return fType;
+ return static_cast(fType);
}
Type type() const { return this->getType(); }
@@ -104,8 +96,13 @@ public:
inline bool isRect() const { return kRect_Type == this->getType(); }
inline bool isOval() const { return kOval_Type == this->getType(); }
inline bool isSimple() const { return kSimple_Type == this->getType(); }
+ // TODO: should isSimpleCircular & isCircle take a tolerance? This could help
+ // instances where the mapping to device space is noisy.
inline bool isSimpleCircular() const {
- return this->isSimple() && fRadii[0].fX == fRadii[0].fY;
+ return this->isSimple() && SkScalarNearlyEqual(fRadii[0].fX, fRadii[0].fY);
+ }
+ inline bool isCircle() const {
+ return this->isOval() && SkScalarNearlyEqual(fRadii[0].fX, fRadii[0].fY);
}
inline bool isNinePatch() const { return kNinePatch_Type == this->getType(); }
inline bool isComplex() const { return kComplex_Type == this->getType(); }
@@ -130,32 +127,48 @@ public:
* Set this RR to match the supplied rect. All radii will be 0.
*/
void setRect(const SkRect& rect) {
- if (rect.isEmpty()) {
+ fRect = rect;
+ fRect.sort();
+
+ if (fRect.isEmpty()) {
this->setEmpty();
return;
}
- fRect = rect;
memset(fRadii, 0, sizeof(fRadii));
fType = kRect_Type;
SkDEBUGCODE(this->validate();)
}
+ static SkRRect MakeRect(const SkRect& r) {
+ SkRRect rr;
+ rr.setRect(r);
+ return rr;
+ }
+
+ static SkRRect MakeOval(const SkRect& oval) {
+ SkRRect rr;
+ rr.setOval(oval);
+ return rr;
+ }
+
/**
* Set this RR to match the supplied oval. All x radii will equal half the
* width and all y radii will equal half the height.
*/
void setOval(const SkRect& oval) {
- if (oval.isEmpty()) {
+ fRect = oval;
+ fRect.sort();
+
+ if (fRect.isEmpty()) {
this->setEmpty();
return;
}
- SkScalar xRad = SkScalarHalf(oval.width());
- SkScalar yRad = SkScalarHalf(oval.height());
+ SkScalar xRad = SkScalarHalf(fRect.width());
+ SkScalar yRad = SkScalarHalf(fRect.height());
- fRect = oval;
for (int i = 0; i < 4; ++i) {
fRadii[i].set(xRad, yRad);
}
@@ -292,23 +305,20 @@ public:
*/
bool transform(const SkMatrix& matrix, SkRRect* dst) const;
-#ifdef SK_DEVELOPER
- /**
- * Prints the rrect using SkDebugf. This is intended for Skia development debugging. Don't
- * rely on the existence of this function or the formatting of its output.
- */
- void dump() const;
-#endif
+ void dump(bool asHex) const;
+ void dump() const { this->dump(false); }
+ void dumpHex() const { this->dump(true); }
private:
SkRect fRect;
// Radii order is UL, UR, LR, LL. Use Corner enum to index into fRadii[]
SkVector fRadii[4];
- mutable Type fType;
+ // use an explicitly sized type so we're sure the class is dense (no uninitialized bytes)
+ int32_t fType;
// TODO: add padding so we can use memcpy for flattening and not copy
// uninitialized data
- void computeType() const;
+ void computeType();
bool checkCornerContainment(SkScalar x, SkScalar y) const;
// to access fRadii directly
diff --git a/gfx/skia/skia/include/core/SkRSXform.h b/gfx/skia/skia/include/core/SkRSXform.h
new file mode 100644
index 0000000000..7af6e67c12
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkRSXform.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2015 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkRSXform_DEFINED
+#define SkRSXform_DEFINED
+
+#include "SkScalar.h"
+
+/**
+ * A compressed form of a rotation+scale matrix.
+ *
+ * [ fSCos -fSSin fTx ]
+ * [ fSSin fSCos fTy ]
+ * [ 0 0 1 ]
+ */
+struct SkRSXform {
+ static SkRSXform Make(SkScalar scos, SkScalar ssin, SkScalar tx, SkScalar ty) {
+ SkRSXform xform = { scos, ssin, tx, ty };
+ return xform;
+ }
+
+ /*
+ * Initialize a new xform based on the scale, rotation (in radians), final tx,ty location
+ * and anchor-point ax,ay within the src quad.
+ *
+ * Note: the anchor point is not normalized (e.g. 0...1) but is in pixels of the src image.
+ */
+ static SkRSXform MakeFromRadians(SkScalar scale, SkScalar radians, SkScalar tx, SkScalar ty,
+ SkScalar ax, SkScalar ay) {
+ const SkScalar s = SkScalarSin(radians) * scale;
+ const SkScalar c = SkScalarCos(radians) * scale;
+ return Make(c, s, tx + -c * ax + s * ay, ty + -s * ax - c * ay);
+ }
+
+ SkScalar fSCos;
+ SkScalar fSSin;
+ SkScalar fTx;
+ SkScalar fTy;
+
+ bool rectStaysRect() const {
+ return 0 == fSCos || 0 == fSSin;
+ }
+
+ void setIdentity() {
+ fSCos = 1;
+ fSSin = fTx = fTy = 0;
+ }
+
+ void set(SkScalar scos, SkScalar ssin, SkScalar tx, SkScalar ty) {
+ fSCos = scos;
+ fSSin = ssin;
+ fTx = tx;
+ fTy = ty;
+ }
+
+ void toQuad(SkScalar width, SkScalar height, SkPoint quad[4]) const;
+ void toQuad(const SkSize& size, SkPoint quad[4]) const {
+ this->toQuad(size.width(), size.height(), quad);
+ }
+};
+
+#endif
+
diff --git a/gfx/skia/skia/include/core/SkRasterizer.h b/gfx/skia/skia/include/core/SkRasterizer.h
index d6e514c263..1881ccef24 100644
--- a/gfx/skia/skia/include/core/SkRasterizer.h
+++ b/gfx/skia/skia/include/core/SkRasterizer.h
@@ -20,8 +20,6 @@ struct SkIRect;
class SK_API SkRasterizer : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkRasterizer)
-
/** Turn the path into a mask, respecting the specified local->device matrix.
*/
bool rasterize(const SkPath& path, const SkMatrix& matrix,
@@ -32,8 +30,6 @@ public:
protected:
SkRasterizer() {}
- SkRasterizer(SkReadBuffer& buffer) : INHERITED(buffer) {}
-
virtual bool onRasterize(const SkPath& path, const SkMatrix& matrix,
const SkIRect* clipBounds,
SkMask* mask, SkMask::CreateMode mode) const;
diff --git a/gfx/skia/skia/include/core/SkReadBuffer.h b/gfx/skia/skia/include/core/SkReadBuffer.h
deleted file mode 100644
index faf7eb81a5..0000000000
--- a/gfx/skia/skia/include/core/SkReadBuffer.h
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Copyright 2011 Google Inc.
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SkReadBuffer_DEFINED
-#define SkReadBuffer_DEFINED
-
-#include "SkBitmapHeap.h"
-#include "SkColorFilter.h"
-#include "SkData.h"
-#include "SkDrawLooper.h"
-#include "SkImageFilter.h"
-#include "SkMaskFilter.h"
-#include "SkPath.h"
-#include "SkPathEffect.h"
-#include "SkPicture.h"
-#include "SkRasterizer.h"
-#include "SkReadBuffer.h"
-#include "SkReader32.h"
-#include "SkRefCnt.h"
-#include "SkShader.h"
-#include "SkWriteBuffer.h"
-#include "SkXfermode.h"
-
-class SkBitmap;
-
-#if defined(SK_DEBUG) && defined(SK_BUILD_FOR_MAC)
- #define DEBUG_NON_DETERMINISTIC_ASSERT
-#endif
-
-class SkReadBuffer {
-public:
- SkReadBuffer();
- SkReadBuffer(const void* data, size_t size);
- SkReadBuffer(SkStream* stream);
- virtual ~SkReadBuffer();
-
- enum Version {
- kFilterLevelIsEnum_Version = 23,
- kGradientFlippedFlag_Version = 24,
- kDashWritesPhaseIntervals_Version = 25,
- kColorShaderNoBool_Version = 26,
- kNoUnitMappers_Version = 27,
- kNoMoreBitmapFlatten_Version = 28,
- kSimplifyLocalMatrix_Version = 30,
- };
-
- /**
- * Returns true IFF the version is older than the specified version.
- */
- bool isVersionLT(Version targetVersion) const {
- SkASSERT(targetVersion > 0);
- return fVersion > 0 && fVersion < targetVersion;
- }
-
- /** This may be called at most once; most clients of SkReadBuffer should not mess with it. */
- void setVersion(int version) {
- SkASSERT(0 == fVersion || version == fVersion);
- fVersion = version;
- }
-
- enum Flags {
- kCrossProcess_Flag = 1 << 0,
- kScalarIsFloat_Flag = 1 << 1,
- kPtrIs64Bit_Flag = 1 << 2,
- kValidation_Flag = 1 << 3,
- };
-
- void setFlags(uint32_t flags) { fFlags = flags; }
- uint32_t getFlags() const { return fFlags; }
-
- bool isCrossProcess() const {
- return this->isValidating() || SkToBool(fFlags & kCrossProcess_Flag);
- }
- bool isScalarFloat() const { return SkToBool(fFlags & kScalarIsFloat_Flag); }
- bool isPtr64Bit() const { return SkToBool(fFlags & kPtrIs64Bit_Flag); }
- bool isValidating() const { return SkToBool(fFlags & kValidation_Flag); }
-
- SkReader32* getReader32() { return &fReader; }
-
- size_t size() { return fReader.size(); }
- size_t offset() { return fReader.offset(); }
- bool eof() { return fReader.eof(); }
- virtual const void* skip(size_t size) { return fReader.skip(size); }
- void* readFunctionPtr() { return fReader.readPtr(); }
-
- // primitives
- virtual bool readBool();
- virtual SkColor readColor();
- virtual SkFixed readFixed();
- virtual int32_t readInt();
- virtual SkScalar readScalar();
- virtual uint32_t readUInt();
- virtual int32_t read32();
-
- // strings -- the caller is responsible for freeing the string contents
- virtual void readString(SkString* string);
- virtual void* readEncodedString(size_t* length, SkPaint::TextEncoding encoding);
-
- // common data structures
- virtual void readPoint(SkPoint* point);
- SkPoint readPoint() { SkPoint p; this->readPoint(&p); return p; }
- virtual void readMatrix(SkMatrix* matrix);
- virtual void readIRect(SkIRect* rect);
- virtual void readRect(SkRect* rect);
- virtual void readRegion(SkRegion* region);
- virtual void readPath(SkPath* path);
- void readPaint(SkPaint* paint) { paint->unflatten(*this); }
-
- virtual SkFlattenable* readFlattenable(SkFlattenable::Type);
- template T* readFlattenable() {
- return (T*) this->readFlattenable(T::GetFlattenableType());
- }
- SkColorFilter* readColorFilter() { return this->readFlattenable(); }
- SkDrawLooper* readDrawLooper() { return this->readFlattenable(); }
- SkImageFilter* readImageFilter() { return this->readFlattenable(); }
- SkMaskFilter* readMaskFilter() { return this->readFlattenable(); }
- SkPathEffect* readPathEffect() { return this->readFlattenable(); }
- SkRasterizer* readRasterizer() { return this->readFlattenable(); }
- SkShader* readShader() { return this->readFlattenable(); }
- SkXfermode* readXfermode() { return this->readFlattenable(); }
-
- /**
- * Like readFlattenable() but explicitly just skips the data that was written for the
- * flattenable (or the sentinel that there wasn't one).
- */
- virtual void skipFlattenable();
-
- // binary data and arrays
- virtual bool readByteArray(void* value, size_t size);
- virtual bool readColorArray(SkColor* colors, size_t size);
- virtual bool readIntArray(int32_t* values, size_t size);
- virtual bool readPointArray(SkPoint* points, size_t size);
- virtual bool readScalarArray(SkScalar* values, size_t size);
-
- SkData* readByteArrayAsData() {
- size_t len = this->getArrayCount();
- if (!this->validateAvailable(len)) {
- return SkData::NewEmpty();
- }
- void* buffer = sk_malloc_throw(len);
- this->readByteArray(buffer, len);
- return SkData::NewFromMalloc(buffer, len);
- }
-
- // helpers to get info about arrays and binary data
- virtual uint32_t getArrayCount();
-
- /**
- * Returns false if the bitmap could not be completely read. In that case, it will be set
- * to have width/height, but no pixels.
- */
- bool readBitmap(SkBitmap* bitmap);
-
- virtual SkTypeface* readTypeface();
-
- void setBitmapStorage(SkBitmapHeapReader* bitmapStorage) {
- SkRefCnt_SafeAssign(fBitmapStorage, bitmapStorage);
- }
-
- void setTypefaceArray(SkTypeface* array[], int count) {
- fTFArray = array;
- fTFCount = count;
- }
-
- /**
- * Call this with a pre-loaded array of Factories, in the same order as
- * were created/written by the writer. SkPicture uses this.
- */
- void setFactoryPlayback(SkFlattenable::Factory array[], int count) {
- fFactoryTDArray = NULL;
- fFactoryArray = array;
- fFactoryCount = count;
- }
-
- /**
- * Call this with an initially empty array, so the reader can cache each
- * factory it sees by name. Used by the pipe code in conjunction with
- * SkWriteBuffer::setNamedFactoryRecorder.
- */
- void setFactoryArray(SkTDArray* array) {
- fFactoryTDArray = array;
- fFactoryArray = NULL;
- fFactoryCount = 0;
- }
-
- /**
- * Provide a function to decode an SkBitmap from encoded data. Only used if the writer
- * encoded the SkBitmap. If the proper decoder cannot be used, a red bitmap with the
- * appropriate size will be used.
- */
- void setBitmapDecoder(SkPicture::InstallPixelRefProc bitmapDecoder) {
- fBitmapDecoder = bitmapDecoder;
- }
-
- // Default impelementations don't check anything.
- virtual bool validate(bool isValid) { return true; }
- virtual bool isValid() const { return true; }
- virtual bool validateAvailable(size_t size) { return true; }
-
-protected:
- SkReader32 fReader;
-
-private:
- bool readArray(void* value, size_t size, size_t elementSize);
-
- uint32_t fFlags;
- int fVersion;
-
- void* fMemoryPtr;
-
- SkBitmapHeapReader* fBitmapStorage;
- SkTypeface** fTFArray;
- int fTFCount;
-
- SkTDArray* fFactoryTDArray;
- SkFlattenable::Factory* fFactoryArray;
- int fFactoryCount;
-
- SkPicture::InstallPixelRefProc fBitmapDecoder;
-
-#ifdef DEBUG_NON_DETERMINISTIC_ASSERT
- // Debugging counter to keep track of how many bitmaps we
- // have decoded.
- int fDecodedBitmapIndex;
-#endif // DEBUG_NON_DETERMINISTIC_ASSERT
-};
-
-#endif // SkReadBuffer_DEFINED
diff --git a/gfx/skia/skia/include/core/SkReader32.h b/gfx/skia/skia/include/core/SkReader32.h
deleted file mode 100644
index 51e28ef146..0000000000
--- a/gfx/skia/skia/include/core/SkReader32.h
+++ /dev/null
@@ -1,160 +0,0 @@
-
-/*
- * Copyright 2008 The Android Open Source Project
- *
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-
-#ifndef SkReader32_DEFINED
-#define SkReader32_DEFINED
-
-#include "SkMatrix.h"
-#include "SkPath.h"
-#include "SkRegion.h"
-#include "SkRRect.h"
-#include "SkScalar.h"
-
-class SkString;
-
-class SkReader32 : SkNoncopyable {
-public:
- SkReader32() : fCurr(NULL), fStop(NULL), fBase(NULL) {}
- SkReader32(const void* data, size_t size) {
- this->setMemory(data, size);
- }
-
- void setMemory(const void* data, size_t size) {
- SkASSERT(ptr_align_4(data));
- SkASSERT(SkAlign4(size) == size);
-
- fBase = fCurr = (const char*)data;
- fStop = (const char*)data + size;
- }
-
- size_t size() const { return fStop - fBase; }
- size_t offset() const { return fCurr - fBase; }
- bool eof() const { return fCurr >= fStop; }
- const void* base() const { return fBase; }
- const void* peek() const { return fCurr; }
-
- size_t available() const { return fStop - fCurr; }
- bool isAvailable(size_t size) const { return size <= this->available(); }
-
- void rewind() { fCurr = fBase; }
-
- void setOffset(size_t offset) {
- SkASSERT(SkAlign4(offset) == offset);
- SkASSERT(offset <= this->size());
- fCurr = fBase + offset;
- }
-
- bool readBool() { return this->readInt() != 0; }
-
- int32_t readInt() {
- SkASSERT(ptr_align_4(fCurr));
- int32_t value = *(const int32_t*)fCurr;
- fCurr += sizeof(value);
- SkASSERT(fCurr <= fStop);
- return value;
- }
-
- void* readPtr() {
- void* ptr;
- // we presume this "if" is resolved at compile-time
- if (4 == sizeof(void*)) {
- ptr = *(void**)fCurr;
- } else {
- memcpy(&ptr, fCurr, sizeof(void*));
- }
- fCurr += sizeof(void*);
- return ptr;
- }
-
- SkScalar readScalar() {
- SkASSERT(ptr_align_4(fCurr));
- SkScalar value = *(const SkScalar*)fCurr;
- fCurr += sizeof(value);
- SkASSERT(fCurr <= fStop);
- return value;
- }
-
- const void* skip(size_t size) {
- SkASSERT(ptr_align_4(fCurr));
- const void* addr = fCurr;
- fCurr += SkAlign4(size);
- SkASSERT(fCurr <= fStop);
- return addr;
- }
-
- template const T& skipT() {
- SkASSERT(SkAlign4(sizeof(T)) == sizeof(T));
- return *(const T*)this->skip(sizeof(T));
- }
-
- void read(void* dst, size_t size) {
- SkASSERT(0 == size || dst != NULL);
- SkASSERT(ptr_align_4(fCurr));
- memcpy(dst, fCurr, size);
- fCurr += SkAlign4(size);
- SkASSERT(fCurr <= fStop);
- }
-
- uint8_t readU8() { return (uint8_t)this->readInt(); }
- uint16_t readU16() { return (uint16_t)this->readInt(); }
- int32_t readS32() { return this->readInt(); }
- uint32_t readU32() { return this->readInt(); }
-
- bool readPath(SkPath* path) {
- return readObjectFromMemory(path);
- }
-
- bool readMatrix(SkMatrix* matrix) {
- return readObjectFromMemory(matrix);
- }
-
- bool readRRect(SkRRect* rrect) {
- return readObjectFromMemory(rrect);
- }
-
- bool readRegion(SkRegion* rgn) {
- return readObjectFromMemory(rgn);
- }
-
- /**
- * Read the length of a string (written by SkWriter32::writeString) into
- * len (if len is not NULL) and return the null-ternimated address of the
- * string within the reader's buffer.
- */
- const char* readString(size_t* len = NULL);
-
- /**
- * Read the string (written by SkWriter32::writeString) and return it in
- * copy (if copy is not null). Return the length of the string.
- */
- size_t readIntoString(SkString* copy);
-
-private:
- template bool readObjectFromMemory(T* obj) {
- size_t size = obj->readFromMemory(this->peek(), this->available());
- // If readFromMemory() fails (which means that available() was too small), it returns 0
- bool success = (size > 0) && (size <= this->available()) && (SkAlign4(size) == size);
- // In case of failure, we want to skip to the end
- (void)this->skip(success ? size : this->available());
- return success;
- }
-
- // these are always 4-byte aligned
- const char* fCurr; // current position within buffer
- const char* fStop; // end of buffer
- const char* fBase; // beginning of buffer
-
-#ifdef SK_DEBUG
- static bool ptr_align_4(const void* ptr) {
- return (((const char*)ptr - (const char*)NULL) & 3) == 0;
- }
-#endif
-};
-
-#endif
diff --git a/gfx/skia/skia/include/core/SkRect.h b/gfx/skia/skia/include/core/SkRect.h
index d699156ebf..fe276e6710 100644
--- a/gfx/skia/skia/include/core/SkRect.h
+++ b/gfx/skia/skia/include/core/SkRect.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,13 +5,14 @@
* found in the LICENSE file.
*/
-
#ifndef SkRect_DEFINED
#define SkRect_DEFINED
#include "SkPoint.h"
#include "SkSize.h"
+struct SkRect;
+
/** \struct SkIRect
SkIRect holds four 32 bit integer coordinates for a rectangle
@@ -77,6 +77,8 @@ struct SK_API SkIRect {
*/
int height() const { return fBottom - fTop; }
+ SkISize size() const { return SkISize::Make(this->width(), this->height()); }
+
/**
* Since the center of an integer rect may fall on a factional value, this
* method is defined to return (right + left) >> 1.
@@ -160,17 +162,24 @@ struct SK_API SkIRect {
/**
* Return a new IRect, built as an offset of this rect.
*/
- SkIRect makeOffset(int dx, int dy) const {
+ SkIRect makeOffset(int32_t dx, int32_t dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight + dx, fBottom + dy);
}
/**
* Return a new IRect, built as an inset of this rect.
*/
- SkIRect makeInset(int dx, int dy) const {
+ SkIRect makeInset(int32_t dx, int32_t dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight - dx, fBottom - dy);
}
+ /**
+ * Return a new Rect, built as an outset of this rect.
+ */
+ SkIRect makeOutset(int32_t dx, int32_t dy) const {
+ return MakeLTRB(fLeft - dx, fTop - dy, fRight + dx, fBottom + dy);
+ }
+
/** Offset set the rectangle by adding dx to its left and right,
and adding dy to its top and bottom.
*/
@@ -244,6 +253,10 @@ struct SK_API SkIRect {
fRight >= r.fRight && fBottom >= r.fBottom;
}
+ /** Returns true if the specified rectangle r is inside or equal to this rectangle.
+ */
+ bool contains(const SkRect& r) const;
+
/** Return true if this rectangle contains the specified rectangle.
For speed, this method does not check if either this or the specified
rectangles are empty, and if either is, its return value is undefined.
@@ -267,8 +280,7 @@ struct SK_API SkIRect {
intersection, otherwise return false and do not change this rectangle.
If either rectangle is empty, do nothing and return false.
*/
- bool intersect(const SkIRect& r) {
- SkASSERT(&r);
+ bool SK_WARN_UNUSED_RESULT intersect(const SkIRect& r) {
return this->intersect(r.fLeft, r.fTop, r.fRight, r.fBottom);
}
@@ -276,7 +288,7 @@ struct SK_API SkIRect {
that intersection, otherwise return false and do not change this
rectangle. If either rectangle is empty, do nothing and return false.
*/
- bool intersect(const SkIRect& a, const SkIRect& b) {
+ bool SK_WARN_UNUSED_RESULT intersect(const SkIRect& a, const SkIRect& b) {
if (!a.isEmpty() && !b.isEmpty() &&
a.fLeft < b.fRight && b.fLeft < a.fRight &&
@@ -296,7 +308,7 @@ struct SK_API SkIRect {
If either is, then the return result is undefined. In the debug build,
we assert that both rectangles are non-empty.
*/
- bool intersectNoEmptyCheck(const SkIRect& a, const SkIRect& b) {
+ bool SK_WARN_UNUSED_RESULT intersectNoEmptyCheck(const SkIRect& a, const SkIRect& b) {
SkASSERT(!a.isEmpty() && !b.isEmpty());
if (a.fLeft < b.fRight && b.fLeft < a.fRight &&
@@ -315,7 +327,8 @@ struct SK_API SkIRect {
otherwise return false and do not change this rectangle.
If either rectangle is empty, do nothing and return false.
*/
- bool intersect(int32_t left, int32_t top, int32_t right, int32_t bottom) {
+ bool SK_WARN_UNUSED_RESULT intersect(int32_t left, int32_t top,
+ int32_t right, int32_t bottom) {
if (left < right && top < bottom && !this->isEmpty() &&
fLeft < right && left < fRight && fTop < bottom && top < fBottom) {
if (fLeft < left) fLeft = left;
@@ -331,8 +344,8 @@ struct SK_API SkIRect {
*/
static bool Intersects(const SkIRect& a, const SkIRect& b) {
return !a.isEmpty() && !b.isEmpty() && // check for empties
- a.fLeft < b.fRight && b.fLeft < a.fRight &&
- a.fTop < b.fBottom && b.fTop < a.fBottom;
+ a.fLeft < b.fRight && b.fLeft < a.fRight &&
+ a.fTop < b.fBottom && b.fTop < a.fBottom;
}
/**
@@ -395,6 +408,12 @@ struct SK_API SkRect {
return r;
}
+ static SkRect SK_WARN_UNUSED_RESULT MakeIWH(int w, int h) {
+ SkRect r;
+ r.set(0, 0, SkIntToScalar(w), SkIntToScalar(h));
+ return r;
+ }
+
static SkRect SK_WARN_UNUSED_RESULT MakeSize(const SkSize& size) {
SkRect r;
r.set(0, 0, size.width(), size.height());
@@ -595,7 +614,7 @@ struct SK_API SkRect {
SkRect makeOffset(SkScalar dx, SkScalar dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight + dx, fBottom + dy);
}
-
+
/**
* Return a new Rect, built as an inset of this rect.
*/
@@ -603,6 +622,13 @@ struct SK_API SkRect {
return MakeLTRB(fLeft + dx, fTop + dy, fRight - dx, fBottom - dy);
}
+ /**
+ * Return a new Rect, built as an outset of this rect.
+ */
+ SkRect makeOutset(SkScalar dx, SkScalar dy) const {
+ return MakeLTRB(fLeft - dx, fTop - dy, fRight + dx, fBottom + dy);
+ }
+
/** Offset set the rectangle by adding dx to its left and right,
and adding dy to its top and bottom.
*/
@@ -650,42 +676,54 @@ struct SK_API SkRect {
intersection, otherwise return false and do not change this rectangle.
If either rectangle is empty, do nothing and return false.
*/
- bool intersect(const SkRect& r);
- bool intersect2(const SkRect& r);
+ bool SK_WARN_UNUSED_RESULT intersect(const SkRect& r);
/** If this rectangle intersects the rectangle specified by left, top, right, bottom,
return true and set this rectangle to that intersection, otherwise return false
and do not change this rectangle.
If either rectangle is empty, do nothing and return false.
*/
- bool intersect(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom);
+ bool SK_WARN_UNUSED_RESULT intersect(SkScalar left, SkScalar top,
+ SkScalar right, SkScalar bottom);
+ /**
+ * If rectangles a and b intersect, return true and set this rectangle to
+ * that intersection, otherwise return false and do not change this
+ * rectangle. If either rectangle is empty, do nothing and return false.
+ */
+ bool SK_WARN_UNUSED_RESULT intersect(const SkRect& a, const SkRect& b);
+
+
+private:
+ static bool Intersects(SkScalar al, SkScalar at, SkScalar ar, SkScalar ab,
+ SkScalar bl, SkScalar bt, SkScalar br, SkScalar bb) {
+ SkScalar L = SkMaxScalar(al, bl);
+ SkScalar R = SkMinScalar(ar, br);
+ SkScalar T = SkMaxScalar(at, bt);
+ SkScalar B = SkMinScalar(ab, bb);
+ return L < R && T < B;
+ }
+
+public:
/**
* Return true if this rectangle is not empty, and the specified sides of
* a rectangle are not empty, and they intersect.
*/
bool intersects(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom) const {
- return // first check that both are not empty
- left < right && top < bottom &&
- fLeft < fRight && fTop < fBottom &&
- // now check for intersection
- fLeft < right && left < fRight &&
- fTop < bottom && top < fBottom;
+ return Intersects(fLeft, fTop, fRight, fBottom, left, top, right, bottom);
}
- /** If rectangles a and b intersect, return true and set this rectangle to
- * that intersection, otherwise return false and do not change this
- * rectangle. If either rectangle is empty, do nothing and return false.
- */
- bool intersect(const SkRect& a, const SkRect& b);
+ bool intersects(const SkRect& r) const {
+ return Intersects(fLeft, fTop, fRight, fBottom,
+ r.fLeft, r.fTop, r.fRight, r.fBottom);
+ }
/**
* Return true if rectangles a and b are not empty and intersect.
*/
static bool Intersects(const SkRect& a, const SkRect& b) {
- return !a.isEmpty() && !b.isEmpty() &&
- a.fLeft < b.fRight && b.fLeft < a.fRight &&
- a.fTop < b.fBottom && b.fTop < a.fBottom;
+ return Intersects(a.fLeft, a.fTop, a.fRight, a.fBottom,
+ b.fLeft, b.fTop, b.fRight, b.fBottom);
}
/**
@@ -702,8 +740,27 @@ struct SK_API SkRect {
void join(const SkRect& r) {
this->join(r.fLeft, r.fTop, r.fRight, r.fBottom);
}
- // alias for join()
- void growToInclude(const SkRect& r) { this->join(r); }
+
+ void joinNonEmptyArg(const SkRect& r) {
+ SkASSERT(!r.isEmpty());
+ // if we are empty, just assign
+ if (fLeft >= fRight || fTop >= fBottom) {
+ *this = r;
+ } else {
+ this->joinPossiblyEmptyRect(r);
+ }
+ }
+
+ /**
+ * Joins the rectangle with another without checking if either are empty (may produce unexpected
+ * results if either rect is inverted).
+ */
+ void joinPossiblyEmptyRect(const SkRect& r) {
+ fLeft = SkMinScalar(fLeft, r.left());
+ fTop = SkMinScalar(fTop, r.top());
+ fRight = SkMaxScalar(fRight, r.right());
+ fBottom = SkMaxScalar(fBottom, r.bottom());
+ }
/**
* Grow the rect to include the specified (x,y). After this call, the
@@ -747,6 +804,16 @@ struct SK_API SkRect {
fRight >= r.fRight && fBottom >= r.fBottom;
}
+ /**
+ * Returns true if the specified rectangle r is inside or equal to this rectangle.
+ */
+ bool contains(const SkIRect& r) const {
+ // todo: can we eliminate the this->isEmpty check?
+ return !r.isEmpty() && !this->isEmpty() &&
+ fLeft <= SkIntToScalar(r.fLeft) && fTop <= SkIntToScalar(r.fTop) &&
+ fRight >= SkIntToScalar(r.fRight) && fBottom >= SkIntToScalar(r.fBottom);
+ }
+
/**
* Set the dst rectangle by rounding this rectangle's coordinates to their
* nearest integer values using SkScalarRoundToInt.
@@ -786,15 +853,16 @@ struct SK_API SkRect {
}
/**
- * Expand this rectangle by rounding its coordinates "out", choosing the
- * floor of top and left, and the ceil of right and bottom. If this rect
- * is already on integer coordinates, then it will be unchanged.
+ * Set the dst rectangle by rounding "out" this rectangle, choosing the
+ * SkScalarFloorToScalar of top and left, and the SkScalarCeilToScalar of right and bottom.
+ *
+ * It is safe for this == dst
*/
- void roundOut() {
- this->set(SkScalarFloorToScalar(fLeft),
- SkScalarFloorToScalar(fTop),
- SkScalarCeilToScalar(fRight),
- SkScalarCeilToScalar(fBottom));
+ void roundOut(SkRect* dst) const {
+ dst->set(SkScalarFloorToScalar(fLeft),
+ SkScalarFloorToScalar(fTop),
+ SkScalarCeilToScalar(fRight),
+ SkScalarCeilToScalar(fBottom));
}
/**
@@ -809,39 +877,50 @@ struct SK_API SkRect {
SkScalarFloorToInt(fRight), SkScalarFloorToInt(fBottom));
}
- /**
- * Return a new SkIRect which is contains the rounded coordinates of this
- * rect using SkScalarRoundToInt.
- */
+ //! Returns the result of calling round(&dst)
SkIRect round() const {
SkIRect ir;
this->round(&ir);
return ir;
}
-
+
+ //! Returns the result of calling roundOut(&dst)
+ SkIRect roundOut() const {
+ SkIRect ir;
+ this->roundOut(&ir);
+ return ir;
+ }
+
/**
* Swap top/bottom or left/right if there are flipped (i.e. if width()
* or height() would have returned a negative value.) This should be called
* if the edges are computed separately, and may have crossed over each
* other. When this returns, left <= right && top <= bottom
*/
- void sort();
+ void sort() {
+ if (fLeft > fRight) {
+ SkTSwap(fLeft, fRight);
+ }
+
+ if (fTop > fBottom) {
+ SkTSwap(fTop, fBottom);
+ }
+ }
/**
* cast-safe way to treat the rect as an array of (4) SkScalars.
*/
const SkScalar* asScalars() const { return &fLeft; }
-#ifdef SK_DEVELOPER
- /**
- * Dumps the rect using SkDebugf. This is intended for Skia development debugging. Don't
- * rely on the existence of this function or the formatting of its output.
- */
- void dump() const {
- SkDebugf("{ l: %f, t: %f, r: %f, b: %f }", fLeft, fTop, fRight, fBottom);
- }
-#endif
-
+ void dump(bool asHex) const;
+ void dump() const { this->dump(false); }
+ void dumpHex() const { this->dump(true); }
};
+inline bool SkIRect::contains(const SkRect& r) const {
+ return !r.isEmpty() && !this->isEmpty() && // check for empties
+ (SkScalar)fLeft <= r.fLeft && (SkScalar)fTop <= r.fTop &&
+ (SkScalar)fRight >= r.fRight && (SkScalar)fBottom >= r.fBottom;
+}
+
#endif
diff --git a/gfx/skia/skia/include/core/SkRefCnt.h b/gfx/skia/skia/include/core/SkRefCnt.h
index ce38c67bd5..6c608ac939 100644
--- a/gfx/skia/skia/include/core/SkRefCnt.h
+++ b/gfx/skia/skia/include/core/SkRefCnt.h
@@ -1,4 +1,3 @@
-
/*
* Copyright 2006 The Android Open Source Project
*
@@ -6,14 +5,12 @@
* found in the LICENSE file.
*/
-
#ifndef SkRefCnt_DEFINED
#define SkRefCnt_DEFINED
-#include "SkDynamicAnnotations.h"
-#include "SkThread.h"
-#include "SkInstCnt.h"
-#include "SkTemplates.h"
+#include "../private/SkAtomics.h"
+#include "../private/SkUniquePtr.h"
+#include "SkTypes.h"
/** \class SkRefCntBase
@@ -27,8 +24,6 @@
*/
class SK_API SkRefCntBase : SkNoncopyable {
public:
- SK_DECLARE_INST_COUNT_ROOT(SkRefCntBase)
-
/** Default construct, initializing the reference count to 1.
*/
SkRefCntBase() : fRefCnt(1) {}
@@ -49,22 +44,28 @@ public:
* Ensures that all previous owner's actions are complete.
*/
bool unique() const {
- // We believe we're reading fRefCnt in a safe way here, so we stifle the TSAN warning about
- // an unproctected read. Generally, don't read fRefCnt, and don't stifle this warning.
- bool const unique = (1 == SK_ANNOTATE_UNPROTECTED_READ(fRefCnt));
- if (unique) {
- // Acquire barrier (L/SL), if not provided by load of fRefCnt.
- // Prevents user's 'unique' code from happening before decrements.
- //TODO: issue the barrier.
+ if (1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire)) {
+ // The acquire barrier is only really needed if we return true. It
+ // prevents code conditioned on the result of unique() from running
+ // until previous owners are all totally done calling unref().
+ return true;
}
- return unique;
+ return false;
}
/** Increment the reference count. Must be balanced by a call to unref().
*/
void ref() const {
+#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
+ // Android employs some special subclasses that enable the fRefCnt to
+ // go to zero, but not below, prior to reusing the object. This breaks
+ // the use of unique() on such objects and as such should be removed
+ // once the Android code is fixed.
+ SkASSERT(fRefCnt >= 0);
+#else
SkASSERT(fRefCnt > 0);
- sk_atomic_inc(&fRefCnt); // No barrier required.
+#endif
+ (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed); // No barrier required.
}
/** Decrement the reference count. If the reference count is 1 before the
@@ -73,12 +74,11 @@ public:
*/
void unref() const {
SkASSERT(fRefCnt > 0);
- // Release barrier (SL/S), if not provided below.
- if (sk_atomic_dec(&fRefCnt) == 1) {
- // Acquire barrier (L/SL), if not provided above.
- // Prevents code in dispose from happening before the decrement.
- sk_membar_acquire__after_atomic_dec();
- internal_dispose();
+ // A release here acts in place of all releases we "should" have been doing in ref().
+ if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
+ // Like unique(), the acquire is only needed on success, to make sure
+ // code in internal_dispose() doesn't happen before the decrement.
+ this->internal_dispose();
}
}
@@ -108,7 +108,7 @@ private:
*/
virtual void internal_dispose() const {
this->internal_dispose_restore_refcnt_to_1();
- SkDELETE(this);
+ delete this;
}
// The following friends are those which override internal_dispose()
@@ -142,7 +142,7 @@ class SK_API SkRefCnt : public SkRefCntBase { };
} while (0)
-/** Call obj->ref() and return obj. The obj must not be NULL.
+/** Call obj->ref() and return obj. The obj must not be nullptr.
*/
template static inline T* SkRef(T* obj) {
SkASSERT(obj);
@@ -168,76 +168,27 @@ template static inline void SkSafeUnref(T* obj) {
}
template static inline void SkSafeSetNull(T*& obj) {
- if (NULL != obj) {
+ if (obj) {
obj->unref();
- obj = NULL;
+ obj = nullptr;
}
}
///////////////////////////////////////////////////////////////////////////////
+template struct SkTUnref {
+ void operator()(T* t) { t->unref(); }
+};
+
/**
* Utility class that simply unref's its argument in the destructor.
*/
-template class SkAutoTUnref : SkNoncopyable {
+template class SkAutoTUnref : public skstd::unique_ptr> {
public:
- explicit SkAutoTUnref(T* obj = NULL) : fObj(obj) {}
- ~SkAutoTUnref() { SkSafeUnref(fObj); }
+ explicit SkAutoTUnref(T* obj = nullptr) : skstd::unique_ptr>(obj) {}
- T* get() const { return fObj; }
-
- T* reset(T* obj) {
- SkSafeUnref(fObj);
- fObj = obj;
- return obj;
- }
-
- void swap(SkAutoTUnref* other) {
- T* tmp = fObj;
- fObj = other->fObj;
- other->fObj = tmp;
- }
-
- /**
- * Return the hosted object (which may be null), transferring ownership.
- * The reference count is not modified, and the internal ptr is set to NULL
- * so unref() will not be called in our destructor. A subsequent call to
- * detach() will do nothing and return null.
- */
- T* detach() {
- T* obj = fObj;
- fObj = NULL;
- return obj;
- }
-
- /**
- * BlockRef is a type which inherits from B, cannot be created,
- * cannot be deleted, and makes ref and unref private.
- */
- template class BlockRef : public B {
- private:
- BlockRef();
- ~BlockRef();
- void ref() const;
- void unref() const;
- };
-
- /** If T is const, the type returned from operator-> will also be const. */
- typedef typename SkTConstType, SkTIsConst::value>::type BlockRefType;
-
- /**
- * SkAutoTUnref assumes ownership of the ref. As a result, it is an error
- * for the user to ref or unref through SkAutoTUnref. Therefore
- * SkAutoTUnref::operator-> returns BlockRef*. This prevents use of
- * skAutoTUnrefInstance->ref() and skAutoTUnrefInstance->unref().
- */
- BlockRefType *operator->() const {
- return static_cast(fObj);
- }
- operator T*() { return fObj; }
-
-private:
- T* fObj;
+ T* detach() { return this->release(); }
+ operator T*() const { return this->get(); }
};
// Can't use the #define trick below to guard a bare SkAutoTUnref(...) because it's templated. :(
@@ -247,4 +198,31 @@ public:
};
#define SkAutoUnref(...) SK_REQUIRE_LOCAL_VAR(SkAutoUnref)
+// This is a variant of SkRefCnt that's Not Virtual, so weighs 4 bytes instead of 8 or 16.
+// There's only benefit to using this if the deriving class does not otherwise need a vtable.
+template
+class SkNVRefCnt : SkNoncopyable {
+public:
+ SkNVRefCnt() : fRefCnt(1) {}
+ ~SkNVRefCnt() { SkASSERTF(1 == fRefCnt, "NVRefCnt was %d", fRefCnt); }
+
+ // 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;
+ // - ref() doesn't need any barrier;
+ // - unref() needs a release barrier, and an acquire if it's going to call delete.
+
+ bool unique() const { return 1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire); }
+ void ref() const { (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed); }
+ void unref() const {
+ if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
+ SkDEBUGCODE(fRefCnt = 1;) // restore the 1 for our destructor's assert
+ delete (const Derived*)this;
+ }
+ }
+ void deref() const { this->unref(); }
+
+private:
+ mutable int32_t fRefCnt;
+};
+
#endif
diff --git a/gfx/skia/skia/include/core/SkRegion.h b/gfx/skia/skia/include/core/SkRegion.h
index 20366bc638..eb0f1367ab 100644
--- a/gfx/skia/skia/include/core/SkRegion.h
+++ b/gfx/skia/skia/include/core/SkRegion.h
@@ -59,7 +59,6 @@ public:
* resulting region is non-empty.
*/
bool set(const SkRegion& src) {
- SkASSERT(&src);
*this = src;
return !this->isEmpty();
}
diff --git a/gfx/skia/skia/include/core/SkScalar.h b/gfx/skia/skia/include/core/SkScalar.h
index 3056b7297e..4efa8417af 100644
--- a/gfx/skia/skia/include/core/SkScalar.h
+++ b/gfx/skia/skia/include/core/SkScalar.h
@@ -9,70 +9,31 @@
#define SkScalar_DEFINED
#include "SkFixed.h"
-#include "SkFloatingPoint.h"
+#include "../private/SkFloatingPoint.h"
-//#define SK_SUPPORT_DEPRECATED_SCALARROUND
+// TODO: move this sort of check into SkPostConfig.h
+#define SK_SCALAR_IS_DOUBLE 0
+#undef SK_SCALAR_IS_FLOAT
+#define SK_SCALAR_IS_FLOAT 1
-typedef float SkScalar;
-/** SK_Scalar1 is defined to be 1.0 represented as an SkScalar
-*/
-#define SK_Scalar1 (1.0f)
-/** SK_Scalar1 is defined to be 1/2 represented as an SkScalar
-*/
-#define SK_ScalarHalf (0.5f)
-/** SK_ScalarInfinity is defined to be infinity as an SkScalar
-*/
-#define SK_ScalarInfinity SK_FloatInfinity
-/** SK_ScalarNegativeInfinity is defined to be negative infinity as an SkScalar
-*/
-#define SK_ScalarNegativeInfinity SK_FloatNegativeInfinity
-/** SK_ScalarMax is defined to be the largest value representable as an SkScalar
-*/
-#define SK_ScalarMax (3.402823466e+38f)
-/** SK_ScalarMin is defined to be the smallest value representable as an SkScalar
-*/
-#define SK_ScalarMin (-SK_ScalarMax)
-/** SK_ScalarNaN is defined to be 'Not a Number' as an SkScalar
-*/
-#define SK_ScalarNaN SK_FloatNaN
-/** SkScalarIsNaN(n) returns true if argument is not a number
-*/
-static inline bool SkScalarIsNaN(float x) { return x != x; }
+#if SK_SCALAR_IS_FLOAT
-/** Returns true if x is not NaN and not infinite */
-static inline bool SkScalarIsFinite(float x) {
- // We rely on the following behavior of infinities and nans
- // 0 * finite --> 0
- // 0 * infinity --> NaN
- // 0 * NaN --> NaN
- float prod = x * 0;
- // At this point, prod will either be NaN or 0
- // Therefore we can return (prod == prod) or (0 == prod).
- return !SkScalarIsNaN(prod);
-}
+typedef float SkScalar;
-/** SkIntToScalar(n) returns its integer argument as an SkScalar
-*/
-#define SkIntToScalar(n) ((float)(n))
-/** SkFixedToScalar(n) returns its SkFixed argument as an SkScalar
-*/
-#define SkFixedToScalar(x) SkFixedToFloat(x)
-/** SkScalarToFixed(n) returns its SkScalar argument as an SkFixed
-*/
-#define SkScalarToFixed(x) SkFloatToFixed(x)
+#define SK_Scalar1 1.0f
+#define SK_ScalarHalf 0.5f
+#define SK_ScalarSqrt2 1.41421356f
+#define SK_ScalarPI 3.14159265f
+#define SK_ScalarTanPIOver8 0.414213562f
+#define SK_ScalarRoot2Over2 0.707106781f
+#define SK_ScalarMax 3.402823466e+38f
+#define SK_ScalarInfinity SK_FloatInfinity
+#define SK_ScalarNegativeInfinity SK_FloatNegativeInfinity
+#define SK_ScalarNaN SK_FloatNaN
-#define SkScalarToFloat(n) (n)
-#ifndef SK_SCALAR_TO_FLOAT_EXCLUDED
-#define SkFloatToScalar(n) (n)
-#endif
-
-#define SkScalarToDouble(n) (double)(n)
-#define SkDoubleToScalar(n) (float)(n)
-
-/** SkScalarFraction(x) returns the signed fractional part of the argument
-*/
-#define SkScalarFraction(x) sk_float_mod(x, 1.0f)
+#define SkFixedToScalar(x) SkFixedToFloat(x)
+#define SkScalarToFixed(x) SkFloatToFixed(x)
#define SkScalarFloorToScalar(x) sk_float_floor(x)
#define SkScalarCeilToScalar(x) sk_float_ceil(x)
@@ -81,7 +42,111 @@ static inline bool SkScalarIsFinite(float x) {
#define SkScalarFloorToInt(x) sk_float_floor2int(x)
#define SkScalarCeilToInt(x) sk_float_ceil2int(x)
#define SkScalarRoundToInt(x) sk_float_round2int(x)
-#define SkScalarTruncToInt(x) static_cast(x)
+
+#define SkScalarAbs(x) sk_float_abs(x)
+#define SkScalarCopySign(x, y) sk_float_copysign(x, y)
+#define SkScalarMod(x, y) sk_float_mod(x,y)
+#define SkScalarFraction(x) sk_float_mod(x, 1.0f)
+#define SkScalarSqrt(x) sk_float_sqrt(x)
+#define SkScalarPow(b, e) sk_float_pow(b, e)
+
+#define SkScalarSin(radians) (float)sk_float_sin(radians)
+#define SkScalarCos(radians) (float)sk_float_cos(radians)
+#define SkScalarTan(radians) (float)sk_float_tan(radians)
+#define SkScalarASin(val) (float)sk_float_asin(val)
+#define SkScalarACos(val) (float)sk_float_acos(val)
+#define SkScalarATan2(y, x) (float)sk_float_atan2(y,x)
+#define SkScalarExp(x) (float)sk_float_exp(x)
+#define SkScalarLog(x) (float)sk_float_log(x)
+#define SkScalarLog2(x) (float)sk_float_log2(x)
+
+#else // SK_SCALAR_IS_DOUBLE
+
+typedef double SkScalar;
+
+#define SK_Scalar1 1.0
+#define SK_ScalarHalf 0.5
+#define SK_ScalarSqrt2 1.414213562373095
+#define SK_ScalarPI 3.141592653589793
+#define SK_ScalarTanPIOver8 0.4142135623731
+#define SK_ScalarRoot2Over2 0.70710678118655
+#define SK_ScalarMax 1.7976931348623157+308
+#define SK_ScalarInfinity SK_DoubleInfinity
+#define SK_ScalarNegativeInfinity SK_DoubleNegativeInfinity
+#define SK_ScalarNaN SK_DoubleNaN
+
+#define SkFixedToScalar(x) SkFixedToDouble(x)
+#define SkScalarToFixed(x) SkDoubleToFixed(x)
+
+#define SkScalarFloorToScalar(x) floor(x)
+#define SkScalarCeilToScalar(x) ceil(x)
+#define SkScalarRoundToScalar(x) floor((x) + 0.5)
+
+#define SkScalarFloorToInt(x) (int)floor(x)
+#define SkScalarCeilToInt(x) (int)ceil(x)
+#define SkScalarRoundToInt(x) (int)floor((x) + 0.5)
+
+#define SkScalarAbs(x) abs(x)
+#define SkScalarCopySign(x, y) copysign(x, y)
+#define SkScalarMod(x, y) fmod(x,y)
+#define SkScalarFraction(x) fmod(x, 1.0)
+#define SkScalarSqrt(x) sqrt(x)
+#define SkScalarPow(b, e) pow(b, e)
+
+#define SkScalarSin(radians) sin(radians)
+#define SkScalarCos(radians) cos(radians)
+#define SkScalarTan(radians) tan(radians)
+#define SkScalarASin(val) asin(val)
+#define SkScalarACos(val) acos(val)
+#define SkScalarATan2(y, x) atan2(y,x)
+#define SkScalarExp(x) exp(x)
+#define SkScalarLog(x) log(x)
+#define SkScalarLog2(x) log2(x)
+
+#endif
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+#define SkIntToScalar(x) static_cast(x)
+#define SkScalarTruncToInt(x) static_cast(x)
+
+#define SkScalarToFloat(x) static_cast(x)
+#define SkFloatToScalar(x) static_cast(x)
+#define SkScalarToDouble(x) static_cast(x)
+#define SkDoubleToScalar(x) static_cast(x)
+
+#define SK_ScalarMin (-SK_ScalarMax)
+
+static inline bool SkScalarIsNaN(SkScalar x) { return x != x; }
+
+/** Returns true if x is not NaN and not infinite
+ */
+static inline bool SkScalarIsFinite(SkScalar x) {
+ // We rely on the following behavior of infinities and nans
+ // 0 * finite --> 0
+ // 0 * infinity --> NaN
+ // 0 * NaN --> NaN
+ SkScalar prod = x * 0;
+ // At this point, prod will either be NaN or 0
+ return !SkScalarIsNaN(prod);
+}
+
+static inline bool SkScalarsAreFinite(SkScalar a, SkScalar b) {
+ SkScalar prod = 0;
+ prod *= a;
+ prod *= b;
+ // At this point, prod will either be NaN or 0
+ return !SkScalarIsNaN(prod);
+}
+
+static inline bool SkScalarsAreFinite(const SkScalar array[], int count) {
+ SkScalar prod = 0;
+ for (int i = 0; i < count; ++i) {
+ prod *= array[i];
+ }
+ // At this point, prod will either be NaN or 0
+ return !SkScalarIsNaN(prod);
+}
/**
* Variant of SkScalarRoundToInt, that performs the rounding step (adding 0.5) explicitly using
@@ -103,88 +168,38 @@ static inline int SkDScalarRoundToInt(SkScalar x) {
return (int)floor(xx);
}
-/** Returns the absolute value of the specified SkScalar
-*/
-#define SkScalarAbs(x) sk_float_abs(x)
-/** Return x with the sign of y
- */
-#define SkScalarCopySign(x, y) sk_float_copysign(x, y)
-/** Returns the value pinned between 0 and max inclusive
-*/
-inline SkScalar SkScalarClampMax(SkScalar x, SkScalar max) {
- return x < 0 ? 0 : x > max ? max : x;
+static inline SkScalar SkScalarClampMax(SkScalar x, SkScalar max) {
+ x = SkTMin(x, max);
+ x = SkTMax(x, 0);
+ return x;
}
-/** Returns the value pinned between min and max inclusive
-*/
-inline SkScalar SkScalarPin(SkScalar x, SkScalar min, SkScalar max) {
- return x < min ? min : x > max ? max : x;
+
+static inline SkScalar SkScalarPin(SkScalar x, SkScalar min, SkScalar max) {
+ return SkTPin(x, min, max);
}
-/** Returns the specified SkScalar squared (x*x)
-*/
-inline SkScalar SkScalarSquare(SkScalar x) { return x * x; }
-/** Returns the product of two SkScalars
-*/
-#define SkScalarMul(a, b) ((float)(a) * (b))
-/** Returns the product of two SkScalars plus a third SkScalar
-*/
-#define SkScalarMulAdd(a, b, c) ((float)(a) * (b) + (c))
-/** Returns the quotient of two SkScalars (a/b)
-*/
-#define SkScalarDiv(a, b) ((float)(a) / (b))
-/** Returns the mod of two SkScalars (a mod b)
-*/
-#define SkScalarMod(x,y) sk_float_mod(x,y)
-/** Returns the product of the first two arguments, divided by the third argument
-*/
-#define SkScalarMulDiv(a, b, c) ((float)(a) * (b) / (c))
-/** Returns the multiplicative inverse of the SkScalar (1/x)
-*/
+
+SkScalar SkScalarSinCos(SkScalar radians, SkScalar* cosValue);
+
+static inline SkScalar SkScalarSquare(SkScalar x) { return x * x; }
+
+#define SkScalarMul(a, b) ((SkScalar)(a) * (b))
+#define SkScalarMulAdd(a, b, c) ((SkScalar)(a) * (b) + (c))
+#define SkScalarMulDiv(a, b, c) ((SkScalar)(a) * (b) / (c))
#define SkScalarInvert(x) (SK_Scalar1 / (x))
#define SkScalarFastInvert(x) (SK_Scalar1 / (x))
-/** Returns the square root of the SkScalar
-*/
-#define SkScalarSqrt(x) sk_float_sqrt(x)
-/** Returns b to the e
-*/
-#define SkScalarPow(b, e) sk_float_pow(b, e)
-/** Returns the average of two SkScalars (a+b)/2
-*/
-#define SkScalarAve(a, b) (((a) + (b)) * 0.5f)
-/** Returns one half of the specified SkScalar
-*/
-#define SkScalarHalf(a) ((a) * 0.5f)
-
-#define SK_ScalarSqrt2 1.41421356f
-#define SK_ScalarPI 3.14159265f
-#define SK_ScalarTanPIOver8 0.414213562f
-#define SK_ScalarRoot2Over2 0.707106781f
+#define SkScalarAve(a, b) (((a) + (b)) * SK_ScalarHalf)
+#define SkScalarHalf(a) ((a) * SK_ScalarHalf)
#define SkDegreesToRadians(degrees) ((degrees) * (SK_ScalarPI / 180))
#define SkRadiansToDegrees(radians) ((radians) * (180 / SK_ScalarPI))
-float SkScalarSinCos(SkScalar radians, SkScalar* cosValue);
-#define SkScalarSin(radians) (float)sk_float_sin(radians)
-#define SkScalarCos(radians) (float)sk_float_cos(radians)
-#define SkScalarTan(radians) (float)sk_float_tan(radians)
-#define SkScalarASin(val) (float)sk_float_asin(val)
-#define SkScalarACos(val) (float)sk_float_acos(val)
-#define SkScalarATan2(y, x) (float)sk_float_atan2(y,x)
-#define SkScalarExp(x) (float)sk_float_exp(x)
-#define SkScalarLog(x) (float)sk_float_log(x)
-inline SkScalar SkMaxScalar(SkScalar a, SkScalar b) { return a > b ? a : b; }
-inline SkScalar SkMinScalar(SkScalar a, SkScalar b) { return a < b ? a : b; }
+static inline SkScalar SkMaxScalar(SkScalar a, SkScalar b) { return a > b ? a : b; }
+static inline SkScalar SkMinScalar(SkScalar a, SkScalar b) { return a < b ? a : b; }
static inline bool SkScalarIsInt(SkScalar x) {
- return x == (float)(int)x;
+ return x == (SkScalar)(int)x;
}
-// DEPRECATED : use ToInt or ToScalar variant
-#ifdef SK_SUPPORT_DEPRECATED_SCALARROUND
-# define SkScalarFloor(x) SkScalarFloorToInt(x)
-# define SkScalarCeil(x) SkScalarCeilToInt(x)
-# define SkScalarRound(x) SkScalarRoundToInt(x)
-#endif
-
/**
* Returns -1 || 0 || 1 depending on the sign of value:
* -1 if x < 0
@@ -209,7 +224,7 @@ static inline bool SkScalarNearlyZero(SkScalar x,
}
static inline bool SkScalarNearlyEqual(SkScalar x, SkScalar y,
- SkScalar tolerance = SK_ScalarNearlyZero) {
+ SkScalar tolerance = SK_ScalarNearlyZero) {
SkASSERT(tolerance >= 0);
return SkScalarAbs(x-y) <= tolerance;
}
diff --git a/gfx/skia/skia/include/core/SkShader.h b/gfx/skia/skia/include/core/SkShader.h
index e5af40dd7a..34cb648022 100644
--- a/gfx/skia/skia/include/core/SkShader.h
+++ b/gfx/skia/skia/include/core/SkShader.h
@@ -5,7 +5,6 @@
* found in the LICENSE file.
*/
-
#ifndef SkShader_DEFINED
#define SkShader_DEFINED
@@ -20,7 +19,7 @@ class SkPath;
class SkPicture;
class SkXfermode;
class GrContext;
-class GrEffect;
+class GrFragmentProcessor;
/** \class SkShader
*
@@ -34,8 +33,6 @@ class GrEffect;
*/
class SK_API SkShader : public SkFlattenable {
public:
- SK_DECLARE_INST_COUNT(SkShader)
-
SkShader(const SkMatrix* localMatrix = NULL);
virtual ~SkShader();
@@ -47,14 +44,6 @@ public:
*/
const SkMatrix& getLocalMatrix() const { return fLocalMatrix; }
- /**
- * Returns true if the local matrix is not an identity matrix.
- *
- * FIXME: This can be incorrect for a Shader with its own local matrix
- * that is also wrapped via CreateLocalMatrixShader.
- */
- bool hasLocalMatrix() const { return !fLocalMatrix.isIdentity(); }
-
enum TileMode {
/** replicate the edge color if the shader draws outside of its
* original bounds
@@ -73,8 +62,10 @@ public:
/** only draw within the original domain, return 0 everywhere else */
kDecal_TileMode,
#endif
+ };
- kTileModeCount
+ enum {
+ kTileModeCount = kMirror_TileMode + 1
};
// override these in your subclass
@@ -120,14 +111,11 @@ public:
* ContextRec acts as a parameter bundle for creating Contexts.
*/
struct ContextRec {
- ContextRec() : fDevice(NULL), fPaint(NULL), fMatrix(NULL), fLocalMatrix(NULL) {}
- ContextRec(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix)
- : fDevice(&device)
- , fPaint(&paint)
+ ContextRec(const SkPaint& paint, const SkMatrix& matrix, const SkMatrix* localM)
+ : fPaint(&paint)
, fMatrix(&matrix)
- , fLocalMatrix(NULL) {}
+ , fLocalMatrix(localM) {}
- const SkBitmap* fDevice; // the bitmap we are drawing into
const SkPaint* fPaint; // the current paint associated with the draw
const SkMatrix* fMatrix; // the current matrix in the canvas
const SkMatrix* fLocalMatrix; // optional local matrix
@@ -185,6 +173,9 @@ public:
return SkShader::CanCallShadeSpan16(this->getFlags());
}
+ // Notification from blitter::blitMask in case we need to see the non-alpha channels
+ virtual void set3DMask(const SkMask*) {}
+
protected:
// Reference to shader, so we don't have to dupe information.
const SkShader& fShader;
@@ -232,68 +223,17 @@ public:
}
/**
- Gives method bitmap should be read to implement a shader.
- Also determines number and interpretation of "extra" parameters returned
- by asABitmap
+ * 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.
*/
- enum BitmapType {
- kNone_BitmapType, //onIsABitmap(outTexture, outMatrix, xy);
+ }
- kLast_BitmapType = kLinear_BitmapType
- };
- /** Optional methods for shaders that can pretend to be a bitmap/texture
- to play along with opengl. Default just returns kNone_BitmapType and
- ignores the out parameters.
-
- @param outTexture if non-NULL will be the bitmap representing the shader
- after return.
- @param outMatrix if non-NULL will be the matrix to apply to vertices
- to access the bitmap after return.
- @param xy if non-NULL will be the tile modes that should be
- used to access the bitmap after return.
- @param twoPointRadialParams Two extra return values needed for two point
- radial bitmaps. The first is the x-offset of
- the second point and the second is the radius
- about the first point.
- */
- virtual BitmapType asABitmap(SkBitmap* outTexture, SkMatrix* outMatrix,
- TileMode xy[2]) const;
+ bool isABitmap() const {
+ return this->isABitmap(nullptr, nullptr, nullptr);
+ }
/**
* If the shader subclass can be represented as a gradient, asAGradient
@@ -317,7 +257,7 @@ public:
* fPoint[0] and fPoint[1] are the end-points of the gradient
* Radial:
* fPoint[0] and fRadius[0] are the center and radius
- * Radial2:
+ * Conical:
* fPoint[0] and fRadius[0] are the center and radius of the 1st circle
* fPoint[1] and fRadius[1] are the center and radius of the 2nd circle
* Sweep:
@@ -329,7 +269,6 @@ public:
kColor_GradientType,
kLinear_GradientType,
kRadial_GradientType,
- kRadial2_GradientType,
kSweep_GradientType,
kConical_GradientType,
kLast_GradientType = kConical_GradientType
@@ -363,35 +302,43 @@ public:
const SkXfermode* fMode;
};
- virtual bool asACompose(ComposeRec* rec) const { return false; }
+ virtual bool asACompose(ComposeRec*) const { return false; }
/**
- * Returns true if the shader subclass succeeds in creating an effect or if none is required.
- * False is returned if it fails or if there is not an implementation of this method in the
- * shader subclass.
+ * Returns a GrFragmentProcessor that implements the shader for the GPU backend. NULL is
+ * returned if there is no GPU implementation.
*
- * On success an implementation of this method must inspect the SkPaint and set paintColor to
- * the color the effect expects as its input color. If the SkShader wishes to emit a solid
- * color then it should set paintColor to that color and not create an effect. Note that
- * GrColor is always premul. The common patterns are to convert paint's SkColor to GrColor or
- * to extract paint's alpha and replicate it to all channels in paintColor. Upon failure
- * paintColor should not be modified. It is not recommended to specialize the effect to
- * the paint's color as then many GPU shaders may be generated.
+ * The GPU device does not call SkShader::createContext(), instead we pass the view matrix,
+ * local matrix, and filter quality directly.
*
- * The GrContext may be used by the effect to create textures. The GPU device does not
- * call createContext. Instead we pass the SkPaint here in case the shader needs paint info.
+ * The GrContext may be used by the to create textures that are required by the returned
+ * processor.
+ *
+ * The returned GrFragmentProcessor should expect an unpremultiplied input color and
+ * produce a premultiplied output.
*/
- virtual bool asNewEffect(GrContext* context, const SkPaint& paint,
- const SkMatrix* localMatrixOrNull, GrColor* paintColor,
- GrEffect** effect) const;
+ virtual const GrFragmentProcessor* asFragmentProcessor(GrContext*,
+ const SkMatrix& viewMatrix,
+ const SkMatrix* localMatrix,
+ SkFilterQuality) const;
+
+ /**
+ * If the shader can represent its "average" luminance in a single color, return true and
+ * if color is not NULL, return that color. If it cannot, return false and ignore the color
+ * parameter.
+ *
+ * Note: if this returns true, the returned color will always be opaque, as only the RGB
+ * components are used to compute luminance.
+ */
+ bool asLuminanceColor(SkColor*) const;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/**
* If the shader is a custom shader which has data the caller might want, call this function
* to get that data.
*/
- virtual bool asACustomShader(void** customData) const { return false; }
+ virtual bool asACustomShader(void** /* customData */) const { return false; }
#endif
//////////////////////////////////////////////////////////////////////////
@@ -402,6 +349,12 @@ public:
*/
static SkShader* CreateEmptyShader();
+ /**
+ * Call this to create a new shader that just draws the specified color. This should always
+ * draw the same as a paint with this color (and no shader).
+ */
+ static SkShader* CreateColorShader(SkColor);
+
/** Call this to create a new shader that will draw with the specified bitmap.
*
* If the bitmap cannot be used (e.g. has no pixels, or its dimensions
@@ -420,18 +373,26 @@ public:
TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix = NULL);
+ // NOTE: You can create an SkImage Shader with SkImage::newShader().
+
/** Call this to create a new shader that will draw with the specified picture.
*
* @param src The picture to use inside the shader (if not NULL, its ref count
* is incremented). The SkPicture must not be changed after
* successfully creating a picture shader.
- * FIXME: src cannot be const due to SkCanvas::drawPicture
* @param tmx The tiling mode to use when sampling the bitmap in the x-direction.
* @param tmy The tiling mode to use when sampling the bitmap in the y-direction.
+ * @param tile The tile rectangle in picture coordinates: this represents the subset
+ * (or superset) of the picture used when building a tile. It is not
+ * affected by localMatrix and does not imply scaling (only translation
+ * and cropping). If null, the tile rect is considered equal to the picture
+ * bounds.
* @return Returns a new shader object. Note: this function never returns null.
*/
- static SkShader* CreatePictureShader(SkPicture* src, TileMode tmx, TileMode tmy,
- const SkMatrix* localMatrix = NULL);
+ static SkShader* CreatePictureShader(const SkPicture* src,
+ TileMode tmx, TileMode tmy,
+ const SkMatrix* localMatrix,
+ const SkRect* tile);
/**
* Return a shader that will apply the specified localMatrix to the proxy shader.
@@ -454,8 +415,7 @@ public:
SK_DEFINE_FLATTENABLE_TYPE(SkShader)
protected:
- SkShader(SkReadBuffer& );
- virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
+ void flatten(SkWriteBuffer&) const override;
bool computeTotalInverse(const ContextRec&, SkMatrix* totalInverse) const;
@@ -465,6 +425,14 @@ protected:
*/
virtual Context* onCreateContext(const ContextRec&, void* storage) const;
+ virtual bool onAsLuminanceColor(SkColor*) const {
+ return false;
+ }
+
+ virtual bool onIsABitmap(SkBitmap*, SkMatrix*, TileMode[2]) const {
+ return false;
+ }
+
private:
// This is essentially const, but not officially so it can be modified in
// constructors.
@@ -472,6 +440,7 @@ private:
// So the SkLocalMatrixShader can whack fLocalMatrix in its SkReadBuffer constructor.
friend class SkLocalMatrixShader;
+ friend class SkBitmapProcShader; // for computeTotalInverse()
typedef SkFlattenable INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkStream.h b/gfx/skia/skia/include/core/SkStream.h
index 516b036a55..2279f9ff10 100644
--- a/gfx/skia/skia/include/core/SkStream.h
+++ b/gfx/skia/skia/include/core/SkStream.h
@@ -36,17 +36,17 @@ class SkStreamMemory;
* no more data (at EOF or hit an error). The caller should *not* call again
* in hopes of fulfilling more of the request.
*/
-class SK_API SkStream : public SkRefCnt { //TODO: remove SkRefCnt
+class SK_API SkStream : public SkNoncopyable {
public:
+ virtual ~SkStream() {}
+
/**
* Attempts to open the specified file, and return a stream to it (using
- * mmap if available). On success, the caller must call unref() on the
- * returned object. On failure, returns NULL.
+ * mmap if available). On success, the caller is responsible for deleting.
+ * On failure, returns NULL.
*/
static SkStreamAsset* NewFromFile(const char path[]);
- SK_DECLARE_INST_COUNT(SkStream)
-
/** Reads or skips size number of bytes.
* If buffer == NULL, skip size bytes, return how many were skipped.
* If buffer != NULL, copy size bytes into buffer, return how many were copied.
@@ -63,6 +63,20 @@ public:
return this->read(NULL, size);
}
+ /**
+ * Attempt to peek at size bytes.
+ * If this stream supports peeking, and it can peek size bytes, copy size
+ * bytes into buffer, and return true.
+ * If the stream does not support peeking, or cannot peek size bytes,
+ * return false and leave buffer unchanged.
+ * The stream is guaranteed to be in the same visible state after this
+ * call, regardless of success or failure.
+ * @param buffer Must not be NULL. Destination to copy bytes.
+ * @param size Number of bytes to copy.
+ * @return Whether the peek was performed.
+ */
+ virtual bool peek(void* /* buffer */, size_t /* size */) const { return false; }
+
/** Returns true when all the bytes in the stream have been read.
* This may return true early (when there are no more bytes to be read)
* or late (after the first unsuccessful read).
@@ -81,12 +95,6 @@ public:
SkScalar readScalar();
size_t readPackedUInt();
- /**
- * Reconstitute an SkData object that was written to the stream
- * using SkWStream::writeData().
- */
- SkData* readData();
-
//SkStreamRewindable
/** Rewinds to the beginning of the stream. Returns true if the stream is known
* to be at the beginning after this call returns.
@@ -108,13 +116,13 @@ public:
* If an attempt is made to seek past the end of the stream, the position will be set
* to the end of the stream.
*/
- virtual bool seek(size_t position) { return false; }
+ virtual bool seek(size_t /*position*/) { return false; }
/** Seeks to an relative offset in the stream. If this cannot be done, returns false.
* If an attempt is made to move to a position outside the stream, the position will be set
* to the closest point within the stream (beginning or end).
*/
- virtual bool move(long offset) { return false; }
+ virtual bool move(long /*offset*/) { return false; }
/** Duplicates this stream. If this cannot be done, returns NULL.
* The returned stream will be positioned the same as this stream.
@@ -131,53 +139,48 @@ public:
/** Returns the starting address for the data. If this cannot be done, returns NULL. */
//TODO: replace with virtual const SkData* getData()
virtual const void* getMemoryBase() { return NULL; }
-
-private:
- typedef SkRefCnt INHERITED;
};
/** SkStreamRewindable is a SkStream for which rewind and duplicate are required. */
class SK_API SkStreamRewindable : public SkStream {
public:
- virtual bool rewind() SK_OVERRIDE = 0;
- virtual SkStreamRewindable* duplicate() const SK_OVERRIDE = 0;
+ bool rewind() override = 0;
+ SkStreamRewindable* duplicate() const override = 0;
};
/** SkStreamSeekable is a SkStreamRewindable for which position, seek, move, and fork are required. */
class SK_API SkStreamSeekable : public SkStreamRewindable {
public:
- virtual SkStreamSeekable* duplicate() const SK_OVERRIDE = 0;
+ SkStreamSeekable* duplicate() const override = 0;
- virtual bool hasPosition() const SK_OVERRIDE { return true; }
- virtual size_t getPosition() const SK_OVERRIDE = 0;
- virtual bool seek(size_t position) SK_OVERRIDE = 0;
- virtual bool move(long offset) SK_OVERRIDE = 0;
- virtual SkStreamSeekable* fork() const SK_OVERRIDE = 0;
+ bool hasPosition() const override { return true; }
+ size_t getPosition() const override = 0;
+ bool seek(size_t position) override = 0;
+ bool move(long offset) override = 0;
+ SkStreamSeekable* fork() const override = 0;
};
/** SkStreamAsset is a SkStreamSeekable for which getLength is required. */
class SK_API SkStreamAsset : public SkStreamSeekable {
public:
- virtual SkStreamAsset* duplicate() const SK_OVERRIDE = 0;
- virtual SkStreamAsset* fork() const SK_OVERRIDE = 0;
+ SkStreamAsset* duplicate() const override = 0;
+ SkStreamAsset* fork() const override = 0;
- virtual bool hasLength() const SK_OVERRIDE { return true; }
- virtual size_t getLength() const SK_OVERRIDE = 0;
+ bool hasLength() const override { return true; }
+ size_t getLength() const override = 0;
};
/** SkStreamMemory is a SkStreamAsset for which getMemoryBase is required. */
class SK_API SkStreamMemory : public SkStreamAsset {
public:
- virtual SkStreamMemory* duplicate() const SK_OVERRIDE = 0;
- virtual SkStreamMemory* fork() const SK_OVERRIDE = 0;
+ SkStreamMemory* duplicate() const override = 0;
+ SkStreamMemory* fork() const override = 0;
- virtual const void* getMemoryBase() SK_OVERRIDE = 0;
+ const void* getMemoryBase() override = 0;
};
class SK_API SkWStream : SkNoncopyable {
public:
- SK_DECLARE_INST_COUNT_ROOT(SkWStream)
-
virtual ~SkWStream();
/** Called to write bytes to a SkWStream. Returns true on success
@@ -209,16 +212,6 @@ public:
bool writeStream(SkStream* input, size_t length);
- /**
- * Append an SkData object to the stream, such that it can be read
- * out of the stream using SkStream::readData().
- *
- * Note that the encoding method used to write the SkData object
- * to the stream may change over time. This method DOES NOT
- * just write the raw content of the SkData object to the stream.
- */
- bool writeData(const SkData*);
-
/**
* This returns the number of bytes in the stream required to store
* 'value'.
@@ -231,13 +224,9 @@ public:
#include "SkString.h"
#include
-struct SkFILE;
-
/** A stream that wraps a C FILE* file stream. */
class SK_API SkFILEStream : public SkStreamAsset {
public:
- SK_DECLARE_INST_COUNT(SkFILEStream)
-
/** Initialize the stream by calling sk_fopen on the specified path.
* This internal stream will be closed in the destructor.
*/
@@ -264,23 +253,23 @@ public:
*/
void setPath(const char path[]);
- virtual size_t read(void* buffer, size_t size) SK_OVERRIDE;
- virtual bool isAtEnd() const SK_OVERRIDE;
+ size_t read(void* buffer, size_t size) override;
+ bool isAtEnd() const override;
- virtual bool rewind() SK_OVERRIDE;
- virtual SkStreamAsset* duplicate() const SK_OVERRIDE;
+ bool rewind() override;
+ SkStreamAsset* duplicate() const override;
- virtual size_t getPosition() const SK_OVERRIDE;
- virtual bool seek(size_t position) SK_OVERRIDE;
- virtual bool move(long offset) SK_OVERRIDE;
- virtual SkStreamAsset* fork() const SK_OVERRIDE;
+ size_t getPosition() const override;
+ bool seek(size_t position) override;
+ bool move(long offset) override;
+ SkStreamAsset* fork() const override;
- virtual size_t getLength() const SK_OVERRIDE;
+ size_t getLength() const override;
- virtual const void* getMemoryBase() SK_OVERRIDE;
+ const void* getMemoryBase() override;
private:
- SkFILE* fFILE;
+ FILE* fFILE;
SkString fName;
Ownership fOwnership;
// fData is lazilly initialized when needed.
@@ -291,8 +280,6 @@ private:
class SK_API SkMemoryStream : public SkStreamMemory {
public:
- SK_DECLARE_INST_COUNT(SkMemoryStream)
-
SkMemoryStream();
/** We allocate (and free) the memory. Write to it via getMemoryBase() */
@@ -334,22 +321,23 @@ public:
void skipToAlign4();
const void* getAtPos();
- size_t peek() const { return fOffset; }
- virtual size_t read(void* buffer, size_t size) SK_OVERRIDE;
- virtual bool isAtEnd() const SK_OVERRIDE;
+ size_t read(void* buffer, size_t size) override;
+ bool isAtEnd() const override;
- virtual bool rewind() SK_OVERRIDE;
- virtual SkMemoryStream* duplicate() const SK_OVERRIDE;
+ bool peek(void* buffer, size_t size) const override;
- virtual size_t getPosition() const SK_OVERRIDE;
- virtual bool seek(size_t position) SK_OVERRIDE;
- virtual bool move(long offset) SK_OVERRIDE;
- virtual SkMemoryStream* fork() const SK_OVERRIDE;
+ bool rewind() override;
+ SkMemoryStream* duplicate() const override;
- virtual size_t getLength() const SK_OVERRIDE;
+ size_t getPosition() const override;
+ bool seek(size_t position) override;
+ bool move(long offset) override;
+ SkMemoryStream* fork() const override;
- virtual const void* getMemoryBase() SK_OVERRIDE;
+ size_t getLength() const override;
+
+ const void* getMemoryBase() override;
private:
SkData* fData;
@@ -362,8 +350,6 @@ private:
class SK_API SkFILEWStream : public SkWStream {
public:
- SK_DECLARE_INST_COUNT(SkFILEWStream)
-
SkFILEWStream(const char path[]);
virtual ~SkFILEWStream();
@@ -371,23 +357,21 @@ public:
*/
bool isValid() const { return fFILE != NULL; }
- virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
- virtual void flush() SK_OVERRIDE;
- virtual size_t bytesWritten() const SK_OVERRIDE;
+ bool write(const void* buffer, size_t size) override;
+ void flush() override;
+ size_t bytesWritten() const override;
private:
- SkFILE* fFILE;
+ FILE* fFILE;
typedef SkWStream INHERITED;
};
class SkMemoryWStream : public SkWStream {
public:
- SK_DECLARE_INST_COUNT(SkMemoryWStream)
-
SkMemoryWStream(void* buffer, size_t size);
- virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
- virtual size_t bytesWritten() const SK_OVERRIDE { return fBytesWritten; }
+ bool write(const void* buffer, size_t size) override;
+ size_t bytesWritten() const override { return fBytesWritten; }
private:
char* fBuffer;
@@ -399,13 +383,11 @@ private:
class SK_API SkDynamicMemoryWStream : public SkWStream {
public:
- SK_DECLARE_INST_COUNT(SkDynamicMemoryWStream)
-
SkDynamicMemoryWStream();
virtual ~SkDynamicMemoryWStream();
- virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
- virtual size_t bytesWritten() const SK_OVERRIDE { return fBytesWritten; }
+ bool write(const void* buffer, size_t size) override;
+ size_t bytesWritten() const override { return fBytesWritten; }
// random access write
// modifies stream and returns true if offset + size is less than or equal to getOffset()
bool write(const void* buffer, size_t offset, size_t size);
@@ -414,6 +396,7 @@ public:
// copy what has been written to the stream into dst
void copyTo(void* dst) const;
+ void writeToStream(SkWStream* dst) const;
/**
* Return a copy of the data written so far. This call is responsible for
@@ -447,12 +430,11 @@ private:
class SK_API SkDebugWStream : public SkWStream {
public:
SkDebugWStream() : fBytesWritten(0) {}
- SK_DECLARE_INST_COUNT(SkDebugWStream)
// overrides
- virtual bool write(const void* buffer, size_t size) SK_OVERRIDE;
- virtual void newline() SK_OVERRIDE;
- virtual size_t bytesWritten() const SK_OVERRIDE { return fBytesWritten; }
+ bool write(const void* buffer, size_t size) override;
+ void newline() override;
+ size_t bytesWritten() const override { return fBytesWritten; }
private:
size_t fBytesWritten;
diff --git a/gfx/skia/skia/include/core/SkString.h b/gfx/skia/skia/include/core/SkString.h
index bc06cb0aba..9229d808a6 100644
--- a/gfx/skia/skia/include/core/SkString.h
+++ b/gfx/skia/skia/include/core/SkString.h
@@ -39,6 +39,12 @@ static int SkStrFind(const char string[], const char substring[]) {
return SkToS32(first - &string[0]);
}
+static int SkStrFindLastOf(const char string[], const char subchar) {
+ const char* last = strrchr(string, subchar);
+ if (NULL == last) return -1;
+ return SkToS32(last - &string[0]);
+}
+
static bool SkStrContains(const char string[], const char substring[]) {
SkASSERT(string);
SkASSERT(substring);
@@ -58,7 +64,23 @@ static inline char *SkStrDup(const char string[]) {
return ret;
}
-
+/*
+ * The SkStrAppend... methods will write into the provided buffer, assuming it is large enough.
+ * Each method has an associated const (e.g. SkStrAppendU32_MaxSize) which will be the largest
+ * value needed for that method's buffer.
+ *
+ * char storage[SkStrAppendU32_MaxSize];
+ * SkStrAppendU32(storage, value);
+ *
+ * Note : none of the SkStrAppend... methods write a terminating 0 to their buffers. Instead,
+ * the methods return the ptr to the end of the written part of the buffer. This can be used
+ * to compute the length, and/or know where to write a 0 if that is desired.
+ *
+ * char storage[SkStrAppendU32_MaxSize + 1];
+ * char* stop = SkStrAppendU32(storage, value);
+ * size_t len = stop - storage;
+ * *stop = 0; // valid, since storage was 1 byte larger than the max.
+ */
#define SkStrAppendU32_MaxSize 10
char* SkStrAppendU32(char buffer[], uint32_t);
@@ -136,6 +158,9 @@ public:
int find(const char substring[]) const {
return SkStrFind(fRec->data(), substring);
}
+ int findLastOf(const char subchar) const {
+ return SkStrFindLastOf(fRec->data(), subchar);
+ }
friend bool operator==(const SkString& a, const SkString& b) {
return a.equals(b);
@@ -153,6 +178,7 @@ public:
char& operator[](size_t n) { return this->writable_str()[n]; }
void reset();
+ /** Destructive resize, does not preserve contents. */
void resize(size_t len) { this->set(NULL, len); }
void set(const SkString& src) { *this = src; }
void set(const char text[]);
@@ -195,6 +221,7 @@ public:
void appendf(const char format[], ...) SK_PRINTF_LIKE(2, 3);
void appendVAList(const char format[], va_list);
void prependf(const char format[], ...) SK_PRINTF_LIKE(2, 3);
+ void prependVAList(const char format[], va_list);
void remove(size_t offset, size_t length);
@@ -221,7 +248,6 @@ private:
Rec* fRec;
#ifdef SK_DEBUG
- const char* fStr;
void validate() const;
#else
void validate() const {}
diff --git a/gfx/skia/skia/include/core/SkStrokeRec.h b/gfx/skia/skia/include/core/SkStrokeRec.h
index 0c5892f625..32e5440563 100644
--- a/gfx/skia/skia/include/core/SkStrokeRec.h
+++ b/gfx/skia/skia/include/core/SkStrokeRec.h
@@ -12,6 +12,7 @@
class SkPath;
+SK_BEGIN_REQUIRE_DENSE
class SkStrokeRec {
public:
enum InitStyle {
@@ -19,10 +20,8 @@ public:
kFill_InitStyle
};
SkStrokeRec(InitStyle style);
-
- SkStrokeRec(const SkStrokeRec&);
- SkStrokeRec(const SkPaint&, SkPaint::Style);
- explicit SkStrokeRec(const SkPaint&);
+ SkStrokeRec(const SkPaint&, SkPaint::Style, SkScalar resScale = 1);
+ explicit SkStrokeRec(const SkPaint&, SkScalar resScale = 1);
enum Style {
kHairline_Style,
@@ -37,8 +36,8 @@ public:
Style getStyle() const;
SkScalar getWidth() const { return fWidth; }
SkScalar getMiter() const { return fMiterLimit; }
- SkPaint::Cap getCap() const { return fCap; }
- SkPaint::Join getJoin() const { return fJoin; }
+ SkPaint::Cap getCap() const { return (SkPaint::Cap)fCap; }
+ SkPaint::Join getJoin() const { return (SkPaint::Join)fJoin; }
bool isHairlineStyle() const {
return kHairline_Style == this->getStyle();
@@ -64,6 +63,11 @@ public:
fMiterLimit = miterLimit;
}
+ void setResScale(SkScalar rs) {
+ SkASSERT(rs > 0 && SkScalarIsFinite(rs));
+ fResScale = rs;
+ }
+
/**
* Returns true if this specifes any thick stroking, i.e. applyToPath()
* will return true.
@@ -85,23 +89,43 @@ public:
*/
bool applyToPath(SkPath* dst, const SkPath& src) const;
- bool operator==(const SkStrokeRec& other) const {
- return fWidth == other.fWidth &&
- fMiterLimit == other.fMiterLimit &&
- fCap == other.fCap &&
- fJoin == other.fJoin &&
- fStrokeAndFill == other.fStrokeAndFill;
+ /**
+ * Apply these stroke parameters to a paint.
+ */
+ void applyToPaint(SkPaint* paint) const;
+
+ /**
+ * Compare if two SkStrokeRecs have an equal effect on a path.
+ * Equal SkStrokeRecs produce equal paths. Equality of produced
+ * paths does not take the ResScale parameter into account.
+ */
+ bool hasEqualEffect(const SkStrokeRec& other) const {
+ if (!this->needToApply()) {
+ return this->getStyle() == other.getStyle();
+ }
+ return fWidth == other.fWidth &&
+ fMiterLimit == other.fMiterLimit &&
+ fCap == other.fCap &&
+ fJoin == other.fJoin &&
+ fStrokeAndFill == other.fStrokeAndFill;
}
private:
- void init(const SkPaint& paint, SkPaint::Style style);
-
+ void init(const SkPaint&, SkPaint::Style, SkScalar resScale);
+ SkScalar fResScale;
SkScalar fWidth;
SkScalar fMiterLimit;
- SkPaint::Cap fCap;
- SkPaint::Join fJoin;
- bool fStrokeAndFill;
+ // The following three members are packed together into a single u32.
+ // This is to avoid unnecessary padding and ensure binary equality for
+ // hashing (because the padded areas might contain garbage values).
+ //
+ // fCap and fJoin are larger than needed to avoid having to initialize
+ // any pad values
+ uint32_t fCap : 16; // SkPaint::Cap
+ uint32_t fJoin : 15; // SkPaint::Join
+ uint32_t fStrokeAndFill : 1; // bool
};
+SK_END_REQUIRE_DENSE
#endif
diff --git a/gfx/skia/skia/include/core/SkSurface.h b/gfx/skia/skia/include/core/SkSurface.h
index cb5133ae00..57527ed33a 100644
--- a/gfx/skia/skia/include/core/SkSurface.h
+++ b/gfx/skia/skia/include/core/SkSurface.h
@@ -10,6 +10,7 @@
#include "SkRefCnt.h"
#include "SkImage.h"
+#include "SkSurfaceProps.h"
class SkCanvas;
class SkPaint;
@@ -23,10 +24,23 @@ class GrRenderTarget;
*
* To draw into a canvas, first create the appropriate type of Surface, and
* then request the canvas from the surface.
+ *
+ * SkSurface always has non-zero dimensions. If there is a request for a new surface, and either
+ * of the requested dimensions are zero, then NULL will be returned.
*/
class SK_API SkSurface : public SkRefCnt {
public:
- SK_DECLARE_INST_COUNT(SkSurface)
+ /**
+ * Indicates whether a new surface or image should count against a cache budget. Currently this
+ * is only used by the GPU backend (sw-raster surfaces and images are never counted against the
+ * resource cache budget.)
+ */
+ enum Budgeted {
+ /** The surface or image does not count against the cache budget. */
+ kNo_Budgeted,
+ /** The surface or image counts against the cache budget. */
+ kYes_Budgeted
+ };
/**
* Create a new surface, using the specified pixels/rowbytes as its
@@ -35,7 +49,8 @@ public:
* If the requested surface cannot be created, or the request is not a
* supported configuration, NULL will be returned.
*/
- static SkSurface* NewRasterDirect(const SkImageInfo&, void* pixels, size_t rowBytes);
+ static SkSurface* NewRasterDirect(const SkImageInfo&, void* pixels, size_t rowBytes,
+ const SkSurfaceProps* = NULL);
/**
* The same as NewRasterDirect, but also accepts a call-back routine, which is invoked
@@ -43,7 +58,7 @@ public:
*/
static SkSurface* NewRasterDirectReleaseProc(const SkImageInfo&, void* pixels, size_t rowBytes,
void (*releaseProc)(void* pixels, void* context),
- void* context);
+ void* context, const SkSurfaceProps* = NULL);
/**
* Return a new surface, with the memory for the pixels automatically
@@ -52,70 +67,59 @@ public:
* If the requested surface cannot be created, or the request is not a
* supported configuration, NULL will be returned.
*/
- static SkSurface* NewRaster(const SkImageInfo&);
+ static SkSurface* NewRaster(const SkImageInfo&, const SkSurfaceProps* = NULL);
/**
* Helper version of NewRaster. It creates a SkImageInfo with the
* specified width and height, and populates the rest of info to match
* pixels in SkPMColor format.
*/
- static SkSurface* NewRasterPMColor(int width, int height) {
- return NewRaster(SkImageInfo::MakeN32Premul(width, height));
+ static SkSurface* NewRasterN32Premul(int width, int height, const SkSurfaceProps* props = NULL) {
+ return NewRaster(SkImageInfo::MakeN32Premul(width, height), props);
}
- /**
- * Text rendering modes that can be passed to NewRenderTarget*
- */
- enum TextRenderMode {
- /**
- * This will use the standard text rendering method
- */
- kStandard_TextRenderMode,
- /**
- * This will use signed distance fields for text rendering when possible
- */
- kDistanceField_TextRenderMode,
- };
-
- enum RenderTargetFlags {
- kNone_RenderTargetFlag = 0x0,
- /*
- * By default a RenderTarget-based surface will be cleared on creation.
- * Pass in this flag to prevent the clear from happening.
- */
- kDontClear_RenderTargetFlag = 0x01,
- };
-
/**
* Return a new surface using the specified render target.
*/
- static SkSurface* NewRenderTargetDirect(GrRenderTarget*,
- TextRenderMode trm = kStandard_TextRenderMode,
- RenderTargetFlags flags = kNone_RenderTargetFlag);
+ static SkSurface* NewRenderTargetDirect(GrRenderTarget*, const SkSurfaceProps*);
+
+ static SkSurface* NewRenderTargetDirect(GrRenderTarget* target) {
+ return NewRenderTargetDirect(target, NULL);
+ }
+
+ /**
+ * Used to wrap a pre-existing backend 3D API texture as a SkSurface. The kRenderTarget flag
+ * must be set on GrBackendTextureDesc for this to succeed. Skia will not assume ownership
+ * of the texture and the client must ensure the texture is valid for the lifetime of the
+ * SkSurface.
+ */
+ static SkSurface* NewFromBackendTexture(GrContext*, const GrBackendTextureDesc&,
+ const SkSurfaceProps*);
+ // Legacy alias
+ static SkSurface* NewWrappedRenderTarget(GrContext* ctx, const GrBackendTextureDesc& desc,
+ const SkSurfaceProps* props) {
+ return NewFromBackendTexture(ctx, desc, props);
+ }
+
+
+ /**
+ * Used to wrap a pre-existing 3D API rendering target as a SkSurface. Skia will not assume
+ * ownership of the render target and the client must ensure the render target is valid for the
+ * lifetime of the SkSurface.
+ */
+ static SkSurface* NewFromBackendRenderTarget(GrContext*, const GrBackendRenderTargetDesc&,
+ const SkSurfaceProps*);
/**
* Return a new surface whose contents will be drawn to an offscreen
* render target, allocated by the surface.
*/
- static SkSurface* NewRenderTarget(GrContext*, const SkImageInfo&, int sampleCount = 0,
- TextRenderMode trm = kStandard_TextRenderMode,
- RenderTargetFlags flags = kNone_RenderTargetFlag);
+ static SkSurface* NewRenderTarget(GrContext*, Budgeted, const SkImageInfo&, int sampleCount,
+ const SkSurfaceProps* = NULL);
- /**
- * Return a new surface whose contents will be drawn to an offscreen
- * render target, allocated by the surface from the scratch texture pool
- * managed by the GrContext. The scratch texture pool serves the purpose
- * of retaining textures after they are no longer in use in order to
- * re-use them later without having to re-allocate. Scratch textures
- * should be used in cases where high turnover is expected. This allows,
- * for example, the copy on write to recycle a texture from a recently
- * released SkImage snapshot of the surface.
- * Note: Scratch textures count against the GrContext's cached resource
- * budget.
- */
- static SkSurface* NewScratchRenderTarget(GrContext*, const SkImageInfo&, int sampleCount = 0,
- TextRenderMode trm = kStandard_TextRenderMode,
- RenderTargetFlags flags = kNone_RenderTargetFlag);
+ static SkSurface* NewRenderTarget(GrContext* gr, Budgeted b, const SkImageInfo& info) {
+ return NewRenderTarget(gr, b, info, 0, NULL);
+ }
int width() const { return fWidth; }
int height() const { return fHeight; }
@@ -150,9 +154,45 @@ public:
/**
* Call this if the contents are about to change. This will (lazily) force a new
* value to be returned from generationID() when it is called next.
+ *
+ * CAN WE DEPRECATE THIS?
*/
void notifyContentWillChange(ContentChangeMode mode);
+ enum BackendHandleAccess {
+ kFlushRead_BackendHandleAccess, //!< caller may read from the backend object
+ kFlushWrite_BackendHandleAccess, //!< caller may write to the backend object
+ kDiscardWrite_BackendHandleAccess, //!< caller must over-write the entire backend object
+ };
+
+ /*
+ * These are legacy aliases which will be removed soon
+ */
+ static const BackendHandleAccess kFlushRead_TextureHandleAccess =
+ kFlushRead_BackendHandleAccess;
+ static const BackendHandleAccess kFlushWrite_TextureHandleAccess =
+ kFlushWrite_BackendHandleAccess;
+ static const BackendHandleAccess kDiscardWrite_TextureHandleAccess =
+ kDiscardWrite_BackendHandleAccess;
+
+
+ /**
+ * Retrieves the backend API handle of the texture used by this surface, or 0 if the surface
+ * is not backed by a GPU texture.
+ *
+ * The returned texture-handle is only valid until the next draw-call into the surface,
+ * or the surface is deleted.
+ */
+ GrBackendObject getTextureHandle(BackendHandleAccess);
+
+ /**
+ * Retrieves the backend API handle of the RenderTarget backing this surface. Callers must
+ * ensure this function returns 'true' or else the GrBackendObject will be invalid
+ *
+ * In OpenGL this will return the FramebufferObject ID.
+ */
+ bool getRenderTargetHandle(GrBackendObject*, BackendHandleAccess);
+
/**
* Return a canvas that will draw into this surface. This will always
* return the same canvas for a given surface, and is manged/owned by the
@@ -179,12 +219,14 @@ public:
/**
* Returns an image of the current state of the surface pixels up to this
* point. Subsequent changes to the surface (by drawing into its canvas)
- * will not be reflected in this image.
+ * will not be reflected in this image. If a copy must be made the Budgeted
+ * parameter controls whether it counts against the resource budget
+ * (currently for the gpu backend only).
*/
- SkImage* newImageSnapshot();
+ SkImage* newImageSnapshot(Budgeted = kYes_Budgeted);
/**
- * Thought the caller could get a snapshot image explicitly, and draw that,
+ * Though the caller could get a snapshot image explicitly, and draw that,
* it seems that directly drawing a surface into another canvas might be
* a common pattern, and that we could possibly be more efficient, since
* we'd know that the "snapshot" need only live until we've handed it off
@@ -204,9 +246,32 @@ public:
*/
const void* peekPixels(SkImageInfo* info, size_t* rowBytes);
+ /**
+ * Copy the pixels from the surface into the specified buffer (pixels + rowBytes),
+ * converting them into the requested format (dstInfo). The surface pixels are read
+ * starting at the specified (srcX,srcY) location.
+ *
+ * The specified ImageInfo and (srcX,srcY) offset specifies a source rectangle
+ *
+ * srcR.setXYWH(srcX, srcY, dstInfo.width(), dstInfo.height());
+ *
+ * srcR is intersected with the bounds of the base-layer. If this intersection is not empty,
+ * then we have two sets of pixels (of equal size). Replace the dst pixels with the
+ * corresponding src pixels, performing any colortype/alphatype transformations needed
+ * (in the case where the src and dst have different colortypes or alphatypes).
+ *
+ * This call can fail, returning false, for several reasons:
+ * - If srcR does not intersect the surface bounds.
+ * - If the requested colortype/alphatype cannot be converted from the surface's types.
+ */
+ bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
+ int srcX, int srcY);
+
+ const SkSurfaceProps& props() const { return fProps; }
+
protected:
- SkSurface(int width, int height);
- SkSurface(const SkImageInfo&);
+ SkSurface(int width, int height, const SkSurfaceProps*);
+ SkSurface(const SkImageInfo&, const SkSurfaceProps*);
// called by subclass if their contents have changed
void dirtyGenerationID() {
@@ -214,9 +279,10 @@ protected:
}
private:
- const int fWidth;
- const int fHeight;
- uint32_t fGenerationID;
+ const SkSurfaceProps fProps;
+ const int fWidth;
+ const int fHeight;
+ uint32_t fGenerationID;
typedef SkRefCnt INHERITED;
};
diff --git a/gfx/skia/skia/include/core/SkSurfaceProps.h b/gfx/skia/skia/include/core/SkSurfaceProps.h
new file mode 100644
index 0000000000..735561f1dc
--- /dev/null
+++ b/gfx/skia/skia/include/core/SkSurfaceProps.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2014 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef SkSurfaceProps_DEFINED
+#define SkSurfaceProps_DEFINED
+
+#include "SkTypes.h"
+
+/**
+ * Description of how the LCD strips are arranged for each pixel. If this is unknown, or the
+ * pixels are meant to be "portable" and/or transformed before showing (e.g. rotated, scaled)
+ * then use kUnknown_SkPixelGeometry.
+ */
+enum SkPixelGeometry {
+ kUnknown_SkPixelGeometry,
+ kRGB_H_SkPixelGeometry,
+ kBGR_H_SkPixelGeometry,
+ kRGB_V_SkPixelGeometry,
+ kBGR_V_SkPixelGeometry,
+};
+
+// Returns true iff geo is a known geometry and is RGB.
+static inline bool SkPixelGeometryIsRGB(SkPixelGeometry geo) {
+ return kRGB_H_SkPixelGeometry == geo || kRGB_V_SkPixelGeometry == geo;
+}
+
+// Returns true iff geo is a known geometry and is BGR.
+static inline bool SkPixelGeometryIsBGR(SkPixelGeometry geo) {
+ return kBGR_H_SkPixelGeometry == geo || kBGR_V_SkPixelGeometry == geo;
+}
+
+// Returns true iff geo is a known geometry and is horizontal.
+static inline bool SkPixelGeometryIsH(SkPixelGeometry geo) {
+ return kRGB_H_SkPixelGeometry == geo || kBGR_H_SkPixelGeometry == geo;
+}
+
+// Returns true iff geo is a known geometry and is vertical.
+static inline bool SkPixelGeometryIsV(SkPixelGeometry geo) {
+ return kRGB_V_SkPixelGeometry == geo || kBGR_V_SkPixelGeometry == geo;
+}
+
+/**
+ * Describes properties and constraints of a given SkSurface. The rendering engine can parse these
+ * during drawing, and can sometimes optimize its performance (e.g. disabling an expensive
+ * feature).
+ */
+class SK_API SkSurfaceProps {
+public:
+ enum Flags {
+ kDisallowAntiAlias_Flag = 1 << 0,
+ kDisallowDither_Flag = 1 << 1,
+ kUseDeviceIndependentFonts_Flag = 1 << 2,
+ };
+ /** Deprecated alias used by Chromium. Will be removed. */
+ static const Flags kUseDistanceFieldFonts_Flag = kUseDeviceIndependentFonts_Flag;
+
+ SkSurfaceProps(uint32_t flags, SkPixelGeometry);
+
+ enum InitType {
+ kLegacyFontHost_InitType
+ };
+ SkSurfaceProps(InitType);
+ SkSurfaceProps(uint32_t flags, InitType);
+ SkSurfaceProps(const SkSurfaceProps& other);
+
+ uint32_t flags() const { return fFlags; }
+ SkPixelGeometry pixelGeometry() const { return fPixelGeometry; }
+
+ bool isDisallowAA() const { return SkToBool(fFlags & kDisallowAntiAlias_Flag); }
+ bool isDisallowDither() const { return SkToBool(fFlags & kDisallowDither_Flag); }
+ bool isUseDeviceIndependentFonts() const {
+ return SkToBool(fFlags & kUseDeviceIndependentFonts_Flag);
+ }
+
+private:
+ SkSurfaceProps();
+
+ uint32_t fFlags;
+ SkPixelGeometry fPixelGeometry;
+};
+
+#endif
diff --git a/gfx/skia/skia/include/core/SkTArray.h b/gfx/skia/skia/include/core/SkTArray.h
index 6c76c78094..401f7084d6 100644
--- a/gfx/skia/skia/include/core/SkTArray.h
+++ b/gfx/skia/skia/include/core/SkTArray.h
@@ -8,9 +8,10 @@
#ifndef SkTArray_DEFINED
#define SkTArray_DEFINED
-#include
+#include "../private/SkTemplates.h"
#include "SkTypes.h"
-#include "SkTemplates.h"
+
+#include
template class SkTArray;
@@ -31,18 +32,18 @@ inline void copyAndDelete(SkTArray* self, char* newMemArray) {
template
inline void copy(SkTArray* self, int dst, int src) {
- SkNEW_PLACEMENT_ARGS(&self->fItemArray[dst], T, (self->fItemArray[src]));
+ new (&self->fItemArray[dst]) T(self->fItemArray[src]);
}
template
inline void copy(SkTArray* self, const T* array) {
for (int i = 0; i < self->fCount; ++i) {
- SkNEW_PLACEMENT_ARGS(self->fItemArray + i, T, (array[i]));
+ new (self->fItemArray + i) T(array[i]);
}
}
template
inline void copyAndDelete(SkTArray* self, char* newMemArray) {
for (int i = 0; i < self->fCount; ++i) {
- SkNEW_PLACEMENT_ARGS(newMemArray + sizeof(T) * i, T, (self->fItemArray[i]));
+ new (newMemArray + sizeof(T) * i) T(self->fItemArray[i]);
self->fItemArray[i].~T();
}
}
@@ -107,7 +108,7 @@ public:
return *this;
}
- virtual ~SkTArray() {
+ ~SkTArray() {
for (int i = 0; i < fCount; ++i) {
fItemArray[i].~T();
}
@@ -134,7 +135,7 @@ public:
this->checkRealloc(n);
fCount = n;
for (int i = 0; i < fCount; ++i) {
- SkNEW_PLACEMENT(fItemArray + i, T);
+ new (fItemArray + i) T;
}
}
@@ -179,7 +180,7 @@ public:
*/
T& push_back() {
T* newT = reinterpret_cast(this->push_back_raw(1));
- SkNEW_PLACEMENT(newT, T);
+ new (newT) T;
return *newT;
}
@@ -188,10 +189,18 @@ public:
*/
T& push_back(const T& t) {
T* newT = reinterpret_cast(this->push_back_raw(1));
- SkNEW_PLACEMENT_ARGS(newT, T, (t));
+ new (newT) T(t);
return *newT;
}
+ /**
+ * Construct a new T at the back of this array.
+ */
+ template T& emplace_back(Args&&... args) {
+ T* newT = reinterpret_cast(this->push_back_raw(1));
+ return *new (newT) T(skstd::forward(args)...);
+ }
+
/**
* Allocates n more default-initialized T values, and returns the address of
* the start of that new range. Note: this address is only valid until the
@@ -201,7 +210,7 @@ public:
SkASSERT(n >= 0);
T* newTs = reinterpret_cast(this->push_back_raw(n));
for (int i = 0; i < n; ++i) {
- SkNEW_PLACEMENT(newTs + i, T);
+ new (newTs + i) T;
}
return newTs;
}
@@ -214,7 +223,7 @@ public:
SkASSERT(n >= 0);
T* newTs = reinterpret_cast(this->push_back_raw(n));
for (int i = 0; i < n; ++i) {
- SkNEW_PLACEMENT_ARGS(newTs[i], T, (t));
+ new (newTs[i]) T(t);
}
return newTs;
}
@@ -227,7 +236,7 @@ public:
SkASSERT(n >= 0);
this->checkRealloc(n);
for (int i = 0; i < n; ++i) {
- SkNEW_PLACEMENT_ARGS(fItemArray + fCount + i, T, (t[i]));
+ new (fItemArray + fCount + i) T(t[i]);
}
fCount += n;
return fItemArray + fCount - n;
@@ -270,6 +279,26 @@ public:
}
}
+ /** Swaps the contents of this array with that array. Does a pointer swap if possible,
+ otherwise copies the T values. */
+ void swap(SkTArray* that) {
+ if (this == that) {
+ return;
+ }
+ if (this->fPreAllocMemArray != this->fItemArray &&
+ that->fPreAllocMemArray != that->fItemArray) {
+ // If neither is using a preallocated array then just swap.
+ SkTSwap(fItemArray, that->fItemArray);
+ SkTSwap(fCount, that->fCount);
+ SkTSwap(fAllocCount, that->fAllocCount);
+ } else {
+ // This could be more optimal...
+ SkTArray copy(*that);
+ *that = *this;
+ *this = copy;
+ }
+ }
+
T* begin() {
return fItemArray;
}
@@ -280,7 +309,7 @@ public:
return fItemArray ? fItemArray + fCount : NULL;
}
const T* end() const {
- return fItemArray ? fItemArray + fCount : NULL;;
+ return fItemArray ? fItemArray + fCount : NULL;
}
/**
@@ -375,7 +404,7 @@ protected:
}
void init(const T* array, int count,
- void* preAllocStorage, int preAllocOrReserveCount) {
+ void* preAllocStorage, int preAllocOrReserveCount) {
SkASSERT(count >= 0);
SkASSERT(preAllocOrReserveCount >= 0);
fCount = count;
@@ -384,7 +413,7 @@ protected:
gMIN_ALLOC_COUNT;
fPreAllocMemArray = preAllocStorage;
if (fReserveCount >= fCount &&
- NULL != preAllocStorage) {
+ preAllocStorage) {
fAllocCount = fReserveCount;
fMemArray = preAllocStorage;
} else {
@@ -427,7 +456,7 @@ private:
fAllocCount = newAllocCount;
char* newMemArray;
- if (fAllocCount == fReserveCount && NULL != fPreAllocMemArray) {
+ if (fAllocCount == fReserveCount && fPreAllocMemArray) {
newMemArray = (char*) fPreAllocMemArray;
} else {
newMemArray = (char*) sk_malloc_throw(fAllocCount*sizeof(T));
@@ -452,10 +481,10 @@ private:
template friend void SkTArrayExt::copy(SkTArray* that, const X*);
template friend void SkTArrayExt::copyAndDelete(SkTArray* that, char*);
- int fReserveCount;
- int fCount;
- int fAllocCount;
- void* fPreAllocMemArray;
+ int fReserveCount;
+ int fCount;
+ int fAllocCount;
+ void* fPreAllocMemArray;
union {
T* fItemArray;
void* fMemArray;
@@ -464,7 +493,7 @@ private:
// Use the below macro (SkNEW_APPEND_TO_TARRAY) rather than calling this directly
template
-void* operator new(size_t, SkTArray* array, int atIndex) {
+void* operator new(size_t, SkTArray