-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tools/layoutlib/.idea/scopes/scope_settings.xml b/tools/layoutlib/.idea/scopes/scope_settings.xml
deleted file mode 100644
index 922003b8433bc..0000000000000
--- a/tools/layoutlib/.idea/scopes/scope_settings.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/tools/layoutlib/.idea/uiDesigner.xml b/tools/layoutlib/.idea/uiDesigner.xml
deleted file mode 100644
index 3b0002030884f..0000000000000
--- a/tools/layoutlib/.idea/uiDesigner.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/.idea/vcs.xml b/tools/layoutlib/.idea/vcs.xml
deleted file mode 100644
index 9ab281ac88c73..0000000000000
--- a/tools/layoutlib/.idea/vcs.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/Android.mk b/tools/layoutlib/Android.mk
deleted file mode 100644
index 29c933ac7e752..0000000000000
--- a/tools/layoutlib/Android.mk
+++ /dev/null
@@ -1,82 +0,0 @@
-#
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-LOCAL_PATH := $(my-dir)
-include $(CLEAR_VARS)
-
-#
-# Define rules to build temp_layoutlib.jar, which contains a subset of
-# the classes in framework.jar. The layoutlib_create tool is used to
-# transform the framework jar into the temp_layoutlib jar.
-#
-
-# We need to process the framework classes.jar file, but we can't
-# depend directly on it (private vars won't be inherited correctly).
-# So, we depend on framework's BUILT file.
-built_framework_dep := $(call java-lib-deps,framework)
-built_framework_classes := $(call java-lib-files,framework)
-
-built_oj_dep := $(call java-lib-deps,core-oj)
-built_oj_classes := $(call java-lib-files,core-oj)
-
-built_core_dep := $(call java-lib-deps,core-libart)
-built_core_classes := $(call java-lib-files,core-libart)
-
-built_ext_dep := $(call java-lib-deps,ext)
-built_ext_classes := $(call java-lib-files,ext)
-
-built_icudata_dep := $(call java-lib-deps,icu4j-icudata-host-jarjar,HOST)
-built_icutzdata_dep := $(call java-lib-deps,icu4j-icutzdata-host-jarjar,HOST)
-
-built_layoutlib_create_jar := $(call java-lib-files,layoutlib_create,HOST)
-
-# This is mostly a copy of config/host_java_library.mk
-LOCAL_MODULE := temp_layoutlib
-LOCAL_MODULE_CLASS := JAVA_LIBRARIES
-LOCAL_MODULE_SUFFIX := $(COMMON_JAVA_PACKAGE_SUFFIX)
-LOCAL_IS_HOST_MODULE := true
-LOCAL_BUILT_MODULE_STEM := classes.jar
-
-#######################################
-include $(BUILD_SYSTEM)/base_rules.mk
-#######################################
-
-$(LOCAL_BUILT_MODULE): $(built_oj_dep) \
- $(built_core_dep) \
- $(built_framework_dep) \
- $(built_ext_dep) \
- $(built_icudata_dep) \
- $(built_icutzdata_dep) \
- $(built_layoutlib_create_jar)
- $(hide) echo "host layoutlib_create: $@"
- $(hide) mkdir -p $(dir $@)
- $(hide) rm -f $@
- $(hide) ls -l $(built_framework_classes)
- $(hide) java -ea -jar $(built_layoutlib_create_jar) \
- $@ \
- $(built_oj_classes) \
- $(built_core_classes) \
- $(built_framework_classes) \
- $(built_ext_classes) \
- $(built_icudata_dep) \
- $(built_icutzdata_dep) \
- $(built_ext_data)
- $(hide) ls -l $(built_framework_classes)
-
-
-#
-# Include the subdir makefiles.
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tools/layoutlib/README b/tools/layoutlib/README
deleted file mode 100644
index 0fea9bd9d9ac9..0000000000000
--- a/tools/layoutlib/README
+++ /dev/null
@@ -1,4 +0,0 @@
-Layoutlib is a custom version of the android View framework designed to run inside Eclipse.
-The goal of the library is to provide layout rendering in Eclipse that are very very close to their rendering on devices.
-
-None of the com.android.* or android.* classes in layoutlib run on devices.
\ No newline at end of file
diff --git a/tools/layoutlib/bridge/.classpath b/tools/layoutlib/bridge/.classpath
deleted file mode 100644
index 9c4160c8127f7..0000000000000
--- a/tools/layoutlib/bridge/.classpath
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/bridge/.project b/tools/layoutlib/bridge/.project
deleted file mode 100644
index e36e71b23ff90..0000000000000
--- a/tools/layoutlib/bridge/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- layoutlib_bridge
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
-
- org.eclipse.jdt.core.javanature
-
-
diff --git a/tools/layoutlib/bridge/.settings/README.txt b/tools/layoutlib/bridge/.settings/README.txt
deleted file mode 100644
index 9120b20710a3c..0000000000000
--- a/tools/layoutlib/bridge/.settings/README.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Copy this in eclipse project as a .settings folder at the root.
-This ensure proper compilation compliance and warning/error levels.
\ No newline at end of file
diff --git a/tools/layoutlib/bridge/.settings/org.eclipse.jdt.core.prefs b/tools/layoutlib/bridge/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index 5381a0e16c7de..0000000000000
--- a/tools/layoutlib/bridge/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,93 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullReference=error
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/tools/layoutlib/bridge/Android.mk b/tools/layoutlib/bridge/Android.mk
deleted file mode 100644
index 3dd8002bcff5e..0000000000000
--- a/tools/layoutlib/bridge/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under,src)
-LOCAL_JAVA_RESOURCE_DIRS := resources
-
-LOCAL_JAVA_LIBRARIES := \
- layoutlib_api-prebuilt \
- tools-common-prebuilt
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
- temp_layoutlib \
- ninepatch-prebuilt
-
-LOCAL_MODULE := layoutlib
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-# Build all sub-directories
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/tools/layoutlib/bridge/bridge.iml b/tools/layoutlib/bridge/bridge.iml
deleted file mode 100644
index 85ec3eb73b923..0000000000000
--- a/tools/layoutlib/bridge/bridge.iml
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/tools/layoutlib/bridge/resources/bars/README b/tools/layoutlib/bridge/resources/bars/README
deleted file mode 100644
index c84ef804ccabe..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/README
+++ /dev/null
@@ -1,8 +0,0 @@
-The directory contains the resources for StatusBar and Navigation Bar.
-
-The resources are not arranged as per the standard resources configuration.
-They are stored per API. However, to prevent duplication of resources, each API
-resource directory is used as a backup for all earlier API levels.
-
-For example, for the back icon for ICS, we search first in v18, where we don't
-find it, and then in v19.
diff --git a/tools/layoutlib/bridge/resources/bars/navigation_bar.xml b/tools/layoutlib/bridge/resources/bars/navigation_bar.xml
deleted file mode 100644
index 55bd1d2c67a4c..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/navigation_bar.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/bridge/resources/bars/navigation_bar600dp.xml b/tools/layoutlib/bridge/resources/bars/navigation_bar600dp.xml
deleted file mode 100644
index e208a0daf3efe..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/navigation_bar600dp.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/bridge/resources/bars/status_bar.xml b/tools/layoutlib/bridge/resources/bars/status_bar.xml
deleted file mode 100644
index 04571e1d6d35b..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/status_bar.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/tools/layoutlib/bridge/resources/bars/title_bar.xml b/tools/layoutlib/bridge/resources/bars/title_bar.xml
deleted file mode 100644
index 76d78d9169d46..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/title_bar.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
diff --git a/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_battery_100.png
deleted file mode 100644
index c920ec4fe71ab..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 6248cfd7b09b1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/hdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_battery_100.png
deleted file mode 100644
index 943332e5929c7..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 441de0ce78f81..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/mdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_battery_100.png
deleted file mode 100644
index 36c61e13ade30..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 459a1a2e83ce8..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v18/xhdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_back.png
deleted file mode 100644
index 84e6bc89c0829..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_home.png
deleted file mode 100644
index 38e4f45719e7f..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_recent.png
deleted file mode 100644
index bf9f3009c32c2..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/hdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/hdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v19/hdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 6248cfd7b09b1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/hdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_back.png
deleted file mode 100644
index 782ebfe3f2ba7..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_recent.png
deleted file mode 100644
index 677b47137a3fb..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-hdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_back.png
deleted file mode 100644
index a1b8062669591..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_recent.png
deleted file mode 100644
index fcdbefe9f5065..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-mdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_back.png
deleted file mode 100644
index 633d864829381..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_recent.png
deleted file mode 100644
index 4665e2a6fef93..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/ldrtl-xhdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_back.png
deleted file mode 100644
index a00bc5b5f33b1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_home.png
deleted file mode 100644
index dc3183bf640f8..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_recent.png
deleted file mode 100644
index b07f611ab98c1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/mdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/mdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v19/mdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 441de0ce78f81..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/mdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_back.png
deleted file mode 100644
index bd60cd65878a3..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_home.png
deleted file mode 100644
index c5bc5c96ef051..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_recent.png
deleted file mode 100644
index f621d9cc72428..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v19/xhdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 459a1a2e83ce8..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xhdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_back.png
deleted file mode 100644
index 79cfcee70c4b8..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_home.png
deleted file mode 100644
index 64f6a22fe65b5..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_recent.png
deleted file mode 100644
index 6e0b071206d54..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 494b005326d8d..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v19/xxhdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_back.png
deleted file mode 100644
index d2760bb912e2f..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_home.png
deleted file mode 100644
index df43e21b47d11..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_recent.png
deleted file mode 100644
index 6fab1d645dff4..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/hdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/hdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v21/hdpi/stat_sys_battery_100.png
deleted file mode 100644
index f17189a0645d1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/hdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-hdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/ldrtl-hdpi/ic_sysbar_back.png
deleted file mode 100644
index 2fcfdde08164d..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-hdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-mdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/ldrtl-mdpi/ic_sysbar_back.png
deleted file mode 100644
index 48708a5099a83..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-mdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xhdpi/ic_sysbar_back.png
deleted file mode 100644
index 3d731840a93f6..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xxhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xxhdpi/ic_sysbar_back.png
deleted file mode 100644
index 786935d5d185c..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/ldrtl-xxhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_back.png
deleted file mode 100644
index 1d8c3af177161..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_home.png
deleted file mode 100644
index 66de0ec75ec95..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_recent.png
deleted file mode 100644
index 30c65f51a1288..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/mdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/mdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v21/mdpi/stat_sys_battery_100.png
deleted file mode 100644
index 2a9757dea17ee..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/mdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_back.png
deleted file mode 100644
index a3562850ef9cc..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_home.png
deleted file mode 100644
index ba2d0b2642cec..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_recent.png
deleted file mode 100644
index 94a74b189abfd..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_battery_100.png
deleted file mode 100644
index 555bcd972415d..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_wifi_signal_4_fully.xml b/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_wifi_signal_4_fully.xml
deleted file mode 100644
index 0498b6cedbb85..0000000000000
--- a/tools/layoutlib/bridge/resources/bars/v21/xhdpi/stat_sys_wifi_signal_4_fully.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_back.png b/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_back.png
deleted file mode 100644
index 29da099f6d825..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_back.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_home.png b/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_home.png
deleted file mode 100644
index 59b32f2dd1781..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_home.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_recent.png b/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_recent.png
deleted file mode 100644
index ba66d27f11993..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/ic_sysbar_recent.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/stat_sys_battery_100.png
deleted file mode 100644
index 6474aadeeab02..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v21/xxhdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_battery_100.png
deleted file mode 100644
index 754cdf6564d60..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index b5326d257961e..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v9/hdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v9/ldpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v9/ldpi/stat_sys_battery_100.png
deleted file mode 100644
index 7023ea7b420cc..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v9/ldpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_battery_100.png b/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_battery_100.png
deleted file mode 100644
index 17a955dcc3db9..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_battery_100.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_wifi_signal_4_fully.png
deleted file mode 100644
index 19165ab40ea0f..0000000000000
Binary files a/tools/layoutlib/bridge/resources/bars/v9/mdpi/stat_sys_wifi_signal_4_fully.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-b.png b/tools/layoutlib/bridge/resources/icons/shadow-b.png
deleted file mode 100644
index 68f4f4ba5b4f0..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-b.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-bl.png b/tools/layoutlib/bridge/resources/icons/shadow-bl.png
deleted file mode 100644
index ee7dbe84600b0..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-bl.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-br.png b/tools/layoutlib/bridge/resources/icons/shadow-br.png
deleted file mode 100644
index c45ad77f8d1e4..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-br.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-l.png b/tools/layoutlib/bridge/resources/icons/shadow-l.png
deleted file mode 100644
index 77d0bd089391e..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-l.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-r.png b/tools/layoutlib/bridge/resources/icons/shadow-r.png
deleted file mode 100644
index 4af7a33305551..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-r.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-tl.png b/tools/layoutlib/bridge/resources/icons/shadow-tl.png
deleted file mode 100644
index 424fb3676f5db..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-tl.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow-tr.png b/tools/layoutlib/bridge/resources/icons/shadow-tr.png
deleted file mode 100644
index 1fd0c77269c0e..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow-tr.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-b.png b/tools/layoutlib/bridge/resources/icons/shadow2-b.png
deleted file mode 100644
index 963973ea7d74e..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-b.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-bl.png b/tools/layoutlib/bridge/resources/icons/shadow2-bl.png
deleted file mode 100644
index 76124877759e6..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-bl.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-br.png b/tools/layoutlib/bridge/resources/icons/shadow2-br.png
deleted file mode 100644
index 8e20252cbf646..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-br.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-l.png b/tools/layoutlib/bridge/resources/icons/shadow2-l.png
deleted file mode 100644
index 2db18a05911d1..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-l.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-r.png b/tools/layoutlib/bridge/resources/icons/shadow2-r.png
deleted file mode 100644
index 8e026f147ce1f..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-r.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-tl.png b/tools/layoutlib/bridge/resources/icons/shadow2-tl.png
deleted file mode 100644
index a8045ed379e02..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-tl.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/resources/icons/shadow2-tr.png b/tools/layoutlib/bridge/resources/icons/shadow2-tr.png
deleted file mode 100644
index 590373c955db6..0000000000000
Binary files a/tools/layoutlib/bridge/resources/icons/shadow2-tr.png and /dev/null differ
diff --git a/tools/layoutlib/bridge/src/android/animation/AnimationThread.java b/tools/layoutlib/bridge/src/android/animation/AnimationThread.java
deleted file mode 100644
index ce2aec790119e..0000000000000
--- a/tools/layoutlib/bridge/src/android/animation/AnimationThread.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.animation;
-
-import com.android.ide.common.rendering.api.IAnimationListener;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.rendering.api.Result.Status;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.RenderSessionImpl;
-
-import android.os.Handler;
-import android.os.Handler_Delegate;
-import android.os.Message;
-
-import java.util.PriorityQueue;
-import java.util.Queue;
-
-/**
- * Abstract animation thread.
- *
- * This does not actually start an animation, instead it fakes a looper that will play whatever
- * animation is sending messages to its own {@link Handler}.
- *
- * Classes should implement {@link #preAnimation()} and {@link #postAnimation()}.
- *
- * If {@link #preAnimation()} does not start an animation somehow then the thread doesn't do
- * anything.
- *
- */
-public abstract class AnimationThread extends Thread {
-
- private static class MessageBundle implements Comparable {
- final Handler mTarget;
- final Message mMessage;
- final long mUptimeMillis;
-
- MessageBundle(Handler target, Message message, long uptimeMillis) {
- mTarget = target;
- mMessage = message;
- mUptimeMillis = uptimeMillis;
- }
-
- @Override
- public int compareTo(MessageBundle bundle) {
- if (mUptimeMillis < bundle.mUptimeMillis) {
- return -1;
- }
- return 1;
- }
- }
-
- private final RenderSessionImpl mSession;
-
- private Queue mQueue = new PriorityQueue();
- private final IAnimationListener mListener;
-
- public AnimationThread(RenderSessionImpl scene, String threadName,
- IAnimationListener listener) {
- super(threadName);
- mSession = scene;
- mListener = listener;
- }
-
- public abstract Result preAnimation();
- public abstract void postAnimation();
-
- @Override
- public void run() {
- Bridge.prepareThread();
- try {
- /* FIXME: The ANIMATION_FRAME message no longer exists. Instead, the
- * animation timing loop is completely based on a Choreographer objects
- * that schedules animation and drawing frames. The animation handler is
- * no longer even a handler; it is just a Runnable enqueued on the Choreographer.
- Handler_Delegate.setCallback(new IHandlerCallback() {
- @Override
- public void sendMessageAtTime(Handler handler, Message msg, long uptimeMillis) {
- if (msg.what == ValueAnimator.ANIMATION_START ||
- msg.what == ValueAnimator.ANIMATION_FRAME) {
- mQueue.add(new MessageBundle(handler, msg, uptimeMillis));
- } else {
- // just ignore.
- }
- }
- });
- */
-
- // call out to the pre-animation work, which should start an animation or more.
- Result result = preAnimation();
- if (result.isSuccess() == false) {
- mListener.done(result);
- }
-
- // loop the animation
- RenderSession session = mSession.getSession();
- do {
- // check early.
- if (mListener.isCanceled()) {
- break;
- }
-
- // get the next message.
- MessageBundle bundle = mQueue.poll();
- if (bundle == null) {
- break;
- }
-
- // sleep enough for this bundle to be on time
- long currentTime = System.currentTimeMillis();
- if (currentTime < bundle.mUptimeMillis) {
- try {
- sleep(bundle.mUptimeMillis - currentTime);
- } catch (InterruptedException e) {
- // FIXME log/do something/sleep again?
- e.printStackTrace();
- }
- }
-
- // check after sleeping.
- if (mListener.isCanceled()) {
- break;
- }
-
- // ready to do the work, acquire the scene.
- result = mSession.acquire(250);
- if (result.isSuccess() == false) {
- mListener.done(result);
- return;
- }
-
- // process the bundle. If the animation is not finished, this will enqueue
- // the next message, so mQueue will have another one.
- try {
- // check after acquiring in case it took a while.
- if (mListener.isCanceled()) {
- break;
- }
-
- bundle.mTarget.handleMessage(bundle.mMessage);
- if (mSession.render(false /*freshRender*/).isSuccess()) {
- mListener.onNewFrame(session);
- }
- } finally {
- mSession.release();
- }
- } while (mListener.isCanceled() == false && mQueue.size() > 0);
-
- mListener.done(Status.SUCCESS.createResult());
-
- } catch (Throwable throwable) {
- // can't use Bridge.getLog() as the exception might be thrown outside
- // of an acquire/release block.
- mListener.done(Status.ERROR_UNKNOWN.createResult("Error playing animation", throwable));
-
- } finally {
- postAnimation();
- Handler_Delegate.setCallback(null);
- Bridge.cleanupThread();
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/animation/PropertyValuesHolder_Delegate.java b/tools/layoutlib/bridge/src/android/animation/PropertyValuesHolder_Delegate.java
deleted file mode 100644
index 28a489ad6ed7a..0000000000000
--- a/tools/layoutlib/bridge/src/android/animation/PropertyValuesHolder_Delegate.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.animation;
-
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Delegate implementing the native methods of android.animation.PropertyValuesHolder
- *
- * Through the layoutlib_create tool, the original native methods of PropertyValuesHolder have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
- * around to map int to instance of the delegate.
- *
- * The main goal of this class' methods are to provide a native way to access setters and getters
- * on some object. We override these methods to use reflection since the original reflection
- * implementation of the PropertyValuesHolder won't be able to access protected methods.
- *
- */
-/*package*/
-@SuppressWarnings("unused")
-class PropertyValuesHolder_Delegate {
- // This code is copied from android.animation.PropertyValuesHolder and must be kept in sync
- // We try several different types when searching for appropriate setter/getter functions.
- // The caller may have supplied values in a type that does not match the setter/getter
- // functions (such as the integers 0 and 1 to represent floating point values for alpha).
- // Also, the use of generics in constructors means that we end up with the Object versions
- // of primitive types (Float vs. float). But most likely, the setter/getter functions
- // will take primitive types instead.
- // So we supply an ordered array of other types to try before giving up.
- private static Class[] FLOAT_VARIANTS = {float.class, Float.class, double.class, int.class,
- Double.class, Integer.class};
- private static Class[] INTEGER_VARIANTS = {int.class, Integer.class, float.class, double.class,
- Float.class, Double.class};
-
- private static final Object sMethodIndexLock = new Object();
- private static final Map ID_TO_METHOD = new HashMap();
- private static final Map METHOD_NAME_TO_ID = new HashMap();
- private static long sNextId = 1;
-
- private static long registerMethod(Class> targetClass, String methodName, Class[] types,
- int nArgs) {
- // Encode the number of arguments in the method name
- String methodIndexName = String.format("%1$s.%2$s#%3$d", targetClass.getSimpleName(),
- methodName, nArgs);
- synchronized (sMethodIndexLock) {
- Long methodId = METHOD_NAME_TO_ID.get(methodIndexName);
-
- if (methodId != null) {
- // The method was already registered
- return methodId;
- }
-
- Class[] args = new Class[nArgs];
- Method method = null;
- for (Class typeVariant : types) {
- for (int i = 0; i < nArgs; i++) {
- args[i] = typeVariant;
- }
- try {
- method = targetClass.getDeclaredMethod(methodName, args);
- } catch (NoSuchMethodException ignore) {
- }
- }
-
- if (method != null) {
- methodId = sNextId++;
- ID_TO_METHOD.put(methodId, method);
- METHOD_NAME_TO_ID.put(methodIndexName, methodId);
-
- return methodId;
- }
- }
-
- // Method not found
- return 0;
- }
-
- private static void callMethod(Object target, long methodID, Object... args) {
- Method method = ID_TO_METHOD.get(methodID);
- assert method != null;
-
- try {
- method.setAccessible(true);
- method.invoke(target, args);
- } catch (IllegalAccessException e) {
- Bridge.getLog().error(null, "Unable to update property during animation", e, null);
- } catch (InvocationTargetException e) {
- Bridge.getLog().error(null, "Unable to update property during animation", e, null);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetIntMethod(Class> targetClass, String methodName) {
- return nGetMultipleIntMethod(targetClass, methodName, 1);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetFloatMethod(Class> targetClass, String methodName) {
- return nGetMultipleFloatMethod(targetClass, methodName, 1);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetMultipleIntMethod(Class> targetClass, String methodName,
- int numParams) {
- return registerMethod(targetClass, methodName, INTEGER_VARIANTS, numParams);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetMultipleFloatMethod(Class> targetClass, String methodName,
- int numParams) {
- return registerMethod(targetClass, methodName, FLOAT_VARIANTS, numParams);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallIntMethod(Object target, long methodID, int arg) {
- callMethod(target, methodID, arg);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallFloatMethod(Object target, long methodID, float arg) {
- callMethod(target, methodID, arg);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallTwoIntMethod(Object target, long methodID, int arg1,
- int arg2) {
- callMethod(target, methodID, arg1, arg2);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallFourIntMethod(Object target, long methodID, int arg1,
- int arg2, int arg3, int arg4) {
- callMethod(target, methodID, arg1, arg2, arg3, arg4);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallMultipleIntMethod(Object target, long methodID,
- int[] args) {
- assert args != null;
-
- // Box parameters
- Object[] params = new Object[args.length];
- for (int i = 0; i < args.length; i++) {
- params[i] = args;
- }
- callMethod(target, methodID, params);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallTwoFloatMethod(Object target, long methodID, float arg1,
- float arg2) {
- callMethod(target, methodID, arg1, arg2);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallFourFloatMethod(Object target, long methodID, float arg1,
- float arg2, float arg3, float arg4) {
- callMethod(target, methodID, arg1, arg2, arg3, arg4);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCallMultipleFloatMethod(Object target, long methodID,
- float[] args) {
- assert args != null;
-
- // Box parameters
- Object[] params = new Object[args.length];
- for (int i = 0; i < args.length; i++) {
- params[i] = args;
- }
- callMethod(target, methodID, params);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/app/Fragment_Delegate.java b/tools/layoutlib/bridge/src/android/app/Fragment_Delegate.java
deleted file mode 100644
index f7654ce231b2a..0000000000000
--- a/tools/layoutlib/bridge/src/android/app/Fragment_Delegate.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app;
-
-import com.android.ide.common.rendering.api.LayoutlibCallback;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.content.Context;
-import android.os.Bundle;
-
-/**
- * Delegate used to provide new implementation of a select few methods of {@link Fragment}
- *
- * Through the layoutlib_create tool, the original methods of Fragment have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * The methods being re-implemented are the ones responsible for instantiating Fragment objects.
- * Because the classes of these objects are found in the project, these methods need access to
- * {@link LayoutlibCallback} object. They are however static methods, so the callback is set
- * before the inflation through {@link #setLayoutlibCallback(LayoutlibCallback)}.
- */
-public class Fragment_Delegate {
-
- private static LayoutlibCallback sLayoutlibCallback;
-
- /**
- * Sets the current {@link LayoutlibCallback} to be used to instantiate classes coming
- * from the project being rendered.
- */
- public static void setLayoutlibCallback(LayoutlibCallback layoutlibCallback) {
- sLayoutlibCallback = layoutlibCallback;
- }
-
- /**
- * Like {@link #instantiate(Context, String, Bundle)} but with a null
- * argument Bundle.
- */
- @LayoutlibDelegate
- /*package*/ static Fragment instantiate(Context context, String fname) {
- return instantiate(context, fname, null);
- }
-
- /**
- * Create a new instance of a Fragment with the given class name. This is
- * the same as calling its empty constructor.
- *
- * @param context The calling context being used to instantiate the fragment.
- * This is currently just used to get its ClassLoader.
- * @param fname The class name of the fragment to instantiate.
- * @param args Bundle of arguments to supply to the fragment, which it
- * can retrieve with {@link Fragment#getArguments()}. May be null.
- * @return Returns a new fragment instance.
- * @throws Fragment.InstantiationException If there is a failure in instantiating
- * the given fragment class. This is a runtime exception; it is not
- * normally expected to happen.
- */
- @LayoutlibDelegate
- /*package*/ static Fragment instantiate(Context context, String fname, Bundle args) {
- try {
- if (sLayoutlibCallback != null) {
- Fragment f = (Fragment) sLayoutlibCallback.loadView(fname,
- new Class[0], new Object[0]);
-
- if (args != null) {
- args.setClassLoader(f.getClass().getClassLoader());
- f.mArguments = args;
- }
- return f;
- }
-
- return null;
- } catch (ClassNotFoundException e) {
- throw new Fragment.InstantiationException("Unable to instantiate fragment " + fname
- + ": make sure class name exists, is public, and has an"
- + " empty constructor that is public", e);
- } catch (java.lang.InstantiationException e) {
- throw new Fragment.InstantiationException("Unable to instantiate fragment " + fname
- + ": make sure class name exists, is public, and has an"
- + " empty constructor that is public", e);
- } catch (IllegalAccessException e) {
- throw new Fragment.InstantiationException("Unable to instantiate fragment " + fname
- + ": make sure class name exists, is public, and has an"
- + " empty constructor that is public", e);
- } catch (Exception e) {
- throw new Fragment.InstantiationException("Unable to instantiate fragment " + fname
- + ": make sure class name exists, is public, and has an"
- + " empty constructor that is public", e);
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/app/SystemServiceRegistry_Accessor.java b/tools/layoutlib/bridge/src/android/app/SystemServiceRegistry_Accessor.java
deleted file mode 100644
index 591aee07aa3f7..0000000000000
--- a/tools/layoutlib/bridge/src/android/app/SystemServiceRegistry_Accessor.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app;
-
-/**
- * Class to allow accessing {@link SystemServiceRegistry#getSystemServiceName}
- */
-public class SystemServiceRegistry_Accessor {
- /**
- * Gets the name of the system-level service that is represented by the specified class.
- */
- public static String getSystemServiceName(Class> serviceClass) {
- return SystemServiceRegistry.getSystemServiceName(serviceClass);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/AssetManager_Delegate.java b/tools/layoutlib/bridge/src/android/content/res/AssetManager_Delegate.java
deleted file mode 100644
index b4d5288bc9257..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/AssetManager_Delegate.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.util.SparseArray;
-
-/**
- * Delegate used to provide implementation of a select few native methods of {@link AssetManager}
- *
- * Through the layoutlib_create tool, the original native methods of AssetManager have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- */
-public class AssetManager_Delegate {
-
- @LayoutlibDelegate
- /*package*/ static long newTheme(AssetManager manager) {
- return Resources_Theme_Delegate.getDelegateManager()
- .addNewDelegate(new Resources_Theme_Delegate());
- }
-
- @LayoutlibDelegate
- /*package*/ static void deleteTheme(AssetManager manager, long theme) {
- Resources_Theme_Delegate.getDelegateManager().removeJavaReferenceFor(theme);
- }
-
- @LayoutlibDelegate
- /*package*/ static SparseArray getAssignedPackageIdentifiers(AssetManager manager) {
- return new SparseArray<>();
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/BridgeAssetManager.java b/tools/layoutlib/bridge/src/android/content/res/BridgeAssetManager.java
deleted file mode 100644
index 2691e5640ff02..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/BridgeAssetManager.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.ide.common.rendering.api.AssetRepository;
-import com.android.layoutlib.bridge.Bridge;
-
-public class BridgeAssetManager extends AssetManager {
-
- private AssetRepository mAssetRepository;
-
- /**
- * This initializes the static field {@link AssetManager#sSystem} which is used
- * by methods who get a global asset manager using {@link AssetManager#getSystem()}.
- *
- * They will end up using our bridge asset manager.
- *
- * {@link Bridge} calls this method after setting up a new bridge.
- */
- public static AssetManager initSystem() {
- if (!(AssetManager.sSystem instanceof BridgeAssetManager)) {
- // Note that AssetManager() creates a system AssetManager and we override it
- // with our BridgeAssetManager.
- AssetManager.sSystem = new BridgeAssetManager();
- AssetManager.sSystem.makeStringBlocks(null);
- }
- return AssetManager.sSystem;
- }
-
- /**
- * Clears the static {@link AssetManager#sSystem} to make sure we don't leave objects
- * around that would prevent us from unloading the library.
- */
- public static void clearSystem() {
- AssetManager.sSystem = null;
- }
-
- public void setAssetRepository(AssetRepository assetRepository) {
- mAssetRepository = assetRepository;
- }
-
- public AssetRepository getAssetRepository() {
- return mAssetRepository;
- }
-
- public BridgeAssetManager() {
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/BridgeTypedArray.java b/tools/layoutlib/bridge/src/android/content/res/BridgeTypedArray.java
deleted file mode 100644
index b5996afd7985f..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/BridgeTypedArray.java
+++ /dev/null
@@ -1,1011 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.ide.common.rendering.api.ArrayResourceValue;
-import com.android.ide.common.rendering.api.AttrResourceValue;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.RenderResources;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.StyleResourceValue;
-import com.android.internal.util.XmlUtils;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.android.BridgeContext;
-import com.android.layoutlib.bridge.impl.ResourceHelper;
-import com.android.resources.ResourceType;
-
-import android.annotation.Nullable;
-import android.content.res.Resources.NotFoundException;
-import android.content.res.Resources.Theme;
-import android.graphics.Typeface;
-import android.graphics.drawable.Drawable;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import android.view.LayoutInflater_Delegate;
-import android.view.ViewGroup.LayoutParams;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Map;
-
-import static android.util.TypedValue.TYPE_ATTRIBUTE;
-import static android.util.TypedValue.TYPE_DIMENSION;
-import static android.util.TypedValue.TYPE_FLOAT;
-import static android.util.TypedValue.TYPE_INT_BOOLEAN;
-import static android.util.TypedValue.TYPE_INT_COLOR_ARGB4;
-import static android.util.TypedValue.TYPE_INT_COLOR_ARGB8;
-import static android.util.TypedValue.TYPE_INT_COLOR_RGB4;
-import static android.util.TypedValue.TYPE_INT_COLOR_RGB8;
-import static android.util.TypedValue.TYPE_INT_DEC;
-import static android.util.TypedValue.TYPE_INT_HEX;
-import static android.util.TypedValue.TYPE_NULL;
-import static android.util.TypedValue.TYPE_REFERENCE;
-import static android.util.TypedValue.TYPE_STRING;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.ide.common.rendering.api.RenderResources.REFERENCE_EMPTY;
-import static com.android.ide.common.rendering.api.RenderResources.REFERENCE_NULL;
-import static com.android.ide.common.rendering.api.RenderResources.REFERENCE_UNDEFINED;
-
-/**
- * Custom implementation of TypedArray to handle non compiled resources.
- */
-public final class BridgeTypedArray extends TypedArray {
-
- private final Resources mBridgeResources;
- private final BridgeContext mContext;
- private final boolean mPlatformFile;
-
- private final ResourceValue[] mResourceData;
- private final String[] mNames;
- private final boolean[] mIsFramework;
-
- // Contains ids that are @empty. We still store null in mResourceData for that index, since we
- // want to save on the check against empty, each time a resource value is requested.
- @Nullable
- private int[] mEmptyIds;
-
- public BridgeTypedArray(Resources resources, BridgeContext context, int len,
- boolean platformFile) {
- super(resources);
- mBridgeResources = resources;
- mContext = context;
- mPlatformFile = platformFile;
- mResourceData = new ResourceValue[len];
- mNames = new String[len];
- mIsFramework = new boolean[len];
- }
-
- /**
- * A bridge-specific method that sets a value in the type array
- * @param index the index of the value in the TypedArray
- * @param name the name of the attribute
- * @param isFramework whether the attribute is in the android namespace.
- * @param value the value of the attribute
- */
- public void bridgeSetValue(int index, String name, boolean isFramework, ResourceValue value) {
- mResourceData[index] = value;
- mNames[index] = name;
- mIsFramework[index] = isFramework;
- }
-
- /**
- * Seals the array after all calls to
- * {@link #bridgeSetValue(int, String, boolean, ResourceValue)} have been done.
- * This allows to compute the list of non default values, permitting
- * {@link #getIndexCount()} to return the proper value.
- */
- public void sealArray() {
- // fills TypedArray.mIndices which is used to implement getIndexCount/getIndexAt
- // first count the array size
- int count = 0;
- ArrayList emptyIds = null;
- for (int i = 0; i < mResourceData.length; i++) {
- ResourceValue data = mResourceData[i];
- if (data != null) {
- String dataValue = data.getValue();
- if (REFERENCE_NULL.equals(dataValue) || REFERENCE_UNDEFINED.equals(dataValue)) {
- mResourceData[i] = null;
- } else if (REFERENCE_EMPTY.equals(dataValue)) {
- mResourceData[i] = null;
- if (emptyIds == null) {
- emptyIds = new ArrayList(4);
- }
- emptyIds.add(i);
- } else {
- count++;
- }
- }
- }
-
- if (emptyIds != null) {
- mEmptyIds = new int[emptyIds.size()];
- for (int i = 0; i < emptyIds.size(); i++) {
- mEmptyIds[i] = emptyIds.get(i);
- }
- }
-
- // allocate the table with an extra to store the size
- mIndices = new int[count+1];
- mIndices[0] = count;
-
- // fill the array with the indices.
- int index = 1;
- for (int i = 0 ; i < mResourceData.length ; i++) {
- if (mResourceData[i] != null) {
- mIndices[index++] = i;
- }
- }
- }
-
- /**
- * Set the theme to be used for inflating drawables.
- */
- public void setTheme(Theme theme) {
- mTheme = theme;
- }
-
- /**
- * Return the number of values in this array.
- */
- @Override
- public int length() {
- return mResourceData.length;
- }
-
- /**
- * Return the Resources object this array was loaded from.
- */
- @Override
- public Resources getResources() {
- return mBridgeResources;
- }
-
- /**
- * Retrieve the styled string value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return CharSequence holding string data. May be styled. Returns
- * null if the attribute is not defined.
- */
- @Override
- public CharSequence getText(int index) {
- // FIXME: handle styled strings!
- return getString(index);
- }
-
- /**
- * Retrieve the string value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return String holding string data. Any styling information is
- * removed. Returns null if the attribute is not defined.
- */
- @Override
- public String getString(int index) {
- if (!hasValue(index)) {
- return null;
- }
- // As unfortunate as it is, it's possible to use enums with all attribute formats,
- // not just integers/enums. So, we need to search the enums always. In case
- // enums are used, the returned value is an integer.
- Integer v = resolveEnumAttribute(index);
- return v == null ? mResourceData[index].getValue() : String.valueOf((int) v);
- }
-
- /**
- * Retrieve the boolean value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined.
- *
- * @return Attribute boolean value, or defValue if not defined.
- */
- @Override
- public boolean getBoolean(int index, boolean defValue) {
- String s = getString(index);
- return s == null ? defValue : XmlUtils.convertValueToBoolean(s, defValue);
-
- }
-
- /**
- * Retrieve the integer value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined.
- *
- * @return Attribute int value, or defValue if not defined.
- */
- @Override
- public int getInt(int index, int defValue) {
- String s = getString(index);
- try {
- return convertValueToInt(s, defValue);
- } catch (NumberFormatException e) {
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
- String.format("\"%1$s\" in attribute \"%2$s\" is not a valid integer",
- s, mNames[index]),
- null);
- }
- return defValue;
- }
-
- /**
- * Retrieve the float value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return Attribute float value, or defValue if not defined..
- */
- @Override
- public float getFloat(int index, float defValue) {
- String s = getString(index);
- try {
- if (s != null) {
- return Float.parseFloat(s);
- }
- } catch (NumberFormatException e) {
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
- String.format("\"%1$s\" in attribute \"%2$s\" cannot be converted to float.",
- s, mNames[index]),
- null);
- }
- return defValue;
- }
-
- /**
- * Retrieve the color value for the attribute at index. If
- * the attribute references a color resource holding a complex
- * {@link android.content.res.ColorStateList}, then the default color from
- * the set is returned.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute color value, or defValue if not defined.
- */
- @Override
- public int getColor(int index, int defValue) {
- if (index < 0 || index >= mResourceData.length) {
- return defValue;
- }
-
- if (mResourceData[index] == null) {
- return defValue;
- }
-
- ColorStateList colorStateList = ResourceHelper.getColorStateList(
- mResourceData[index], mContext);
- if (colorStateList != null) {
- return colorStateList.getDefaultColor();
- }
-
- return defValue;
- }
-
- @Override
- public ColorStateList getColorStateList(int index) {
- if (!hasValue(index)) {
- return null;
- }
-
- return ResourceHelper.getColorStateList(mResourceData[index], mContext);
- }
-
- @Override
- public ComplexColor getComplexColor(int index) {
- if (!hasValue(index)) {
- return null;
- }
-
- return ResourceHelper.getComplexColor(mResourceData[index], mContext);
- }
-
- /**
- * Retrieve the integer value for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute integer value, or defValue if not defined.
- */
- @Override
- public int getInteger(int index, int defValue) {
- return getInt(index, defValue);
- }
-
- /**
- * Retrieve a dimensional unit attribute at index. Unit
- * conversions are based on the current {@link DisplayMetrics}
- * associated with the resources this {@link TypedArray} object
- * came from.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute dimension value multiplied by the appropriate
- * metric, or defValue if not defined.
- *
- * @see #getDimensionPixelOffset
- * @see #getDimensionPixelSize
- */
- @Override
- public float getDimension(int index, float defValue) {
- String s = getString(index);
- if (s == null) {
- return defValue;
- }
- // Check if the value is a magic constant that doesn't require a unit.
- try {
- int i = Integer.parseInt(s);
- if (i == LayoutParams.MATCH_PARENT || i == LayoutParams.WRAP_CONTENT) {
- return i;
- }
- } catch (NumberFormatException ignored) {
- // pass
- }
-
- if (ResourceHelper.parseFloatAttribute(mNames[index], s, mValue, true)) {
- return mValue.getDimension(mBridgeResources.getDisplayMetrics());
- }
-
- return defValue;
- }
-
- /**
- * Retrieve a dimensional unit attribute at index for use
- * as an offset in raw pixels. This is the same as
- * {@link #getDimension}, except the returned value is converted to
- * integer pixels for you. An offset conversion involves simply
- * truncating the base value to an integer.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute dimension value multiplied by the appropriate
- * metric and truncated to integer pixels, or defValue if not defined.
- *
- * @see #getDimension
- * @see #getDimensionPixelSize
- */
- @Override
- public int getDimensionPixelOffset(int index, int defValue) {
- return (int) getDimension(index, defValue);
- }
-
- /**
- * Retrieve a dimensional unit attribute at index for use
- * as a size in raw pixels. This is the same as
- * {@link #getDimension}, except the returned value is converted to
- * integer pixels for use as a size. A size conversion involves
- * rounding the base value, and ensuring that a non-zero base value
- * is at least one pixel in size.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute dimension value multiplied by the appropriate
- * metric and truncated to integer pixels, or defValue if not defined.
- *
- * @see #getDimension
- * @see #getDimensionPixelOffset
- */
- @Override
- public int getDimensionPixelSize(int index, int defValue) {
- try {
- return getDimension(index, null);
- } catch (RuntimeException e) {
- String s = getString(index);
-
- if (s != null) {
- // looks like we were unable to resolve the dimension value
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
- String.format("\"%1$s\" in attribute \"%2$s\" is not a valid format.",
- s, mNames[index]), null);
- }
-
- return defValue;
- }
- }
-
- /**
- * Special version of {@link #getDimensionPixelSize} for retrieving
- * {@link android.view.ViewGroup}'s layout_width and layout_height
- * attributes. This is only here for performance reasons; applications
- * should use {@link #getDimensionPixelSize}.
- *
- * @param index Index of the attribute to retrieve.
- * @param name Textual name of attribute for error reporting.
- *
- * @return Attribute dimension value multiplied by the appropriate
- * metric and truncated to integer pixels.
- */
- @Override
- public int getLayoutDimension(int index, String name) {
- try {
- // this will throw an exception if not found.
- return getDimension(index, name);
- } catch (RuntimeException e) {
-
- if (LayoutInflater_Delegate.sIsInInclude) {
- throw new RuntimeException("Layout Dimension '" + name + "' not found.");
- }
-
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
- "You must supply a " + name + " attribute.", null);
-
- return 0;
- }
- }
-
- @Override
- public int getLayoutDimension(int index, int defValue) {
- return getDimensionPixelSize(index, defValue);
- }
-
- /** @param name attribute name, used for error reporting. */
- private int getDimension(int index, @Nullable String name) {
- String s = getString(index);
- if (s == null) {
- if (name != null) {
- throw new RuntimeException("Attribute '" + name + "' not found");
- }
- throw new RuntimeException();
- }
- // Check if the value is a magic constant that doesn't require a unit.
- try {
- int i = Integer.parseInt(s);
- if (i == LayoutParams.MATCH_PARENT || i == LayoutParams.WRAP_CONTENT) {
- return i;
- }
- } catch (NumberFormatException ignored) {
- // pass
- }
- if (ResourceHelper.parseFloatAttribute(mNames[index], s, mValue, true)) {
- float f = mValue.getDimension(mBridgeResources.getDisplayMetrics());
-
- final int res = (int)(f+0.5f);
- if (res != 0) return res;
- if (f == 0) return 0;
- if (f > 0) return 1;
- }
-
- throw new RuntimeException();
- }
-
- /**
- * Retrieve a fractional unit attribute at index.
- *
- * @param index Index of attribute to retrieve.
- * @param base The base value of this fraction. In other words, a
- * standard fraction is multiplied by this value.
- * @param pbase The parent base value of this fraction. In other
- * words, a parent fraction (nn%p) is multiplied by this
- * value.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute fractional value multiplied by the appropriate
- * base value, or defValue if not defined.
- */
- @Override
- public float getFraction(int index, int base, int pbase, float defValue) {
- String value = getString(index);
- if (value == null) {
- return defValue;
- }
-
- if (ResourceHelper.parseFloatAttribute(mNames[index], value, mValue, false)) {
- return mValue.getFraction(base, pbase);
- }
-
- // looks like we were unable to resolve the fraction value
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_FORMAT,
- String.format(
- "\"%1$s\" in attribute \"%2$s\" cannot be converted to a fraction.",
- value, mNames[index]), null);
-
- return defValue;
- }
-
- /**
- * Retrieve the resource identifier for the attribute at
- * index. Note that attribute resource as resolved when
- * the overall {@link TypedArray} object is retrieved. As a
- * result, this function will return the resource identifier of the
- * final resource value that was found, not necessarily the
- * original resource that was specified by the attribute.
- *
- * @param index Index of attribute to retrieve.
- * @param defValue Value to return if the attribute is not defined or
- * not a resource.
- *
- * @return Attribute resource identifier, or defValue if not defined.
- */
- @Override
- public int getResourceId(int index, int defValue) {
- if (index < 0 || index >= mResourceData.length) {
- return defValue;
- }
-
- // get the Resource for this index
- ResourceValue resValue = mResourceData[index];
-
- // no data, return the default value.
- if (resValue == null) {
- return defValue;
- }
-
- // check if this is a style resource
- if (resValue instanceof StyleResourceValue) {
- // get the id that will represent this style.
- return mContext.getDynamicIdByStyle((StyleResourceValue)resValue);
- }
-
- // if the attribute was a reference to a resource, and not a declaration of an id (@+id),
- // then the xml attribute value was "resolved" which leads us to a ResourceValue with a
- // valid getType() and getName() returning a resource name.
- // (and getValue() returning null!). We need to handle this!
- if (resValue.getResourceType() != null) {
- // if this is a framework id
- if (mPlatformFile || resValue.isFramework()) {
- // look for idName in the android R classes
- return mContext.getFrameworkResourceValue(
- resValue.getResourceType(), resValue.getName(), defValue);
- }
-
- // look for idName in the project R class.
- return mContext.getProjectResourceValue(
- resValue.getResourceType(), resValue.getName(), defValue);
- }
-
- // else, try to get the value, and resolve it somehow.
- String value = resValue.getValue();
- if (value == null) {
- return defValue;
- }
- value = value.trim();
-
- // if the value is just an integer, return it.
- try {
- int i = Integer.parseInt(value);
- if (Integer.toString(i).equals(value)) {
- return i;
- }
- } catch (NumberFormatException e) {
- // pass
- }
-
- if (value.startsWith("#")) {
- // this looks like a color, do not try to parse it
- return defValue;
- }
-
- // Handle the @id/, @+id/ and @android:id/
- // We need to return the exact value that was compiled (from the various R classes),
- // as these values can be reused internally with calls to findViewById().
- // There's a trick with platform layouts that not use "android:" but their IDs are in
- // fact in the android.R and com.android.internal.R classes.
- // The field mPlatformFile will indicate that all IDs are to be looked up in the android R
- // classes exclusively.
-
- // if this is a reference to an id, find it.
- if (value.startsWith("@id/") || value.startsWith("@+") ||
- value.startsWith("@android:id/")) {
-
- int pos = value.indexOf('/');
- String idName = value.substring(pos + 1);
- boolean create = value.startsWith("@+");
- boolean isFrameworkId =
- mPlatformFile || value.startsWith("@android") || value.startsWith("@+android");
-
- // Look for the idName in project or android R class depending on isPlatform.
- if (create) {
- Integer idValue;
- if (isFrameworkId) {
- idValue = Bridge.getResourceId(ResourceType.ID, idName);
- } else {
- idValue = mContext.getLayoutlibCallback().getResourceId(ResourceType.ID, idName);
- }
- return idValue == null ? defValue : idValue;
- }
- // This calls the same method as in if(create), but doesn't create a dynamic id, if
- // one is not found.
- if (isFrameworkId) {
- return mContext.getFrameworkResourceValue(ResourceType.ID, idName, defValue);
- } else {
- return mContext.getProjectResourceValue(ResourceType.ID, idName, defValue);
- }
- }
- else if (value.startsWith("@aapt:_aapt")) {
- return mContext.getLayoutlibCallback().getResourceId(ResourceType.AAPT, value);
- }
-
- // not a direct id valid reference. First check if it's an enum (this is a corner case
- // for attributes that have a reference|enum type), then fallback to resolve
- // as an ID without prefix.
- Integer enumValue = resolveEnumAttribute(index);
- if (enumValue != null) {
- return enumValue;
- }
-
- // Ok, not an enum, resolve as an ID
- Integer idValue;
-
- if (resValue.isFramework()) {
- idValue = Bridge.getResourceId(resValue.getResourceType(),
- resValue.getName());
- } else {
- idValue = mContext.getLayoutlibCallback().getResourceId(
- resValue.getResourceType(), resValue.getName());
- }
-
- if (idValue != null) {
- return idValue;
- }
-
- Bridge.getLog().warning(LayoutLog.TAG_RESOURCES_RESOLVE,
- String.format(
- "Unable to resolve id \"%1$s\" for attribute \"%2$s\"", value, mNames[index]),
- resValue);
-
- return defValue;
- }
-
- @Override
- public int getThemeAttributeId(int index, int defValue) {
- // TODO: Get the right Theme Attribute ID to enable caching of the drawables.
- return defValue;
- }
-
- /**
- * Retrieve the Drawable for the attribute at index. This
- * gets the resource ID of the selected attribute, and uses
- * {@link Resources#getDrawable Resources.getDrawable} of the owning
- * Resources object to retrieve its Drawable.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return Drawable for the attribute, or null if not defined.
- */
- @Override
- public Drawable getDrawable(int index) {
- if (!hasValue(index)) {
- return null;
- }
-
- ResourceValue value = mResourceData[index];
- return ResourceHelper.getDrawable(value, mContext, mTheme);
- }
-
- /**
- * Version of {@link #getDrawable(int)} that accepts an override density.
- * @hide
- */
- @Override
- public Drawable getDrawableForDensity(int index, int density) {
- return getDrawable(index);
- }
-
- /**
- * Retrieve the Typeface for the attribute at index.
- * @param index Index of attribute to retrieve.
- *
- * @return Typeface for the attribute, or null if not defined.
- */
- @Override
- public Typeface getFont(int index) {
- if (!hasValue(index)) {
- return null;
- }
-
- ResourceValue value = mResourceData[index];
- return ResourceHelper.getFont(value, mContext, mTheme);
- }
-
- /**
- * Retrieve the CharSequence[] for the attribute at index.
- * This gets the resource ID of the selected attribute, and uses
- * {@link Resources#getTextArray Resources.getTextArray} of the owning
- * Resources object to retrieve its String[].
- *
- * @param index Index of attribute to retrieve.
- *
- * @return CharSequence[] for the attribute, or null if not defined.
- */
- @Override
- public CharSequence[] getTextArray(int index) {
- if (!hasValue(index)) {
- return null;
- }
- ResourceValue resVal = mResourceData[index];
- if (resVal instanceof ArrayResourceValue) {
- ArrayResourceValue array = (ArrayResourceValue) resVal;
- int count = array.getElementCount();
- return count >= 0 ? Resources_Delegate.fillValues(mBridgeResources, array, new CharSequence[count]) :
- null;
- }
- int id = getResourceId(index, 0);
- String resIdMessage = id > 0 ? " (resource id 0x" + Integer.toHexString(id) + ')' : "";
- assert false :
- String.format("%1$s in %2$s%3$s is not a valid array resource.", resVal.getValue(),
- mNames[index], resIdMessage);
-
- return new CharSequence[0];
- }
-
- @Override
- public int[] extractThemeAttrs() {
- // The drawables are always inflated with a Theme and we don't care about caching. So,
- // just return.
- return null;
- }
-
- @Override
- public int getChangingConfigurations() {
- // We don't care about caching. Any change in configuration is a fresh render. So,
- // just return.
- return 0;
- }
-
- /**
- * Retrieve the raw TypedValue for the attribute at index.
- *
- * @param index Index of attribute to retrieve.
- * @param outValue TypedValue object in which to place the attribute's
- * data.
- *
- * @return Returns true if the value was retrieved, else false.
- */
- @Override
- public boolean getValue(int index, TypedValue outValue) {
- // TODO: more switch cases for other types.
- outValue.type = getType(index);
- switch (outValue.type) {
- case TYPE_NULL:
- return false;
- case TYPE_STRING:
- outValue.string = getString(index);
- return true;
- default:
- // For back-compatibility, parse as float.
- String s = getString(index);
- return s != null &&
- ResourceHelper.parseFloatAttribute(mNames[index], s, outValue, false);
- }
- }
-
- @Override
- @SuppressWarnings("ResultOfMethodCallIgnored")
- public int getType(int index) {
- String value = getString(index);
- if (value == null) {
- return TYPE_NULL;
- }
- if (value.startsWith(PREFIX_RESOURCE_REF)) {
- return TYPE_REFERENCE;
- }
- if (value.startsWith(PREFIX_THEME_REF)) {
- return TYPE_ATTRIBUTE;
- }
- try {
- // Don't care about the value. Only called to check if an exception is thrown.
- convertValueToInt(value, 0);
- if (value.startsWith("0x") || value.startsWith("0X")) {
- return TYPE_INT_HEX;
- }
- // is it a color?
- if (value.startsWith("#")) {
- int length = value.length() - 1;
- if (length == 3) { // rgb
- return TYPE_INT_COLOR_RGB4;
- }
- if (length == 4) { // argb
- return TYPE_INT_COLOR_ARGB4;
- }
- if (length == 6) { // rrggbb
- return TYPE_INT_COLOR_RGB8;
- }
- if (length == 8) { // aarrggbb
- return TYPE_INT_COLOR_ARGB8;
- }
- }
- if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
- return TYPE_INT_BOOLEAN;
- }
- return TYPE_INT_DEC;
- } catch (NumberFormatException ignored) {
- try {
- Float.parseFloat(value);
- return TYPE_FLOAT;
- } catch (NumberFormatException ignore) {
- }
- // Might be a dimension.
- if (ResourceHelper.parseFloatAttribute(null, value, new TypedValue(), false)) {
- return TYPE_DIMENSION;
- }
- }
- // TODO: handle fractions.
- return TYPE_STRING;
- }
-
- /**
- * Determines whether there is an attribute at index.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return True if the attribute has a value, false otherwise.
- */
- @Override
- public boolean hasValue(int index) {
- return index >= 0 && index < mResourceData.length && mResourceData[index] != null;
- }
-
- @Override
- public boolean hasValueOrEmpty(int index) {
- return hasValue(index) || index >= 0 && index < mResourceData.length &&
- mEmptyIds != null && Arrays.binarySearch(mEmptyIds, index) >= 0;
- }
-
- /**
- * Retrieve the raw TypedValue for the attribute at index
- * and return a temporary object holding its data. This object is only
- * valid until the next call on to {@link TypedArray}.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return Returns a TypedValue object if the attribute is defined,
- * containing its data; otherwise returns null. (You will not
- * receive a TypedValue whose type is TYPE_NULL.)
- */
- @Override
- public TypedValue peekValue(int index) {
- if (index < 0 || index >= mResourceData.length) {
- return null;
- }
-
- if (getValue(index, mValue)) {
- return mValue;
- }
-
- return null;
- }
-
- /**
- * Returns a message about the parser state suitable for printing error messages.
- */
- @Override
- public String getPositionDescription() {
- return "";
- }
-
- /**
- * Give back a previously retrieved TypedArray, for later re-use.
- */
- @Override
- public void recycle() {
- // pass
- }
-
- @Override
- public String toString() {
- return Arrays.toString(mResourceData);
- }
-
- /**
- * Searches for the string in the attributes (flag or enums) and returns the integer.
- * If found, it will return an integer matching the value.
- *
- * @param index Index of attribute to retrieve.
- *
- * @return Attribute int value, or null if not defined.
- */
- private Integer resolveEnumAttribute(int index) {
- // Get the map of attribute-constant -> IntegerValue
- Map map = null;
- if (mIsFramework[index]) {
- map = Bridge.getEnumValues(mNames[index]);
- } else {
- // get the styleable matching the resolved name
- RenderResources res = mContext.getRenderResources();
- ResourceValue attr = res.getProjectResource(ResourceType.ATTR, mNames[index]);
- if (attr instanceof AttrResourceValue) {
- map = ((AttrResourceValue) attr).getAttributeValues();
- }
- }
-
- if (map != null) {
- // accumulator to store the value of the 1+ constants.
- int result = 0;
- boolean found = false;
-
- // split the value in case this is a mix of several flags.
- String[] keywords = mResourceData[index].getValue().split("\\|");
- for (String keyword : keywords) {
- Integer i = map.get(keyword.trim());
- if (i != null) {
- result |= i;
- found = true;
- }
- // TODO: We should act smartly and log a warning for incorrect keywords. However,
- // this method is currently called even if the resourceValue is not an enum.
- }
- if (found) {
- return result;
- }
- }
-
- return null;
- }
-
- /**
- * Copied from {@link XmlUtils#convertValueToInt(CharSequence, int)}, but adapted to account
- * for aapt, and the fact that host Java VM's Integer.parseInt("XXXXXXXX", 16) cannot handle
- * "XXXXXXXX" > 80000000.
- */
- private static int convertValueToInt(@Nullable String charSeq, int defValue) {
- if (null == charSeq || charSeq.isEmpty())
- return defValue;
-
- int sign = 1;
- int index = 0;
- int len = charSeq.length();
- int base = 10;
-
- if ('-' == charSeq.charAt(0)) {
- sign = -1;
- index++;
- }
-
- if ('0' == charSeq.charAt(index)) {
- // Quick check for a zero by itself
- if (index == (len - 1))
- return 0;
-
- char c = charSeq.charAt(index + 1);
-
- if ('x' == c || 'X' == c) {
- index += 2;
- base = 16;
- } else {
- index++;
- // Leave the base as 10. aapt removes the preceding zero, and thus when framework
- // sees the value, it only gets the decimal value.
- }
- } else if ('#' == charSeq.charAt(index)) {
- return ResourceHelper.getColor(charSeq) * sign;
- } else if ("true".equals(charSeq) || "TRUE".equals(charSeq)) {
- return -1;
- } else if ("false".equals(charSeq) || "FALSE".equals(charSeq)) {
- return 0;
- }
-
- // Use Long, since we want to handle hex ints > 80000000.
- return ((int)Long.parseLong(charSeq.substring(index), base)) * sign;
- }
-
- static TypedArray obtain(Resources res, int len) {
- return new BridgeTypedArray(res, null, len, true);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/ComplexColor_Accessor.java b/tools/layoutlib/bridge/src/android/content/res/ComplexColor_Accessor.java
deleted file mode 100644
index 09c0260196cfa..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/ComplexColor_Accessor.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.res.Resources.Theme;
-import android.util.AttributeSet;
-
-import java.io.IOException;
-
-/**
- * Class that provides access to the {@link GradientColor#createFromXmlInner(Resources,
- * XmlPullParser, AttributeSet, Theme)} and {@link ColorStateList#createFromXmlInner(Resources,
- * XmlPullParser, AttributeSet, Theme)} methods
- */
-public class ComplexColor_Accessor {
- public static GradientColor createGradientColorFromXmlInner(@NonNull Resources r,
- @NonNull XmlPullParser parser, @NonNull AttributeSet attrs, @Nullable Theme theme)
- throws IOException, XmlPullParserException {
- return GradientColor.createFromXmlInner(r, parser, attrs, theme);
- }
-
- public static ColorStateList createColorStateListFromXmlInner(@NonNull Resources r,
- @NonNull XmlPullParser parser, @NonNull AttributeSet attrs, @Nullable Theme theme)
- throws IOException, XmlPullParserException {
- return ColorStateList.createFromXmlInner(r, parser, attrs, theme);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/Resources_Delegate.java b/tools/layoutlib/bridge/src/android/content/res/Resources_Delegate.java
deleted file mode 100644
index c20ee12ee30c5..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/Resources_Delegate.java
+++ /dev/null
@@ -1,1025 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.api.ArrayResourceValue;
-import com.android.ide.common.rendering.api.DensityBasedResourceValue;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.LayoutlibCallback;
-import com.android.ide.common.rendering.api.PluralsResourceValue;
-import com.android.ide.common.rendering.api.RenderResources;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.BridgeConstants;
-import com.android.layoutlib.bridge.android.BridgeContext;
-import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
-import com.android.layoutlib.bridge.impl.ParserFactory;
-import com.android.layoutlib.bridge.impl.ResourceHelper;
-import com.android.layoutlib.bridge.util.NinePatchInputStream;
-import com.android.ninepatch.NinePatch;
-import com.android.resources.ResourceType;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-import com.android.util.Pair;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.res.Resources.NotFoundException;
-import android.content.res.Resources.Theme;
-import android.graphics.Typeface;
-import android.graphics.drawable.Drawable;
-import android.icu.text.PluralRules;
-import android.util.AttributeSet;
-import android.util.DisplayMetrics;
-import android.util.LruCache;
-import android.util.TypedValue;
-import android.view.DisplayAdjustments;
-import android.view.ViewGroup.LayoutParams;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.Iterator;
-
-@SuppressWarnings("deprecation")
-public class Resources_Delegate {
-
- private static boolean[] mPlatformResourceFlag = new boolean[1];
- // TODO: This cache is cleared every time a render session is disposed. Look into making this
- // more long lived.
- private static LruCache sDrawableCache = new LruCache<>(50);
-
- public static Resources initSystem(BridgeContext context,
- AssetManager assets,
- DisplayMetrics metrics,
- Configuration config,
- LayoutlibCallback layoutlibCallback) {
- Resources resources = new Resources(Resources_Delegate.class.getClassLoader());
- resources.setImpl(new ResourcesImpl(assets, metrics, config, new DisplayAdjustments()));
- resources.mContext = context;
- resources.mLayoutlibCallback = layoutlibCallback;
- return Resources.mSystem = resources;
- }
-
- /**
- * Disposes the static {@link Resources#mSystem} to make sure we don't leave objects around that
- * would prevent us from unloading the library.
- */
- public static void disposeSystem() {
- sDrawableCache.evictAll();
- Resources.mSystem.mContext = null;
- Resources.mSystem.mLayoutlibCallback = null;
- Resources.mSystem = null;
- }
-
- public static BridgeTypedArray newTypeArray(Resources resources, int numEntries,
- boolean platformFile) {
- return new BridgeTypedArray(resources, resources.mContext, numEntries, platformFile);
- }
-
- private static Pair getResourceInfo(Resources resources, int id,
- boolean[] platformResFlag_out) {
- // first get the String related to this id in the framework
- Pair resourceInfo = Bridge.resolveResourceId(id);
-
- // Set the layoutlib callback and context for resources
- if (resources != Resources.mSystem && resources.mLayoutlibCallback == null) {
- resources.mLayoutlibCallback = Resources.mSystem.mLayoutlibCallback;
- resources.mContext = Resources.mSystem.mContext;
- }
-
- if (resourceInfo != null) {
- platformResFlag_out[0] = true;
- return resourceInfo;
- }
-
- // didn't find a match in the framework? look in the project.
- if (resources.mLayoutlibCallback != null) {
- resourceInfo = resources.mLayoutlibCallback.resolveResourceId(id);
-
- if (resourceInfo != null) {
- platformResFlag_out[0] = false;
- return resourceInfo;
- }
- }
- return null;
- }
-
- private static Pair getResourceValue(Resources resources, int id,
- boolean[] platformResFlag_out) {
- Pair resourceInfo =
- getResourceInfo(resources, id, platformResFlag_out);
-
- if (resourceInfo != null) {
- String attributeName = resourceInfo.getSecond();
- RenderResources renderResources = resources.mContext.getRenderResources();
- ResourceValue value = platformResFlag_out[0] ?
- renderResources.getFrameworkResource(resourceInfo.getFirst(), attributeName) :
- renderResources.getProjectResource(resourceInfo.getFirst(), attributeName);
-
- if (value == null) {
- // Unable to resolve the attribute, just leave the unresolved value
- value = new ResourceValue(resourceInfo.getFirst(), attributeName, attributeName,
- platformResFlag_out[0]);
- }
- return Pair.of(attributeName, value);
- }
-
- return null;
- }
-
- @LayoutlibDelegate
- static Drawable getDrawable(Resources resources, int id) {
- return getDrawable(resources, id, null);
- }
-
- @LayoutlibDelegate
- static Drawable getDrawable(Resources resources, int id, Theme theme) {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
- if (value != null) {
- String key = value.getSecond().getValue();
-
- Drawable.ConstantState constantState = key != null ? sDrawableCache.get(key) : null;
- Drawable drawable;
- if (constantState != null) {
- drawable = constantState.newDrawable(resources, theme);
- } else {
- drawable =
- ResourceHelper.getDrawable(value.getSecond(), resources.mContext, theme);
-
- if (key != null) {
- sDrawableCache.put(key, drawable.getConstantState());
- }
- }
-
- return drawable;
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static int getColor(Resources resources, int id) {
- return getColor(resources, id, null);
- }
-
- @LayoutlibDelegate
- static int getColor(Resources resources, int id, Theme theme) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resourceValue = value.getSecond();
- try {
- return ResourceHelper.getColor(resourceValue.getValue());
- } catch (NumberFormatException e) {
- // Check if the value passed is a file. If it is, mostly likely, user is referencing
- // a color state list from a place where they should reference only a pure color.
- String message;
- if (new File(resourceValue.getValue()).isFile()) {
- String resource = (resourceValue.isFramework() ? "@android:" : "@") + "color/"
- + resourceValue.getName();
- message = "Hexadecimal color expected, found Color State List for " + resource;
- } else {
- message = e.getMessage();
- }
- Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT, message, e, null);
- return 0;
- }
- }
-
- // Suppress possible NPE. getColorStateList will never return null, it will instead
- // throw an exception, but intelliJ can't figure that out
- //noinspection ConstantConditions
- return getColorStateList(resources, id, theme).getDefaultColor();
- }
-
- @LayoutlibDelegate
- static ColorStateList getColorStateList(Resources resources, int id) throws NotFoundException {
- return getColorStateList(resources, id, null);
- }
-
- @LayoutlibDelegate
- static ColorStateList getColorStateList(Resources resources, int id, Theme theme)
- throws NotFoundException {
- Pair resValue =
- getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (resValue != null) {
- ColorStateList stateList = ResourceHelper.getColorStateList(resValue.getSecond(),
- resources.mContext);
- if (stateList != null) {
- return stateList.obtainForTheme(theme);
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static CharSequence getText(Resources resources, int id, CharSequence def) {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- return v;
- }
- }
- }
-
- return def;
- }
-
- @LayoutlibDelegate
- static CharSequence getText(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- return v;
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static CharSequence[] getTextArray(Resources resources, int id) throws NotFoundException {
- ResourceValue resValue = getArrayResourceValue(resources, id);
- if (resValue == null) {
- // Error already logged by getArrayResourceValue.
- return new CharSequence[0];
- } else if (!(resValue instanceof ArrayResourceValue)) {
- return new CharSequence[]{
- resolveReference(resources, resValue.getValue(), resValue.isFramework())};
- }
- ArrayResourceValue arv = ((ArrayResourceValue) resValue);
- return fillValues(resources, arv, new CharSequence[arv.getElementCount()]);
- }
-
- @LayoutlibDelegate
- static String[] getStringArray(Resources resources, int id) throws NotFoundException {
- ResourceValue resValue = getArrayResourceValue(resources, id);
- if (resValue == null) {
- // Error already logged by getArrayResourceValue.
- return new String[0];
- } else if (!(resValue instanceof ArrayResourceValue)) {
- return new String[]{
- resolveReference(resources, resValue.getValue(), resValue.isFramework())};
- }
- ArrayResourceValue arv = ((ArrayResourceValue) resValue);
- return fillValues(resources, arv, new String[arv.getElementCount()]);
- }
-
- /**
- * Resolve each element in resValue and copy them to {@code values}. The values copied are
- * always Strings. The ideal signature for the method should be <T super String>, but java
- * generics don't support it.
- */
- static T[] fillValues(Resources resources, ArrayResourceValue resValue,
- T[] values) {
- int i = 0;
- for (Iterator iterator = resValue.iterator(); iterator.hasNext(); i++) {
- @SuppressWarnings("unchecked")
- T s = (T) resolveReference(resources, iterator.next(), resValue.isFramework());
- values[i] = s;
- }
- return values;
- }
-
- @LayoutlibDelegate
- static int[] getIntArray(Resources resources, int id) throws NotFoundException {
- ResourceValue rv = getArrayResourceValue(resources, id);
- if (rv == null) {
- // Error already logged by getArrayResourceValue.
- return new int[0];
- } else if (!(rv instanceof ArrayResourceValue)) {
- // This is an older IDE that can only give us the first element of the array.
- String firstValue = resolveReference(resources, rv.getValue(), rv.isFramework());
- try {
- return new int[]{getInt(firstValue)};
- } catch (NumberFormatException e) {
- Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
- "Integer resource array contains non-integer value: " +
- firstValue, null);
- return new int[1];
- }
- }
- ArrayResourceValue resValue = ((ArrayResourceValue) rv);
- int[] values = new int[resValue.getElementCount()];
- int i = 0;
- for (Iterator iterator = resValue.iterator(); iterator.hasNext(); i++) {
- String element = resolveReference(resources, iterator.next(), resValue.isFramework());
- try {
- values[i] = getInt(element);
- } catch (NumberFormatException e) {
- Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
- "Integer resource array contains non-integer value: " + element, null);
- }
- }
- return values;
- }
-
- /**
- * Try to find the ArrayResourceValue for the given id.
- *
- * If the ResourceValue found is not of type {@link ResourceType#ARRAY}, the method logs an
- * error and return null. However, if the ResourceValue found has type {@code
- * ResourceType.ARRAY}, but the value is not an instance of {@link ArrayResourceValue}, the
- * method returns the ResourceValue. This happens on older versions of the IDE, which did not
- * parse the array resources properly.
- *
- *
- * @throws NotFoundException if no resource if found
- */
- @Nullable
- private static ResourceValue getArrayResourceValue(Resources resources, int id)
- throws NotFoundException {
- Pair v = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (v != null) {
- ResourceValue resValue = v.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- final ResourceType type = resValue.getResourceType();
- if (type != ResourceType.ARRAY) {
- Bridge.getLog().error(LayoutLog.TAG_RESOURCES_RESOLVE,
- String.format(
- "Resource with id 0x%1$X is not an array resource, but %2$s",
- id, type == null ? "null" : type.getDisplayName()),
- null);
- return null;
- }
- if (!(resValue instanceof ArrayResourceValue)) {
- Bridge.getLog().warning(LayoutLog.TAG_UNSUPPORTED,
- "Obtaining resource arrays via getTextArray, getStringArray or getIntArray is not fully supported in this version of the IDE.",
- null);
- }
- return resValue;
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @NonNull
- private static String resolveReference(Resources resources, @NonNull String ref,
- boolean forceFrameworkOnly) {
- if (ref.startsWith(SdkConstants.PREFIX_RESOURCE_REF) || ref.startsWith
- (SdkConstants.PREFIX_THEME_REF)) {
- ResourceValue rv =
- resources.mContext.getRenderResources().findResValue(ref, forceFrameworkOnly);
- rv = resources.mContext.getRenderResources().resolveResValue(rv);
- if (rv != null) {
- return rv.getValue();
- }
- }
- // Not a reference.
- return ref;
- }
-
- @LayoutlibDelegate
- static XmlResourceParser getLayout(Resources resources, int id) throws NotFoundException {
- Pair v = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (v != null) {
- ResourceValue value = v.getSecond();
- XmlPullParser parser = null;
-
- try {
- // check if the current parser can provide us with a custom parser.
- if (!mPlatformResourceFlag[0]) {
- parser = resources.mLayoutlibCallback.getParser(value);
- }
-
- // create a new one manually if needed.
- if (parser == null) {
- File xml = new File(value.getValue());
- if (xml.isFile()) {
- // we need to create a pull parser around the layout XML file, and then
- // give that to our XmlBlockParser
- parser = ParserFactory.create(xml, true);
- }
- }
-
- if (parser != null) {
- return new BridgeXmlBlockParser(parser, resources.mContext,
- mPlatformResourceFlag[0]);
- }
- } catch (XmlPullParserException e) {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Failed to configure parser for " + value.getValue(), e, null /*data*/);
- // we'll return null below.
- } catch (FileNotFoundException e) {
- // this shouldn't happen since we check above.
- }
-
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static XmlResourceParser getAnimation(Resources resources, int id) throws NotFoundException {
- Pair v = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (v != null) {
- ResourceValue value = v.getSecond();
- XmlPullParser parser;
-
- try {
- File xml = new File(value.getValue());
- if (xml.isFile()) {
- // we need to create a pull parser around the layout XML file, and then
- // give that to our XmlBlockParser
- parser = ParserFactory.create(xml);
-
- return new BridgeXmlBlockParser(parser, resources.mContext,
- mPlatformResourceFlag[0]);
- }
- } catch (XmlPullParserException e) {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Failed to configure parser for " + value.getValue(), e, null /*data*/);
- // we'll return null below.
- } catch (FileNotFoundException e) {
- // this shouldn't happen since we check above.
- }
-
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static TypedArray obtainAttributes(Resources resources, AttributeSet set, int[] attrs) {
- return resources.mContext.obtainStyledAttributes(set, attrs);
- }
-
- @LayoutlibDelegate
- static TypedArray obtainAttributes(Resources resources, Resources.Theme theme, AttributeSet
- set, int[] attrs) {
- return Resources.obtainAttributes_Original(resources, theme, set, attrs);
- }
-
- @LayoutlibDelegate
- static TypedArray obtainTypedArray(Resources resources, int id) throws NotFoundException {
- throw new UnsupportedOperationException();
- }
-
- @LayoutlibDelegate
- static float getDimension(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- if (v.equals(BridgeConstants.MATCH_PARENT) ||
- v.equals(BridgeConstants.FILL_PARENT)) {
- return LayoutParams.MATCH_PARENT;
- } else if (v.equals(BridgeConstants.WRAP_CONTENT)) {
- return LayoutParams.WRAP_CONTENT;
- }
- TypedValue tmpValue = new TypedValue();
- if (ResourceHelper.parseFloatAttribute(
- value.getFirst(), v, tmpValue, true /*requireUnit*/) &&
- tmpValue.type == TypedValue.TYPE_DIMENSION) {
- return tmpValue.getDimension(resources.getDisplayMetrics());
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return 0;
- }
-
- @LayoutlibDelegate
- static int getDimensionPixelOffset(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- TypedValue tmpValue = new TypedValue();
- if (ResourceHelper.parseFloatAttribute(
- value.getFirst(), v, tmpValue, true /*requireUnit*/) &&
- tmpValue.type == TypedValue.TYPE_DIMENSION) {
- return TypedValue.complexToDimensionPixelOffset(tmpValue.data,
- resources.getDisplayMetrics());
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return 0;
- }
-
- @LayoutlibDelegate
- static int getDimensionPixelSize(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- TypedValue tmpValue = new TypedValue();
- if (ResourceHelper.parseFloatAttribute(
- value.getFirst(), v, tmpValue, true /*requireUnit*/) &&
- tmpValue.type == TypedValue.TYPE_DIMENSION) {
- return TypedValue.complexToDimensionPixelSize(tmpValue.data,
- resources.getDisplayMetrics());
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return 0;
- }
-
- @LayoutlibDelegate
- static int getInteger(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- assert resValue != null;
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- try {
- return getInt(v);
- } catch (NumberFormatException e) {
- // return exception below
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return 0;
- }
-
- @LayoutlibDelegate
- static boolean getBoolean(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resValue = value.getSecond();
-
- if (resValue != null) {
- String v = resValue.getValue();
- if (v != null) {
- return Boolean.parseBoolean(v);
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return false;
- }
-
- @LayoutlibDelegate
- static String getResourceEntryName(Resources resources, int resid) throws NotFoundException {
- Pair resourceInfo = getResourceInfo(resources, resid, new boolean[1]);
- if (resourceInfo != null) {
- return resourceInfo.getSecond();
- }
- throwException(resid, null);
- return null;
-
- }
-
- @LayoutlibDelegate
- static String getResourceName(Resources resources, int resid) throws NotFoundException {
- boolean[] platformOut = new boolean[1];
- Pair resourceInfo = getResourceInfo(resources, resid, platformOut);
- String packageName;
- if (resourceInfo != null) {
- if (platformOut[0]) {
- packageName = SdkConstants.ANDROID_NS_NAME;
- } else {
- packageName = resources.mContext.getPackageName();
- packageName = packageName == null ? SdkConstants.APP_PREFIX : packageName;
- }
- return packageName + ':' + resourceInfo.getFirst().getName() + '/' +
- resourceInfo.getSecond();
- }
- throwException(resid, null);
- return null;
- }
-
- @LayoutlibDelegate
- static String getResourcePackageName(Resources resources, int resid) throws NotFoundException {
- boolean[] platformOut = new boolean[1];
- Pair resourceInfo = getResourceInfo(resources, resid, platformOut);
- if (resourceInfo != null) {
- if (platformOut[0]) {
- return SdkConstants.ANDROID_NS_NAME;
- }
- String packageName = resources.mContext.getPackageName();
- return packageName == null ? SdkConstants.APP_PREFIX : packageName;
- }
- throwException(resid, null);
- return null;
- }
-
- @LayoutlibDelegate
- static String getResourceTypeName(Resources resources, int resid) throws NotFoundException {
- Pair resourceInfo = getResourceInfo(resources, resid, new boolean[1]);
- if (resourceInfo != null) {
- return resourceInfo.getFirst().getName();
- }
- throwException(resid, null);
- return null;
- }
-
- @LayoutlibDelegate
- static String getString(Resources resources, int id, Object... formatArgs)
- throws NotFoundException {
- String s = getString(resources, id);
- if (s != null) {
- return String.format(s, formatArgs);
-
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static String getString(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null && value.getSecond().getValue() != null) {
- return value.getSecond().getValue();
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static String getQuantityString(Resources resources, int id, int quantity) throws
- NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- if (value.getSecond() instanceof PluralsResourceValue) {
- PluralsResourceValue pluralsResourceValue = (PluralsResourceValue) value.getSecond();
- PluralRules pluralRules = PluralRules.forLocale(resources.getConfiguration().getLocales()
- .get(0));
- String strValue = pluralsResourceValue.getValue(pluralRules.select(quantity));
- if (strValue == null) {
- strValue = pluralsResourceValue.getValue(PluralRules.KEYWORD_OTHER);
- }
-
- return strValue;
- }
- else {
- return value.getSecond().getValue();
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static String getQuantityString(Resources resources, int id, int quantity, Object... formatArgs)
- throws NotFoundException {
- String raw = getQuantityString(resources, id, quantity);
- return String.format(resources.getConfiguration().getLocales().get(0), raw, formatArgs);
- }
-
- @LayoutlibDelegate
- static CharSequence getQuantityText(Resources resources, int id, int quantity) throws
- NotFoundException {
- return getQuantityString(resources, id, quantity);
- }
-
- @LayoutlibDelegate
- static Typeface getFont(Resources resources, int id) throws
- NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
- if (value != null) {
- return ResourceHelper.getFont(value.getSecond(), resources.mContext, null);
- }
-
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static Typeface getFont(Resources resources, TypedValue outValue, int id) throws
- NotFoundException {
- Resources_Delegate.getValue(resources, id, outValue, true);
- if (outValue.string != null) {
- return ResourceHelper.getFont(outValue.string.toString(), resources.mContext, null,
- mPlatformResourceFlag[0]);
- }
-
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static void getValue(Resources resources, int id, TypedValue outValue, boolean resolveRefs)
- throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- ResourceValue resVal = value.getSecond();
- String v = resVal.getValue();
-
- if (v != null) {
- if (ResourceHelper.parseFloatAttribute(value.getFirst(), v, outValue,
- false /*requireUnit*/)) {
- return;
- }
- if (resVal instanceof DensityBasedResourceValue) {
- outValue.density =
- ((DensityBasedResourceValue) resVal).getResourceDensity().getDpiValue();
- }
-
- // else it's a string
- outValue.type = TypedValue.TYPE_STRING;
- outValue.string = v;
- return;
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
- }
-
- @LayoutlibDelegate
- static void getValue(Resources resources, String name, TypedValue outValue, boolean resolveRefs)
- throws NotFoundException {
- throw new UnsupportedOperationException();
- }
-
- @LayoutlibDelegate
- static XmlResourceParser getXml(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- String v = value.getSecond().getValue();
-
- if (v != null) {
- // check this is a file
- File f = new File(v);
- if (f.isFile()) {
- try {
- XmlPullParser parser = ParserFactory.create(f);
-
- return new BridgeXmlBlockParser(parser, resources.mContext,
- mPlatformResourceFlag[0]);
- } catch (XmlPullParserException e) {
- NotFoundException newE = new NotFoundException();
- newE.initCause(e);
- throw newE;
- } catch (FileNotFoundException e) {
- NotFoundException newE = new NotFoundException();
- newE.initCause(e);
- throw newE;
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static XmlResourceParser loadXmlResourceParser(Resources resources, int id,
- String type) throws NotFoundException {
- return resources.loadXmlResourceParser_Original(id, type);
- }
-
- @LayoutlibDelegate
- static XmlResourceParser loadXmlResourceParser(Resources resources, String file, int id,
- int assetCookie, String type) throws NotFoundException {
- // even though we know the XML file to load directly, we still need to resolve the
- // id so that we can know if it's a platform or project resource.
- // (mPlatformResouceFlag will get the result and will be used later).
- getResourceValue(resources, id, mPlatformResourceFlag);
-
- File f = new File(file);
- try {
- XmlPullParser parser = ParserFactory.create(f);
-
- return new BridgeXmlBlockParser(parser, resources.mContext, mPlatformResourceFlag[0]);
- } catch (XmlPullParserException e) {
- NotFoundException newE = new NotFoundException();
- newE.initCause(e);
- throw newE;
- } catch (FileNotFoundException e) {
- NotFoundException newE = new NotFoundException();
- newE.initCause(e);
- throw newE;
- }
- }
-
- @LayoutlibDelegate
- static InputStream openRawResource(Resources resources, int id) throws NotFoundException {
- Pair value = getResourceValue(resources, id, mPlatformResourceFlag);
-
- if (value != null) {
- String path = value.getSecond().getValue();
-
- if (path != null) {
- // check this is a file
- File f = new File(path);
- if (f.isFile()) {
- try {
- // if it's a nine-patch return a custom input stream so that
- // other methods (mainly bitmap factory) can detect it's a 9-patch
- // and actually load it as a 9-patch instead of a normal bitmap
- if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
- return new NinePatchInputStream(f);
- }
- return new FileInputStream(f);
- } catch (FileNotFoundException e) {
- NotFoundException newE = new NotFoundException();
- newE.initCause(e);
- throw newE;
- }
- }
- }
- }
-
- // id was not found or not resolved. Throw a NotFoundException.
- throwException(resources, id);
-
- // this is not used since the method above always throws
- return null;
- }
-
- @LayoutlibDelegate
- static InputStream openRawResource(Resources resources, int id, TypedValue value) throws
- NotFoundException {
- getValue(resources, id, value, true);
-
- String path = value.string.toString();
-
- File f = new File(path);
- if (f.isFile()) {
- try {
- // if it's a nine-patch return a custom input stream so that
- // other methods (mainly bitmap factory) can detect it's a 9-patch
- // and actually load it as a 9-patch instead of a normal bitmap
- if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
- return new NinePatchInputStream(f);
- }
- return new FileInputStream(f);
- } catch (FileNotFoundException e) {
- NotFoundException exception = new NotFoundException();
- exception.initCause(e);
- throw exception;
- }
- }
-
- throw new NotFoundException();
- }
-
- @LayoutlibDelegate
- static AssetFileDescriptor openRawResourceFd(Resources resources, int id) throws
- NotFoundException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Builds and throws a {@link Resources.NotFoundException} based on a resource id and a resource
- * type.
- *
- * @param id the id of the resource
- *
- * @throws NotFoundException
- */
- private static void throwException(Resources resources, int id) throws NotFoundException {
- throwException(id, getResourceInfo(resources, id, new boolean[1]));
- }
-
- private static void throwException(int id, @Nullable Pair resourceInfo) {
- String message;
- if (resourceInfo != null) {
- message = String.format(
- "Could not find %1$s resource matching value 0x%2$X (resolved name: %3$s) in current configuration.",
- resourceInfo.getFirst(), id, resourceInfo.getSecond());
- } else {
- message = String.format("Could not resolve resource value: 0x%1$X.", id);
- }
-
- throw new NotFoundException(message);
- }
-
- private static int getInt(String v) throws NumberFormatException {
- int radix = 10;
- if (v.startsWith("0x")) {
- v = v.substring(2);
- radix = 16;
- } else if (v.startsWith("0")) {
- radix = 8;
- }
- return Integer.parseInt(v, radix);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java b/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java
deleted file mode 100644
index f1e8fc21ce0e2..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/Resources_Theme_Delegate.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.ide.common.rendering.api.ResourceReference;
-import com.android.ide.common.rendering.api.StyleResourceValue;
-import com.android.layoutlib.bridge.android.BridgeContext;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.impl.RenderSessionImpl;
-import com.android.resources.ResourceType;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.Nullable;
-import android.content.res.Resources.NotFoundException;
-import android.content.res.Resources.Theme;
-import android.content.res.Resources.ThemeKey;
-import android.util.AttributeSet;
-import android.util.TypedValue;
-
-/**
- * Delegate used to provide new implementation of a select few methods of {@link Resources.Theme}
- *
- * Through the layoutlib_create tool, the original methods of Theme have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- */
-public class Resources_Theme_Delegate {
-
- // ---- delegate manager ----
-
- private static final DelegateManager sManager =
- new DelegateManager(Resources_Theme_Delegate.class);
-
- public static DelegateManager getDelegateManager() {
- return sManager;
- }
-
- // ---- delegate methods. ----
-
- @LayoutlibDelegate
- /*package*/ static TypedArray obtainStyledAttributes(
- Resources thisResources, Theme thisTheme,
- int[] attrs) {
- boolean changed = setupResources(thisTheme);
- BridgeTypedArray ta = RenderSessionImpl.getCurrentContext().obtainStyledAttributes(attrs);
- ta.setTheme(thisTheme);
- restoreResources(changed);
- return ta;
- }
-
- @LayoutlibDelegate
- /*package*/ static TypedArray obtainStyledAttributes(
- Resources thisResources, Theme thisTheme,
- int resid, int[] attrs)
- throws NotFoundException {
- boolean changed = setupResources(thisTheme);
- BridgeTypedArray ta = RenderSessionImpl.getCurrentContext().obtainStyledAttributes(resid,
- attrs);
- ta.setTheme(thisTheme);
- restoreResources(changed);
- return ta;
- }
-
- @LayoutlibDelegate
- /*package*/ static TypedArray obtainStyledAttributes(
- Resources thisResources, Theme thisTheme,
- AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
- boolean changed = setupResources(thisTheme);
- BridgeTypedArray ta = RenderSessionImpl.getCurrentContext().obtainStyledAttributes(set,
- attrs, defStyleAttr, defStyleRes);
- ta.setTheme(thisTheme);
- restoreResources(changed);
- return ta;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean resolveAttribute(
- Resources thisResources, Theme thisTheme,
- int resid, TypedValue outValue,
- boolean resolveRefs) {
- boolean changed = setupResources(thisTheme);
- boolean found = RenderSessionImpl.getCurrentContext().resolveThemeAttribute(resid,
- outValue, resolveRefs);
- restoreResources(changed);
- return found;
- }
-
- @LayoutlibDelegate
- /*package*/ static TypedArray resolveAttributes(Resources thisResources, Theme thisTheme,
- int[] values, int[] attrs) {
- // FIXME
- return null;
- }
-
- // ---- private helper methods ----
-
- private static boolean setupResources(Theme thisTheme) {
- // Key is a space-separated list of theme ids applied that have been merged into the
- // BridgeContext's theme to make thisTheme.
- final ThemeKey key = thisTheme.getKey();
- final int[] resId = key.mResId;
- final boolean[] force = key.mForce;
-
- boolean changed = false;
- for (int i = 0, N = key.mCount; i < N; i++) {
- StyleResourceValue style = resolveStyle(resId[i]);
- if (style != null) {
- RenderSessionImpl.getCurrentContext().getRenderResources().applyStyle(
- style, force[i]);
- changed = true;
- }
-
- }
- return changed;
- }
-
- private static void restoreResources(boolean changed) {
- if (changed) {
- RenderSessionImpl.getCurrentContext().getRenderResources().clearStyles();
- }
- }
-
- @Nullable
- private static StyleResourceValue resolveStyle(int nativeResid) {
- if (nativeResid == 0) {
- return null;
- }
- BridgeContext context = RenderSessionImpl.getCurrentContext();
- ResourceReference theme = context.resolveId(nativeResid);
- if (theme.isFramework()) {
- return (StyleResourceValue) context.getRenderResources()
- .getFrameworkResource(ResourceType.STYLE, theme.getName());
- } else {
- return (StyleResourceValue) context.getRenderResources()
- .getProjectResource(ResourceType.STYLE, theme.getName());
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/content/res/TypedArray_Delegate.java b/tools/layoutlib/bridge/src/android/content/res/TypedArray_Delegate.java
deleted file mode 100644
index faa8852b494ea..0000000000000
--- a/tools/layoutlib/bridge/src/android/content/res/TypedArray_Delegate.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.res;
-
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.util.TypedValue;
-
-public class TypedArray_Delegate {
-
- @LayoutlibDelegate
- public static boolean getValueAt(TypedArray theTypedArray, int index, TypedValue outValue) {
- // pass
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static TypedArray obtain(Resources res, int len) {
- return BridgeTypedArray.obtain(res, len);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BaseCanvas_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BaseCanvas_Delegate.java
deleted file mode 100644
index cc71053fced68..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BaseCanvas_Delegate.java
+++ /dev/null
@@ -1,762 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.impl.GcSnapshot;
-import com.android.layoutlib.bridge.impl.PorterDuffUtility;
-import com.android.ninepatch.NinePatchChunk;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.Nullable;
-import android.text.TextUtils;
-
-import java.awt.*;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Arc2D;
-import java.awt.geom.Rectangle2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-
-public class BaseCanvas_Delegate {
- // ---- delegate manager ----
- protected static DelegateManager sManager =
- new DelegateManager<>(BaseCanvas_Delegate.class);
-
- // ---- delegate helper data ----
- private final static boolean[] sBoolOut = new boolean[1];
-
-
- // ---- delegate data ----
- protected Bitmap_Delegate mBitmap;
- protected GcSnapshot mSnapshot;
-
- // ---- Public Helper methods ----
-
- protected BaseCanvas_Delegate(Bitmap_Delegate bitmap) {
- mSnapshot = GcSnapshot.createDefaultSnapshot(mBitmap = bitmap);
- }
-
- protected BaseCanvas_Delegate() {
- mSnapshot = GcSnapshot.createDefaultSnapshot(null /*image*/);
- }
-
- /**
- * Disposes of the {@link Graphics2D} stack.
- */
- protected void dispose() {
- mSnapshot.dispose();
- }
-
- /**
- * Returns the current {@link Graphics2D} used to draw.
- */
- public GcSnapshot getSnapshot() {
- return mSnapshot;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nDrawBitmap(long nativeCanvas, Bitmap bitmap, float left, float top,
- long nativePaintOrZero, int canvasDensity, int screenDensity, int bitmapDensity) {
- // get the delegate from the native int.
- Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
- if (bitmapDelegate == null) {
- return;
- }
-
- BufferedImage image = bitmapDelegate.getImage();
- float right = left + image.getWidth();
- float bottom = top + image.getHeight();
-
- drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero,
- 0, 0, image.getWidth(), image.getHeight(),
- (int)left, (int)top, (int)right, (int)bottom);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawBitmap(long nativeCanvas, Bitmap bitmap, float srcLeft, float srcTop,
- float srcRight, float srcBottom, float dstLeft, float dstTop, float dstRight,
- float dstBottom, long nativePaintOrZero, int screenDensity, int bitmapDensity) {
- // get the delegate from the native int.
- Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
- if (bitmapDelegate == null) {
- return;
- }
-
- drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero, (int) srcLeft, (int) srcTop,
- (int) srcRight, (int) srcBottom, (int) dstLeft, (int) dstTop, (int) dstRight,
- (int) dstBottom);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawBitmap(long nativeCanvas, int[] colors, int offset, int stride,
- final float x, final float y, int width, int height, boolean hasAlpha,
- long nativePaintOrZero) {
- // create a temp BufferedImage containing the content.
- final BufferedImage image = new BufferedImage(width, height,
- hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
- image.setRGB(0, 0, width, height, colors, offset, stride);
-
- draw(nativeCanvas, nativePaintOrZero, true /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paint) -> {
- if (paint != null && paint.isFilterBitmap()) {
- graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
- RenderingHints.VALUE_INTERPOLATION_BILINEAR);
- }
-
- graphics.drawImage(image, (int) x, (int) y, null);
- });
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawColor(long nativeCanvas, final int color, final int mode) {
- // get the delegate from the native int.
- BaseCanvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- final int w = canvasDelegate.mBitmap.getImage().getWidth();
- final int h = canvasDelegate.mBitmap.getImage().getHeight();
- draw(nativeCanvas, (graphics, paint) -> {
- // reset its transform just in case
- graphics.setTransform(new AffineTransform());
-
- // set the color
- graphics.setColor(new java.awt.Color(color, true /*alpha*/));
-
- Composite composite = PorterDuffUtility.getComposite(
- PorterDuffUtility.getPorterDuffMode(mode), 0xFF);
- if (composite != null) {
- graphics.setComposite(composite);
- }
-
- graphics.fillRect(0, 0, w, h);
- });
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawPaint(long nativeCanvas, long paint) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Canvas.drawPaint is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawPoint(long nativeCanvas, float x, float y,
- long nativePaint) {
- // TODO: need to support the attribute (e.g. stroke width) of paint
- draw(nativeCanvas, nativePaint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> graphics.fillRect((int)x, (int)y, 1, 1));
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawPoints(long nativeCanvas, float[] pts, int offset, int count,
- long nativePaint) {
- if (offset < 0 || count < 0 || offset + count > pts.length) {
- throw new IllegalArgumentException("Invalid argument set");
- }
- // ignore the last point if the count is odd (It means it is not paired).
- count = (count >> 1) << 1;
- for (int i = offset; i < offset + count; i += 2) {
- nDrawPoint(nativeCanvas, pts[i], pts[i + 1], nativePaint);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawLine(long nativeCanvas,
- final float startX, final float startY, final float stopX, final float stopY,
- long paint) {
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> graphics.drawLine((int)startX, (int)startY, (int)stopX, (int)stopY));
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawLines(long nativeCanvas,
- final float[] pts, final int offset, final int count,
- long nativePaint) {
- draw(nativeCanvas, nativePaint, false /*compositeOnly*/,
- false /*forceSrcMode*/, (graphics, paintDelegate) -> {
- for (int i = 0; i < count; i += 4) {
- graphics.drawLine((int) pts[i + offset], (int) pts[i + offset + 1],
- (int) pts[i + offset + 2], (int) pts[i + offset + 3]);
- }
- });
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawRect(long nativeCanvas,
- final float left, final float top, final float right, final float bottom, long paint) {
-
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- int style = paintDelegate.getStyle();
-
- // draw
- if (style == Paint.Style.FILL.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.fillRect((int)left, (int)top,
- (int)(right-left), (int)(bottom-top));
- }
-
- if (style == Paint.Style.STROKE.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.drawRect((int)left, (int)top,
- (int)(right-left), (int)(bottom-top));
- }
- });
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawOval(long nativeCanvas, final float left,
- final float top, final float right, final float bottom, long paint) {
- if (right > left && bottom > top) {
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- int style = paintDelegate.getStyle();
-
- // draw
- if (style == Paint.Style.FILL.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.fillOval((int)left, (int)top,
- (int)(right - left), (int)(bottom - top));
- }
-
- if (style == Paint.Style.STROKE.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.drawOval((int)left, (int)top,
- (int)(right - left), (int)(bottom - top));
- }
- });
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawCircle(long nativeCanvas,
- float cx, float cy, float radius, long paint) {
- nDrawOval(nativeCanvas,
- cx - radius, cy - radius, cx + radius, cy + radius,
- paint);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawArc(long nativeCanvas,
- final float left, final float top, final float right, final float bottom,
- final float startAngle, final float sweep,
- final boolean useCenter, long paint) {
- if (right > left && bottom > top) {
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- int style = paintDelegate.getStyle();
-
- Arc2D.Float arc = new Arc2D.Float(
- left, top, right - left, bottom - top,
- -startAngle, -sweep,
- useCenter ? Arc2D.PIE : Arc2D.OPEN);
-
- // draw
- if (style == Paint.Style.FILL.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.fill(arc);
- }
-
- if (style == Paint.Style.STROKE.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.draw(arc);
- }
- });
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawRoundRect(long nativeCanvas,
- final float left, final float top, final float right, final float bottom,
- final float rx, final float ry, long paint) {
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- int style = paintDelegate.getStyle();
-
- // draw
- if (style == Paint.Style.FILL.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.fillRoundRect(
- (int)left, (int)top,
- (int)(right - left), (int)(bottom - top),
- 2 * (int)rx, 2 * (int)ry);
- }
-
- if (style == Paint.Style.STROKE.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.drawRoundRect(
- (int)left, (int)top,
- (int)(right - left), (int)(bottom - top),
- 2 * (int)rx, 2 * (int)ry);
- }
- });
- }
-
- @LayoutlibDelegate
- public static void nDrawPath(long nativeCanvas, long path, long paint) {
- final Path_Delegate pathDelegate = Path_Delegate.getDelegate(path);
- if (pathDelegate == null) {
- return;
- }
-
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- Shape shape = pathDelegate.getJavaShape();
- Rectangle2D bounds = shape.getBounds2D();
- if (bounds.isEmpty()) {
- // Apple JRE 1.6 doesn't like drawing empty shapes.
- // http://b.android.com/178278
-
- if (pathDelegate.isEmpty()) {
- // This means that the path doesn't have any lines or curves so
- // nothing to draw.
- return;
- }
-
- // The stroke width is not consider for the size of the bounds so,
- // for example, a horizontal line, would be considered as an empty
- // rectangle.
- // If the strokeWidth is not 0, we use it to consider the size of the
- // path as well.
- float strokeWidth = paintDelegate.getStrokeWidth();
- if (strokeWidth <= 0.0f) {
- return;
- }
- bounds.setRect(bounds.getX(), bounds.getY(),
- Math.max(strokeWidth, bounds.getWidth()),
- Math.max(strokeWidth, bounds.getHeight()));
- }
-
- int style = paintDelegate.getStyle();
-
- if (style == Paint.Style.FILL.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.fill(shape);
- }
-
- if (style == Paint.Style.STROKE.nativeInt ||
- style == Paint.Style.FILL_AND_STROKE.nativeInt) {
- graphics.draw(shape);
- }
- });
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawRegion(long nativeCanvas, long nativeRegion,
- long nativePaint) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Some canvas paths may not be drawn", null, null);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawNinePatch(long nativeCanvas, long nativeBitmap, long ninePatch,
- final float dstLeft, final float dstTop, final float dstRight, final float dstBottom,
- long nativePaintOrZero, final int screenDensity, final int bitmapDensity) {
-
- // get the delegate from the native int.
- final Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(nativeBitmap);
- if (bitmapDelegate == null) {
- return;
- }
-
- byte[] c = NinePatch_Delegate.getChunk(ninePatch);
- if (c == null) {
- // not a 9-patch?
- BufferedImage image = bitmapDelegate.getImage();
- drawBitmap(nativeCanvas, bitmapDelegate, nativePaintOrZero, 0, 0, image.getWidth(),
- image.getHeight(), (int) dstLeft, (int) dstTop, (int) dstRight,
- (int) dstBottom);
- return;
- }
-
- final NinePatchChunk chunkObject = NinePatch_Delegate.getChunk(c);
- assert chunkObject != null;
- if (chunkObject == null) {
- return;
- }
-
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- // this one can be null
- Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nativePaintOrZero);
-
- canvasDelegate.getSnapshot().draw(new GcSnapshot.Drawable() {
- @Override
- public void draw(Graphics2D graphics, Paint_Delegate paint) {
- chunkObject.draw(bitmapDelegate.getImage(), graphics, (int) dstLeft, (int) dstTop,
- (int) (dstRight - dstLeft), (int) (dstBottom - dstTop), screenDensity,
- bitmapDensity);
- }
- }, paintDelegate, true, false);
-
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawBitmapMatrix(long nCanvas, Bitmap bitmap,
- long nMatrix, long nPaint) {
- // get the delegate from the native int.
- BaseCanvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- // get the delegate from the native int, which can be null
- Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nPaint);
-
- // get the delegate from the native int.
- Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
- if (bitmapDelegate == null) {
- return;
- }
-
- final BufferedImage image = getImageToDraw(bitmapDelegate, paintDelegate, sBoolOut);
-
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
- if (matrixDelegate == null) {
- return;
- }
-
- final AffineTransform mtx = matrixDelegate.getAffineTransform();
-
- canvasDelegate.getSnapshot().draw((graphics, paint) -> {
- if (paint != null && paint.isFilterBitmap()) {
- graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
- RenderingHints.VALUE_INTERPOLATION_BILINEAR);
- }
-
- //FIXME add support for canvas, screen and bitmap densities.
- graphics.drawImage(image, mtx, null);
- }, paintDelegate, true /*compositeOnly*/, false /*forceSrcMode*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawBitmapMesh(long nCanvas, Bitmap bitmap,
- int meshWidth, int meshHeight, float[] verts, int vertOffset, int[] colors,
- int colorOffset, long nPaint) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Canvas.drawBitmapMesh is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawVertices(long nCanvas, int mode, int n,
- float[] verts, int vertOffset,
- float[] texs, int texOffset,
- int[] colors, int colorOffset,
- short[] indices, int indexOffset,
- int indexCount, long nPaint) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Canvas.drawVertices is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawText(long nativeCanvas, char[] text, int index, int count,
- float startX, float startY, int flags, long paint, long typeface) {
- drawText(nativeCanvas, text, index, count, startX, startY, (flags & 1) != 0,
- paint, typeface);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawText(long nativeCanvas, String text,
- int start, int end, float x, float y, final int flags, long paint,
- long typeface) {
- int count = end - start;
- char[] buffer = TemporaryBuffer.obtain(count);
- TextUtils.getChars(text, start, end, buffer, 0);
-
- nDrawText(nativeCanvas, buffer, 0, count, x, y, flags, paint, typeface);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawTextRun(long nativeCanvas, String text,
- int start, int end, int contextStart, int contextEnd,
- float x, float y, boolean isRtl, long paint, long typeface) {
- int count = end - start;
- char[] buffer = TemporaryBuffer.obtain(count);
- TextUtils.getChars(text, start, end, buffer, 0);
-
- drawText(nativeCanvas, buffer, 0, count, x, y, isRtl, paint, typeface);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawTextRun(long nativeCanvas, char[] text,
- int start, int count, int contextStart, int contextCount,
- float x, float y, boolean isRtl, long paint, long typeface) {
- drawText(nativeCanvas, text, start, count, x, y, isRtl, paint, typeface);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawTextOnPath(long nativeCanvas,
- char[] text, int index,
- int count, long path,
- float hOffset,
- float vOffset, int bidiFlags,
- long paint, long typeface) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Canvas.drawTextOnPath is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nDrawTextOnPath(long nativeCanvas,
- String text, long path,
- float hOffset,
- float vOffset,
- int bidiFlags, long paint,
- long typeface) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Canvas.drawTextOnPath is not supported.", null, null /*data*/);
- }
-
- // ---- Private delegate/helper methods ----
-
- /**
- * Executes a {@link GcSnapshot.Drawable} with a given canvas and paint.
- *
Note that the drawable may actually be executed several times if there are
- * layers involved (see {@link #saveLayer(RectF, Paint_Delegate, int)}.
- */
- private static void draw(long nCanvas, long nPaint, boolean compositeOnly, boolean forceSrcMode,
- GcSnapshot.Drawable drawable) {
- // get the delegate from the native int.
- BaseCanvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- // get the paint which can be null if nPaint is 0;
- Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nPaint);
-
- canvasDelegate.getSnapshot().draw(drawable, paintDelegate, compositeOnly, forceSrcMode);
- }
-
- /**
- * Executes a {@link GcSnapshot.Drawable} with a given canvas. No paint object will be provided
- * to {@link GcSnapshot.Drawable#draw(Graphics2D, Paint_Delegate)}.
- *
Note that the drawable may actually be executed several times if there are
- * layers involved (see {@link #saveLayer(RectF, Paint_Delegate, int)}.
- */
- private static void draw(long nCanvas, GcSnapshot.Drawable drawable) {
- // get the delegate from the native int.
- BaseCanvas_Delegate canvasDelegate = sManager.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.mSnapshot.draw(drawable);
- }
-
- private static void drawText(long nativeCanvas, final char[] text, final int index,
- final int count, final float startX, final float startY, final boolean isRtl,
- long paint, final long typeface) {
-
- draw(nativeCanvas, paint, false /*compositeOnly*/, false /*forceSrcMode*/,
- (graphics, paintDelegate) -> {
- // WARNING: the logic in this method is similar to Paint_Delegate.measureText.
- // Any change to this method should be reflected in Paint.measureText
-
- // assert that the typeface passed is actually the one stored in paint.
- assert (typeface == paintDelegate.mNativeTypeface);
-
- // Paint.TextAlign indicates how the text is positioned relative to X.
- // LEFT is the default and there's nothing to do.
- float x = startX;
- int limit = index + count;
- if (paintDelegate.getTextAlign() != Paint.Align.LEFT.nativeInt) {
- RectF bounds =
- paintDelegate.measureText(text, index, count, null, 0, isRtl);
- float m = bounds.right - bounds.left;
- if (paintDelegate.getTextAlign() == Paint.Align.CENTER.nativeInt) {
- x -= m / 2;
- } else if (paintDelegate.getTextAlign() == Paint.Align.RIGHT.nativeInt) {
- x -= m;
- }
- }
-
- new BidiRenderer(graphics, paintDelegate, text).setRenderLocation(x,
- startY).renderText(index, limit, isRtl, null, 0, true);
- });
- }
-
- private static void drawBitmap(long nativeCanvas, Bitmap_Delegate bitmap,
- long nativePaintOrZero, final int sleft, final int stop, final int sright,
- final int sbottom, final int dleft, final int dtop, final int dright,
- final int dbottom) {
- // get the delegate from the native int.
- BaseCanvas_Delegate canvasDelegate = sManager.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- // get the paint, which could be null if the int is 0
- Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(nativePaintOrZero);
-
- final BufferedImage image = getImageToDraw(bitmap, paintDelegate, sBoolOut);
-
- draw(nativeCanvas, nativePaintOrZero, true /*compositeOnly*/, sBoolOut[0],
- (graphics, paint) -> {
- if (paint != null && paint.isFilterBitmap()) {
- graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
- RenderingHints.VALUE_INTERPOLATION_BILINEAR);
- }
-
- //FIXME add support for canvas, screen and bitmap densities.
- graphics.drawImage(image, dleft, dtop, dright, dbottom, sleft, stop, sright,
- sbottom, null);
- });
- }
-
- /**
- * Returns a BufferedImage ready for drawing, based on the bitmap and paint delegate.
- * The image returns, through a 1-size boolean array, whether the drawing code should
- * use a SRC composite no matter what the paint says.
- *
- * @param bitmap the bitmap
- * @param paint the paint that will be used to draw
- * @param forceSrcMode whether the composite will have to be SRC
- * @return the image to draw
- */
- private static BufferedImage getImageToDraw(Bitmap_Delegate bitmap, Paint_Delegate paint,
- boolean[] forceSrcMode) {
- BufferedImage image = bitmap.getImage();
- forceSrcMode[0] = false;
-
- // if the bitmap config is alpha_8, then we erase all color value from it
- // before drawing it or apply the texture from the shader if present.
- if (bitmap.getConfig() == Bitmap.Config.ALPHA_8) {
- Shader_Delegate shader = paint.getShader();
- java.awt.Paint javaPaint = null;
- if (shader instanceof BitmapShader_Delegate) {
- javaPaint = shader.getJavaPaint();
- }
-
- fixAlpha8Bitmap(image, javaPaint);
- } else if (!bitmap.hasAlpha()) {
- // hasAlpha is merely a rendering hint. There can in fact be alpha values
- // in the bitmap but it should be ignored at drawing time.
- // There is two ways to do this:
- // - override the composite to be SRC. This can only be used if the composite
- // was going to be SRC or SRC_OVER in the first place
- // - Create a different bitmap to draw in which all the alpha channel values is set
- // to 0xFF.
- if (paint != null) {
- PorterDuff.Mode mode = PorterDuff.intToMode(paint.getPorterDuffMode());
-
- forceSrcMode[0] = mode == PorterDuff.Mode.SRC_OVER || mode == PorterDuff.Mode.SRC;
- }
-
- // if we can't force SRC mode, then create a temp bitmap of TYPE_RGB
- if (!forceSrcMode[0]) {
- image = Bitmap_Delegate.createCopy(image, BufferedImage.TYPE_INT_RGB, 0xFF);
- }
- }
-
- return image;
- }
-
- /**
- * This method will apply the correct color to the passed "only alpha" image. Colors on the
- * passed image will be destroyed.
- * If the passed javaPaint is null, the color will be set to 0. If a paint is passed, it will
- * be used to obtain the color that will be applied.
- *
- * This will destroy the passed image color channel.
- */
- private static void fixAlpha8Bitmap(final BufferedImage image,
- @Nullable java.awt.Paint javaPaint) {
- int w = image.getWidth();
- int h = image.getHeight();
-
- DataBuffer texture = null;
- if (javaPaint != null) {
- PaintContext context = javaPaint.createContext(ColorModel.getRGBdefault(), null, null,
- new AffineTransform(), null);
- texture = context.getRaster(0, 0, w, h).getDataBuffer();
- }
-
- int[] argb = new int[w * h];
- image.getRGB(0, 0, image.getWidth(), image.getHeight(), argb, 0, image.getWidth());
-
- final int length = argb.length;
- for (int i = 0; i < length; i++) {
- argb[i] &= 0xFF000000;
- if (texture != null) {
- argb[i] |= texture.getElem(i) & 0x00FFFFFF;
- }
- }
-
- image.setRGB(0, 0, w, h, argb, 0, w);
- }
-
- protected int save(int saveFlags) {
- // get the current save count
- int count = mSnapshot.size();
-
- mSnapshot = mSnapshot.save(saveFlags);
-
- // return the old save count
- return count;
- }
-
- protected int saveLayerAlpha(RectF rect, int alpha, int saveFlags) {
- Paint_Delegate paint = new Paint_Delegate();
- paint.setAlpha(alpha);
- return saveLayer(rect, paint, saveFlags);
- }
-
- protected int saveLayer(RectF rect, Paint_Delegate paint, int saveFlags) {
- // get the current save count
- int count = mSnapshot.size();
-
- mSnapshot = mSnapshot.saveLayer(rect, paint, saveFlags);
-
- // return the old save count
- return count;
- }
-
- /**
- * Restores the {@link GcSnapshot} to saveCount
- * @param saveCount the saveCount
- */
- protected void restoreTo(int saveCount) {
- mSnapshot = mSnapshot.restoreTo(saveCount);
- }
-
- /**
- * Restores the top {@link GcSnapshot}
- */
- protected void restore() {
- mSnapshot = mSnapshot.restore();
- }
-
- protected boolean clipRect(float left, float top, float right, float bottom, int regionOp) {
- return mSnapshot.clipRect(left, top, right, bottom, regionOp);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BidiRenderer.java b/tools/layoutlib/bridge/src/android/graphics/BidiRenderer.java
deleted file mode 100644
index c6827a3c9c5f4..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BidiRenderer.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-
-import android.graphics.Paint_Delegate.FontInfo;
-import android.icu.lang.UScript;
-import android.icu.lang.UScriptRun;
-import android.icu.text.Bidi;
-import android.icu.text.BidiRun;
-
-import java.awt.Font;
-import java.awt.Graphics2D;
-import java.awt.Toolkit;
-import java.awt.font.FontRenderContext;
-import java.awt.font.GlyphVector;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Rectangle2D;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Render the text by breaking it into various scripts and using the right font for each script.
- * Can be used to measure the text without actually drawing it.
- */
-@SuppressWarnings("deprecation")
-public class BidiRenderer {
- private static String JAVA_VENDOR = System.getProperty("java.vendor");
-
- private static class ScriptRun {
- int start;
- int limit;
- boolean isRtl;
- int scriptCode;
- Font font;
-
- public ScriptRun(int start, int limit, boolean isRtl) {
- this.start = start;
- this.limit = limit;
- this.isRtl = isRtl;
- this.scriptCode = UScript.INVALID_CODE;
- }
- }
-
- private final Graphics2D mGraphics;
- private final Paint_Delegate mPaint;
- private char[] mText;
- // This List can contain nulls. A null font implies that the we weren't able to load the font
- // properly. So, if we encounter a situation where we try to use that font, log a warning.
- private List mFonts;
- // Bounds of the text drawn so far.
- private RectF mBounds;
- private float mBaseline;
-
- /**
- * @param graphics May be null.
- * @param paint The Paint to use to get the fonts. Should not be null.
- * @param text Unidirectional text. Should not be null.
- */
- public BidiRenderer(Graphics2D graphics, Paint_Delegate paint, char[] text) {
- assert (paint != null);
- mGraphics = graphics;
- mPaint = paint;
- mText = text;
- mFonts = new ArrayList(paint.getFonts().size());
- for (FontInfo fontInfo : paint.getFonts()) {
- if (fontInfo == null) {
- mFonts.add(null);
- continue;
- }
- mFonts.add(fontInfo.mFont);
- }
- mBounds = new RectF();
- }
-
- /**
- *
- * @param x The x-coordinate of the left edge of where the text should be drawn on the given
- * graphics.
- * @param y The y-coordinate at which to draw the text on the given mGraphics.
- *
- */
- public BidiRenderer setRenderLocation(float x, float y) {
- mBounds = new RectF(x, y, x, y);
- mBaseline = y;
- return this;
- }
-
- /**
- * Perform Bidi Analysis on the text and then render it.
- *
- * To skip the analysis and render unidirectional text, see {@link
- * #renderText(int, int, boolean, float[], int, boolean)}
- */
- public RectF renderText(int start, int limit, int bidiFlags, float[] advances,
- int advancesIndex, boolean draw) {
- Bidi bidi = new Bidi(mText, start, null, 0, limit - start, getIcuFlags(bidiFlags));
- for (int i = 0; i < bidi.countRuns(); i++) {
- BidiRun visualRun = bidi.getVisualRun(i);
- boolean isRtl = visualRun.getDirection() == Bidi.RTL;
- renderText(visualRun.getStart(), visualRun.getLimit(), isRtl, advances,
- advancesIndex, draw);
- }
- return mBounds;
- }
-
- /**
- * Render unidirectional text.
- *
- * This method can also be used to measure the width of the text without actually drawing it.
- *
- * @param start index of the first character
- * @param limit index of the first character that should not be rendered.
- * @param isRtl is the text right-to-left
- * @param advances If not null, then advances for each character to be rendered are returned
- * here.
- * @param advancesIndex index into advances from where the advances need to be filled.
- * @param draw If true and {@code graphics} is not null, draw the rendered text on the graphics
- * at the given co-ordinates
- * @return A rectangle specifying the bounds of the text drawn.
- */
- public RectF renderText(int start, int limit, boolean isRtl, float[] advances,
- int advancesIndex, boolean draw) {
- // We break the text into scripts and then select font based on it and then render each of
- // the script runs.
- for (ScriptRun run : getScriptRuns(mText, start, limit, isRtl, mFonts)) {
- int flag = Font.LAYOUT_NO_LIMIT_CONTEXT | Font.LAYOUT_NO_START_CONTEXT;
- flag |= isRtl ? Font.LAYOUT_RIGHT_TO_LEFT : Font.LAYOUT_LEFT_TO_RIGHT;
- renderScript(run.start, run.limit, run.font, flag, advances, advancesIndex, draw);
- advancesIndex += run.limit - run.start;
- }
- return mBounds;
- }
-
- /**
- * Render a script run to the right of the bounds passed. Use the preferred font to render as
- * much as possible. This also implements a fallback mechanism to render characters that cannot
- * be drawn using the preferred font.
- */
- private void renderScript(int start, int limit, Font preferredFont, int flag,
- float[] advances, int advancesIndex, boolean draw) {
- if (mFonts.size() == 0 || preferredFont == null) {
- return;
- }
-
- while (start < limit) {
- boolean foundFont = false;
- int canDisplayUpTo = preferredFont.canDisplayUpTo(mText, start, limit);
- if (canDisplayUpTo == -1) {
- // We can draw all characters in the text.
- render(start, limit, preferredFont, flag, advances, advancesIndex, draw);
- return;
- }
- if (canDisplayUpTo > start) {
- // We can draw something.
- render(start, canDisplayUpTo, preferredFont, flag, advances, advancesIndex, draw);
- advancesIndex += canDisplayUpTo - start;
- start = canDisplayUpTo;
- }
-
- // The current character cannot be drawn with the preferred font. Cycle through all the
- // fonts to check which one can draw it.
- int charCount = Character.isHighSurrogate(mText[start]) ? 2 : 1;
- for (Font font : mFonts) {
- if (font == null) {
- logFontWarning();
- continue;
- }
- canDisplayUpTo = font.canDisplayUpTo(mText, start, start + charCount);
- if (canDisplayUpTo == -1) {
- render(start, start+charCount, font, flag, advances, advancesIndex, draw);
- start += charCount;
- advancesIndex += charCount;
- foundFont = true;
- break;
- }
- }
- if (!foundFont) {
- // No font can display this char. Use the preferred font. The char will most
- // probably appear as a box or a blank space. We could, probably, use some
- // heuristics and break the character into the base character and diacritics and
- // then draw it, but it's probably not worth the effort.
- render(start, start + charCount, preferredFont, flag, advances, advancesIndex,
- draw);
- start += charCount;
- advancesIndex += charCount;
- }
- }
- }
-
- private static void logFontWarning() {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN,
- "Some fonts could not be loaded. The rendering may not be perfect. " +
- "Try running the IDE with JRE 7.", null, null);
- }
-
- /**
- * Renders the text to the right of the bounds with the given font.
- * @param font The font to render the text with.
- */
- private void render(int start, int limit, Font font, int flag, float[] advances,
- int advancesIndex, boolean draw) {
-
- FontRenderContext frc;
- if (mGraphics != null) {
- frc = mGraphics.getFontRenderContext();
- } else {
- frc = Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext();
-
- // Metrics obtained this way don't have anti-aliasing set. So,
- // we create a new FontRenderContext with anti-aliasing set.
- AffineTransform transform = font.getTransform();
- if (mPaint.isAntiAliased() &&
- // Workaround for http://b.android.com/211659
- (transform.getScaleX() <= 9.9 ||
- !"JetBrains s.r.o".equals(JAVA_VENDOR))) {
- frc = new FontRenderContext(transform, true, frc.usesFractionalMetrics());
- }
- }
- GlyphVector gv = font.layoutGlyphVector(frc, mText, start, limit, flag);
- int ng = gv.getNumGlyphs();
- int[] ci = gv.getGlyphCharIndices(0, ng, null);
- if (advances != null) {
- for (int i = 0; i < ng; i++) {
- int adv_idx = advancesIndex + ci[i];
- advances[adv_idx] += gv.getGlyphMetrics(i).getAdvanceX();
- }
- }
- if (draw && mGraphics != null) {
- mGraphics.drawGlyphVector(gv, mBounds.right, mBaseline);
- }
-
- // Update the bounds.
- Rectangle2D awtBounds = gv.getLogicalBounds();
- RectF bounds = awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline);
- // If the width of the bounds is zero, no text had been drawn earlier. Hence, use the
- // coordinates from the bounds as an offset.
- if (Math.abs(mBounds.right - mBounds.left) == 0) {
- mBounds = bounds;
- } else {
- mBounds.union(bounds);
- }
- }
-
- // --- Static helper methods ---
-
- private static RectF awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY) {
- float left = (float) awtRec.getX();
- float top = (float) awtRec.getY();
- float right = (float) (left + awtRec.getWidth());
- float bottom = (float) (top + awtRec.getHeight());
- RectF androidRect = new RectF(left, top, right, bottom);
- androidRect.offset(offsetX, offsetY);
- return androidRect;
- }
-
- /* package */ static List getScriptRuns(char[] text, int start, int limit,
- boolean isRtl, List fonts) {
- LinkedList scriptRuns = new LinkedList();
-
- int count = limit - start;
- UScriptRun uScriptRun = new UScriptRun(text, start, count);
- while (uScriptRun.next()) {
- int scriptStart = uScriptRun.getScriptStart();
- int scriptLimit = uScriptRun.getScriptLimit();
- ScriptRun run = new ScriptRun(scriptStart, scriptLimit, isRtl);
- run.scriptCode = uScriptRun.getScriptCode();
- setScriptFont(text, run, fonts);
- scriptRuns.add(run);
- }
-
- return scriptRuns;
- }
-
- // TODO: Replace this method with one which returns the font based on the scriptCode.
- private static void setScriptFont(char[] text, ScriptRun run,
- List fonts) {
- for (Font font : fonts) {
- if (font == null) {
- logFontWarning();
- continue;
- }
- if (font.canDisplayUpTo(text, run.start, run.limit) == -1) {
- run.font = font;
- return;
- }
- }
- run.font = fonts.get(0);
- }
-
- private static int getIcuFlags(int bidiFlag) {
- switch (bidiFlag) {
- case Paint.BIDI_LTR:
- case Paint.BIDI_FORCE_LTR:
- return Bidi.DIRECTION_LEFT_TO_RIGHT;
- case Paint.BIDI_RTL:
- case Paint.BIDI_FORCE_RTL:
- return Bidi.DIRECTION_RIGHT_TO_LEFT;
- case Paint.BIDI_DEFAULT_LTR:
- return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
- case Paint.BIDI_DEFAULT_RTL:
- return Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT;
- default:
- assert false;
- return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
deleted file mode 100644
index 8bd2a7acafdc7..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.ninepatch.NinePatchChunk;
-import com.android.resources.Density;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.Nullable;
-import com.android.layoutlib.bridge.util.NinePatchInputStream;
-import android.graphics.BitmapFactory.Options;
-import android.graphics.Bitmap_Delegate.BitmapCreateFlags;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.EnumSet;
-import java.util.Set;
-
-/**
- * Delegate implementing the native methods of android.graphics.BitmapFactory
- *
- * Through the layoutlib_create tool, the original native methods of BitmapFactory have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
- * around to map int to instance of the delegate.
- *
- */
-/*package*/ class BitmapFactory_Delegate {
-
- // ------ Native Delegates ------
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeDecodeStream(InputStream is, byte[] storage,
- @Nullable Rect padding, @Nullable Options opts) {
- Bitmap bm = null;
-
- Density density = Density.MEDIUM;
- Set bitmapCreateFlags = EnumSet.of(BitmapCreateFlags.MUTABLE);
- if (opts != null) {
- density = Density.getEnum(opts.inDensity);
- if (opts.inPremultiplied) {
- bitmapCreateFlags.add(BitmapCreateFlags.PREMULTIPLIED);
- }
- opts.inScaled = false;
- }
-
- try {
- if (is instanceof NinePatchInputStream) {
- NinePatchInputStream npis = (NinePatchInputStream) is;
- npis.disableFakeMarkSupport();
-
- // load the bitmap as a nine patch
- com.android.ninepatch.NinePatch ninePatch = com.android.ninepatch.NinePatch.load(
- npis, true /*is9Patch*/, false /*convert*/);
-
- // get the bitmap and chunk objects.
- bm = Bitmap_Delegate.createBitmap(ninePatch.getImage(), bitmapCreateFlags,
- density);
- NinePatchChunk chunk = ninePatch.getChunk();
-
- // put the chunk in the bitmap
- bm.setNinePatchChunk(NinePatch_Delegate.serialize(chunk));
-
- if (padding != null) {
- // read the padding
- int[] paddingArray = chunk.getPadding();
- padding.left = paddingArray[0];
- padding.top = paddingArray[1];
- padding.right = paddingArray[2];
- padding.bottom = paddingArray[3];
- }
- } else {
- // load the bitmap directly.
- bm = Bitmap_Delegate.createBitmap(is, bitmapCreateFlags, density);
- }
- } catch (IOException e) {
- Bridge.getLog().error(null, "Failed to load image", e, null);
- }
-
- return bm;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
- Rect padding, Options opts) {
- opts.inBitmap = null;
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeDecodeAsset(long asset, Rect padding, Options opts) {
- opts.inBitmap = null;
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeDecodeByteArray(byte[] data, int offset,
- int length, Options opts) {
- opts.inBitmap = null;
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeIsSeekable(FileDescriptor fd) {
- return true;
- }
-
- /**
- * Set the newly decoded bitmap's density based on the Options.
- *
- * Copied from {@link BitmapFactory#setDensityFromOptions(Bitmap, Options)}.
- */
- @LayoutlibDelegate
- /*package*/ static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
- if (outputBitmap == null || opts == null) return;
-
- final int density = opts.inDensity;
- if (density != 0) {
- outputBitmap.setDensity(density);
- final int targetDensity = opts.inTargetDensity;
- if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
- return;
- }
-
- // --- Change from original implementation begins ---
- // LayoutLib doesn't scale the nine patch when decoding it. Hence, don't change the
- // density of the source bitmap in case of ninepatch.
-
- if (opts.inScaled) {
- // --- Change from original implementation ends. ---
- outputBitmap.setDensity(targetDensity);
- }
- } else if (opts.inBitmap != null) {
- // bitmap was reused, ensure density is reset
- outputBitmap.setDensity(Bitmap.getDefaultDensity());
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java
deleted file mode 100644
index 4914a48f20cdf..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapShader_Delegate.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Shader.TileMode;
-
-import java.awt.PaintContext;
-import java.awt.Rectangle;
-import java.awt.RenderingHints;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.NoninvertibleTransformException;
-import java.awt.geom.Rectangle2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.ColorModel;
-import java.awt.image.Raster;
-
-/**
- * Delegate implementing the native methods of android.graphics.BitmapShader
- *
- * Through the layoutlib_create tool, the original native methods of BitmapShader have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original BitmapShader class.
- *
- * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
- *
- * @see Shader_Delegate
- *
- */
-public class BitmapShader_Delegate extends Shader_Delegate {
-
- // ---- delegate data ----
- private java.awt.Paint mJavaPaint;
-
- // ---- Public Helper methods ----
-
- @Override
- public java.awt.Paint getJavaPaint() {
- return mJavaPaint;
- }
-
- @Override
- public boolean isSupported() {
- return true;
- }
-
- @Override
- public String getSupportMessage() {
- // no message since isSupported returns true;
- return null;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(long nativeMatrix, Bitmap androidBitmap,
- int shaderTileModeX, int shaderTileModeY) {
- Bitmap_Delegate bitmap = Bitmap_Delegate.getDelegate(androidBitmap);
- if (bitmap == null) {
- return 0;
- }
-
- BitmapShader_Delegate newDelegate = new BitmapShader_Delegate(nativeMatrix,
- bitmap.getImage(),
- Shader_Delegate.getTileMode(shaderTileModeX),
- Shader_Delegate.getTileMode(shaderTileModeY));
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-
- private BitmapShader_Delegate(long matrix, BufferedImage image,
- TileMode tileModeX, TileMode tileModeY) {
- super(matrix);
- mJavaPaint = new BitmapShaderPaint(image, tileModeX, tileModeY);
- }
-
- private class BitmapShaderPaint implements java.awt.Paint {
- private final BufferedImage mImage;
- private final TileMode mTileModeX;
- private final TileMode mTileModeY;
-
- BitmapShaderPaint(BufferedImage image,
- TileMode tileModeX, TileMode tileModeY) {
- mImage = image;
- mTileModeX = tileModeX;
- mTileModeY = tileModeY;
- }
-
- @Override
- public PaintContext createContext(ColorModel colorModel, Rectangle deviceBounds,
- Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {
- AffineTransform canvasMatrix;
- try {
- canvasMatrix = xform.createInverse();
- } catch (NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in BitmapShader", e, null /*data*/);
- canvasMatrix = new AffineTransform();
- }
-
- AffineTransform localMatrix = getLocalMatrix();
- try {
- localMatrix = localMatrix.createInverse();
- } catch (NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in BitmapShader", e, null /*data*/);
- localMatrix = new AffineTransform();
- }
-
- if (!colorModel.isCompatibleRaster(mImage.getRaster())) {
- // Fallback to the default ARGB color model
- colorModel = ColorModel.getRGBdefault();
- }
-
- return new BitmapShaderContext(canvasMatrix, localMatrix, colorModel);
- }
-
- private class BitmapShaderContext implements PaintContext {
-
- private final AffineTransform mCanvasMatrix;
- private final AffineTransform mLocalMatrix;
- private final ColorModel mColorModel;
-
- public BitmapShaderContext(
- AffineTransform canvasMatrix,
- AffineTransform localMatrix,
- ColorModel colorModel) {
- mCanvasMatrix = canvasMatrix;
- mLocalMatrix = localMatrix;
- mColorModel = colorModel;
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public ColorModel getColorModel() {
- return mColorModel;
- }
-
- @Override
- public Raster getRaster(int x, int y, int w, int h) {
- BufferedImage image = new BufferedImage(
- mColorModel, mColorModel.createCompatibleWritableRaster(w, h),
- mColorModel.isAlphaPremultiplied(), null);
-
- int[] data = new int[w*h];
-
- int index = 0;
- float[] pt1 = new float[2];
- float[] pt2 = new float[2];
- for (int iy = 0 ; iy < h ; iy++) {
- for (int ix = 0 ; ix < w ; ix++) {
- // handle the canvas transform
- pt1[0] = x + ix;
- pt1[1] = y + iy;
- mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
-
- // handle the local matrix.
- pt1[0] = pt2[0];
- pt1[1] = pt2[1];
- mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
-
- data[index++] = getColor(pt2[0], pt2[1]);
- }
- }
-
- image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
- return image.getRaster();
- }
- }
-
- /**
- * Returns a color for an arbitrary point.
- */
- private int getColor(float fx, float fy) {
- int x = getCoordinate(Math.round(fx), mImage.getWidth(), mTileModeX);
- int y = getCoordinate(Math.round(fy), mImage.getHeight(), mTileModeY);
-
- return mImage.getRGB(x, y);
- }
-
- private int getCoordinate(int i, int size, TileMode mode) {
- if (i < 0) {
- switch (mode) {
- case CLAMP:
- i = 0;
- break;
- case REPEAT:
- i = size - 1 - (-i % size);
- break;
- case MIRROR:
- // this is the same as the positive side, just make the value positive
- // first.
- i = -i;
- int count = i / size;
- i = i % size;
-
- if ((count % 2) == 1) {
- i = size - 1 - i;
- }
- break;
- }
- } else if (i >= size) {
- switch (mode) {
- case CLAMP:
- i = size - 1;
- break;
- case REPEAT:
- i = i % size;
- break;
- case MIRROR:
- int count = i / size;
- i = i % size;
-
- if ((count % 2) == 1) {
- i = size - 1 - i;
- }
- break;
- }
- }
-
- return i;
- }
-
-
- @Override
- public int getTransparency() {
- return java.awt.Paint.TRANSLUCENT;
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
deleted file mode 100644
index 0064537943ab5..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
+++ /dev/null
@@ -1,736 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.RenderResources;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.android.BridgeContext;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.impl.RenderAction;
-import com.android.resources.Density;
-import com.android.resources.ResourceType;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.Nullable;
-import android.graphics.Bitmap.Config;
-import android.os.Parcel;
-
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.Buffer;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.Set;
-
-import javax.imageio.ImageIO;
-import libcore.util.NativeAllocationRegistry_Delegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.Bitmap
- *
- * Through the layoutlib_create tool, the original native methods of Bitmap have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Bitmap class.
- *
- * @see DelegateManager
- *
- */
-public final class Bitmap_Delegate {
-
-
- public enum BitmapCreateFlags {
- NONE, PREMULTIPLIED, MUTABLE
- }
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager<>(Bitmap_Delegate.class);
- private static long sFinalizer = -1;
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
- private final Config mConfig;
- private final BufferedImage mImage;
- private boolean mHasAlpha = true;
- private boolean mHasMipMap = false; // TODO: check the default.
- private boolean mIsPremultiplied = true;
- private int mGenerationId = 0;
-
-
- // ---- Public Helper methods ----
-
- /**
- * Returns the native delegate associated to a given an int referencing a {@link Bitmap} object.
- */
- public static Bitmap_Delegate getDelegate(long native_bitmap) {
- return sManager.getDelegate(native_bitmap);
- }
-
- @Nullable
- public static Bitmap_Delegate getDelegate(@Nullable Bitmap bitmap) {
- return bitmap == null ? null : getDelegate(bitmap.getNativeInstance());
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given file content.
- *
- * @param input the file from which to read the bitmap content
- * @param isMutable whether the bitmap is mutable
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- public static Bitmap createBitmap(File input, boolean isMutable, Density density)
- throws IOException {
- return createBitmap(input, getPremultipliedBitmapCreateFlags(isMutable), density);
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given file content.
- *
- * @param input the file from which to read the bitmap content
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isPremultiplied()
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- private static Bitmap createBitmap(File input, Set createFlags,
- Density density) throws IOException {
- // create a delegate with the content of the file.
- BufferedImage image = ImageIO.read(input);
- if (image == null && input.exists()) {
- // There was a problem decoding the image, or the decoder isn't registered. Webp maybe.
- // Replace with a broken image icon.
- BridgeContext currentContext = RenderAction.getCurrentContext();
- if (currentContext != null) {
- RenderResources resources = currentContext.getRenderResources();
- ResourceValue broken = resources.getFrameworkResource(ResourceType.DRAWABLE,
- "ic_menu_report_image");
- File brokenFile = new File(broken.getValue());
- if (brokenFile.exists()) {
- image = ImageIO.read(brokenFile);
- }
- }
- }
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.ARGB_8888);
-
- return createBitmap(delegate, createFlags, density.getDpiValue());
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given stream content.
- *
- * @param input the stream from which to read the bitmap content
- * @param isMutable whether the bitmap is mutable
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- public static Bitmap createBitmap(InputStream input, boolean isMutable, Density density)
- throws IOException {
- return createBitmap(input, getPremultipliedBitmapCreateFlags(isMutable), density);
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given stream content.
- *
- * @param input the stream from which to read the bitmap content
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isPremultiplied()
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- public static Bitmap createBitmap(InputStream input, Set createFlags,
- Density density) throws IOException {
- // create a delegate with the content of the stream.
- Bitmap_Delegate delegate = new Bitmap_Delegate(ImageIO.read(input), Config.ARGB_8888);
-
- return createBitmap(delegate, createFlags, density.getDpiValue());
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given {@link BufferedImage}
- *
- * @param image the bitmap content
- * @param isMutable whether the bitmap is mutable
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- public static Bitmap createBitmap(BufferedImage image, boolean isMutable, Density density) {
- return createBitmap(image, getPremultipliedBitmapCreateFlags(isMutable), density);
- }
-
- /**
- * Creates and returns a {@link Bitmap} initialized with the given {@link BufferedImage}
- *
- * @param image the bitmap content
- * @param density the density associated with the bitmap
- *
- * @see Bitmap#isPremultiplied()
- * @see Bitmap#isMutable()
- * @see Bitmap#getDensity()
- */
- public static Bitmap createBitmap(BufferedImage image, Set createFlags,
- Density density) {
- // create a delegate with the given image.
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.ARGB_8888);
-
- return createBitmap(delegate, createFlags, density.getDpiValue());
- }
-
- private static int getBufferedImageType() {
- return BufferedImage.TYPE_INT_ARGB;
- }
-
- /**
- * Returns the {@link BufferedImage} used by the delegate of the given {@link Bitmap}.
- */
- public BufferedImage getImage() {
- return mImage;
- }
-
- /**
- * Returns the Android bitmap config. Note that this not the config of the underlying
- * Java2D bitmap.
- */
- public Config getConfig() {
- return mConfig;
- }
-
- /**
- * Returns the hasAlpha rendering hint
- * @return true if the bitmap alpha should be used at render time
- */
- public boolean hasAlpha() {
- return mHasAlpha && mConfig != Config.RGB_565;
- }
-
- /**
- * Update the generationId.
- *
- * @see Bitmap#getGenerationId()
- */
- public void change() {
- mGenerationId++;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCreate(int[] colors, int offset, int stride, int width,
- int height, int nativeConfig, boolean isMutable, @Nullable float[] xyzD50,
- @Nullable ColorSpace.Rgb.TransferParameters p) {
- int imageType = getBufferedImageType();
-
- // create the image
- BufferedImage image = new BufferedImage(width, height, imageType);
-
- if (colors != null) {
- image.setRGB(0, 0, width, height, colors, offset, stride);
- }
-
- // create a delegate with the content of the stream.
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.nativeToConfig(nativeConfig));
-
- return createBitmap(delegate, getPremultipliedBitmapCreateFlags(isMutable),
- Bitmap.getDefaultDensity());
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCopy(long srcBitmap, int nativeConfig, boolean isMutable) {
- Bitmap_Delegate srcBmpDelegate = sManager.getDelegate(srcBitmap);
- if (srcBmpDelegate == null) {
- return null;
- }
-
- BufferedImage srcImage = srcBmpDelegate.getImage();
-
- int width = srcImage.getWidth();
- int height = srcImage.getHeight();
-
- int imageType = getBufferedImageType();
-
- // create the image
- BufferedImage image = new BufferedImage(width, height, imageType);
-
- // copy the source image into the image.
- int[] argb = new int[width * height];
- srcImage.getRGB(0, 0, width, height, argb, 0, width);
- image.setRGB(0, 0, width, height, argb, 0, width);
-
- // create a delegate with the content of the stream.
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.nativeToConfig(nativeConfig));
-
- return createBitmap(delegate, getPremultipliedBitmapCreateFlags(isMutable),
- Bitmap.getDefaultDensity());
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCopyAshmem(long nativeSrcBitmap) {
- // Unused method; no implementation provided.
- assert false;
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig) {
- // Unused method; no implementation provided.
- assert false;
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeGetNativeFinalizer() {
- synchronized (Bitmap_Delegate.class) {
- if (sFinalizer == -1) {
- sFinalizer = NativeAllocationRegistry_Delegate.createFinalizer(sManager::removeJavaReferenceFor);
- }
- return sFinalizer;
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeRecycle(long nativeBitmap) {
- // In our case reycle() is a no-op. We will let the finalizer to dispose the bitmap.
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeReconfigure(long nativeBitmap, int width, int height,
- int config, boolean isPremultiplied) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.reconfigure() is not supported", null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeCompress(long nativeBitmap, int format, int quality,
- OutputStream stream, byte[] tempStorage) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.compress() is not supported", null /*data*/);
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeErase(long nativeBitmap, int color) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- BufferedImage image = delegate.mImage;
-
- Graphics2D g = image.createGraphics();
- try {
- g.setColor(new java.awt.Color(color, true));
-
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- } finally {
- g.dispose();
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeRowBytes(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mImage.getWidth();
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeConfig(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mConfig.nativeInt;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeHasAlpha(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- return delegate == null || delegate.mHasAlpha;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeHasMipMap(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- return delegate == null || delegate.mHasMipMap;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeGetPixel(long nativeBitmap, int x, int y) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mImage.getRGB(x, y);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeGetPixels(long nativeBitmap, int[] pixels, int offset,
- int stride, int x, int y, int width, int height) {
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.getImage().getRGB(x, y, width, height, pixels, offset, stride);
- }
-
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetPixel(long nativeBitmap, int x, int y, int color) {
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.getImage().setRGB(x, y, color);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetPixels(long nativeBitmap, int[] colors, int offset,
- int stride, int x, int y, int width, int height) {
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.getImage().setRGB(x, y, width, height, colors, offset, stride);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeCopyPixelsToBuffer(long nativeBitmap, Buffer dst) {
- // FIXME implement native delegate
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.copyPixelsToBuffer is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeCopyPixelsFromBuffer(long nb, Buffer src) {
- // FIXME implement native delegate
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.copyPixelsFromBuffer is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeGenerationId(long nativeBitmap) {
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mGenerationId;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCreateFromParcel(Parcel p) {
- // This is only called by Bitmap.CREATOR (Parcelable.Creator), which is only
- // used during aidl call so really this should not be called.
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "AIDL is not suppored, and therefore Bitmaps cannot be created from parcels.",
- null /*data*/);
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeWriteToParcel(long nativeBitmap, boolean isMutable,
- int density, Parcel p) {
- // This is only called when sending a bitmap through aidl, so really this should not
- // be called.
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "AIDL is not suppored, and therefore Bitmaps cannot be written to parcels.",
- null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeExtractAlpha(long nativeBitmap, long nativePaint,
- int[] offsetXY) {
- Bitmap_Delegate bitmap = sManager.getDelegate(nativeBitmap);
- if (bitmap == null) {
- return null;
- }
-
- // get the paint which can be null if nativePaint is 0.
- Paint_Delegate paint = Paint_Delegate.getDelegate(nativePaint);
-
- if (paint != null && paint.getMaskFilter() != null) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MASKFILTER,
- "MaskFilter not supported in Bitmap.extractAlpha",
- null, null /*data*/);
- }
-
- int alpha = paint != null ? paint.getAlpha() : 0xFF;
- BufferedImage image = createCopy(bitmap.getImage(), BufferedImage.TYPE_INT_ARGB, alpha);
-
- // create the delegate. The actual Bitmap config is only an alpha channel
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, Config.ALPHA_8);
-
- // the density doesn't matter, it's set by the Java method.
- return createBitmap(delegate, EnumSet.of(BitmapCreateFlags.MUTABLE),
- Density.DEFAULT_DENSITY /*density*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeIsPremultiplied(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- return delegate != null && delegate.mIsPremultiplied;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetPremultiplied(long nativeBitmap, boolean isPremul) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.mIsPremultiplied = isPremul;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetHasAlpha(long nativeBitmap, boolean hasAlpha,
- boolean isPremul) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.mHasAlpha = hasAlpha;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return;
- }
-
- delegate.mHasMipMap = hasMipMap;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeSameAs(long nb0, long nb1) {
- Bitmap_Delegate delegate1 = sManager.getDelegate(nb0);
- if (delegate1 == null) {
- return false;
- }
-
- Bitmap_Delegate delegate2 = sManager.getDelegate(nb1);
- if (delegate2 == null) {
- return false;
- }
-
- BufferedImage image1 = delegate1.getImage();
- BufferedImage image2 = delegate2.getImage();
- if (delegate1.mConfig != delegate2.mConfig ||
- image1.getWidth() != image2.getWidth() ||
- image1.getHeight() != image2.getHeight()) {
- return false;
- }
-
- // get the internal data
- int w = image1.getWidth();
- int h = image2.getHeight();
- int[] argb1 = new int[w*h];
- int[] argb2 = new int[w*h];
-
- image1.getRGB(0, 0, w, h, argb1, 0, w);
- image2.getRGB(0, 0, w, h, argb2, 0, w);
-
- // compares
- if (delegate1.mConfig == Config.ALPHA_8) {
- // in this case we have to manually compare the alpha channel as the rest is garbage.
- final int length = w*h;
- for (int i = 0 ; i < length ; i++) {
- if ((argb1[i] & 0xFF000000) != (argb2[i] & 0xFF000000)) {
- return false;
- }
- }
- return true;
- }
-
- return Arrays.equals(argb1, argb2);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeGetAllocationByteCount(long nativeBitmap) {
- // get the delegate from the native int.
- Bitmap_Delegate delegate = sManager.getDelegate(nativeBitmap);
- if (delegate == null) {
- return 0;
- }
- return nativeRowBytes(nativeBitmap) * delegate.mImage.getHeight();
-
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativePrepareToDraw(long nativeBitmap) {
- // do nothing as Bitmap_Delegate does not have caches
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCopyPreserveInternalConfig(long nativeBitmap) {
- Bitmap_Delegate srcBmpDelegate = sManager.getDelegate(nativeBitmap);
- if (srcBmpDelegate == null) {
- return null;
- }
-
- BufferedImage srcImage = srcBmpDelegate.getImage();
-
- // create the image
- BufferedImage image = new BufferedImage(srcImage.getColorModel(), srcImage.copyData(null),
- srcImage.isAlphaPremultiplied(), null);
-
- // create a delegate with the content of the stream.
- Bitmap_Delegate delegate = new Bitmap_Delegate(image, srcBmpDelegate.getConfig());
-
- return createBitmap(delegate, EnumSet.of(BitmapCreateFlags.NONE),
- Bitmap.getDefaultDensity());
- }
-
- @LayoutlibDelegate
- /*package*/ static Bitmap nativeCreateHardwareBitmap(GraphicBuffer buffer) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.nativeCreateHardwareBitmap() is not supported", null /*data*/);
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static GraphicBuffer nativeCreateGraphicBufferHandle(long nativeBitmap) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Bitmap.nativeCreateGraphicBufferHandle() is not supported", null /*data*/);
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeIsSRGB(long nativeBitmap) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Color spaces are not supported", null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeGetColorSpace(long nativePtr, float[] xyz, float[] params) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Color spaces are not supported", null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeCopyColorSpace(long srcBitmap, long dstBitmap) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "Color spaces are not supported", null /*data*/);
- }
-
- // ---- Private delegate/helper methods ----
-
- private Bitmap_Delegate(BufferedImage image, Config config) {
- mImage = image;
- mConfig = config;
- }
-
- private static Bitmap createBitmap(Bitmap_Delegate delegate,
- Set createFlags, int density) {
- // get its native_int
- long nativeInt = sManager.addNewDelegate(delegate);
-
- int width = delegate.mImage.getWidth();
- int height = delegate.mImage.getHeight();
- boolean isMutable = createFlags.contains(BitmapCreateFlags.MUTABLE);
- boolean isPremultiplied = createFlags.contains(BitmapCreateFlags.PREMULTIPLIED);
-
- // and create/return a new Bitmap with it
- return new Bitmap(nativeInt, width, height, density, isMutable,
- isPremultiplied, null /*ninePatchChunk*/, null /* layoutBounds */);
- }
-
- private static Set getPremultipliedBitmapCreateFlags(boolean isMutable) {
- Set createFlags = EnumSet.of(BitmapCreateFlags.PREMULTIPLIED);
- if (isMutable) {
- createFlags.add(BitmapCreateFlags.MUTABLE);
- }
- return createFlags;
- }
-
- /**
- * Creates and returns a copy of a given BufferedImage.
- *
- * if alpha is different than 255, then it is applied to the alpha channel of each pixel.
- *
- * @param image the image to copy
- * @param imageType the type of the new image
- * @param alpha an optional alpha modifier
- * @return a new BufferedImage
- */
- /*package*/ static BufferedImage createCopy(BufferedImage image, int imageType, int alpha) {
- int w = image.getWidth();
- int h = image.getHeight();
-
- BufferedImage result = new BufferedImage(w, h, imageType);
-
- int[] argb = new int[w * h];
- image.getRGB(0, 0, image.getWidth(), image.getHeight(), argb, 0, image.getWidth());
-
- if (alpha != 255) {
- final int length = argb.length;
- for (int i = 0 ; i < length; i++) {
- int a = (argb[i] >>> 24 * alpha) / 255;
- argb[i] = (a << 24) | (argb[i] & 0x00FFFFFF);
- }
- }
-
- result.setRGB(0, 0, w, h, argb, 0, w);
-
- return result;
- }
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BlendComposite.java b/tools/layoutlib/bridge/src/android/graphics/BlendComposite.java
deleted file mode 100644
index 5cc964aee722c..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BlendComposite.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import java.awt.Composite;
-import java.awt.CompositeContext;
-import java.awt.RenderingHints;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-import java.awt.image.Raster;
-import java.awt.image.WritableRaster;
-
-/*
- * (non-Javadoc)
- * The class is adapted from a demo tool for Blending Modes written by
- * Romain Guy (romainguy@android.com). The tool is available at
- * http://www.curious-creature.org/2006/09/20/new-blendings-modes-for-java2d/
- *
- * This class has been adapted for applying color filters. When applying color filters, the src
- * image should not extend beyond the dest image, but in our implementation of the filters, it does.
- * To compensate for the effect, we recompute the alpha value of the src image before applying
- * the color filter as it should have been applied.
- */
-public final class BlendComposite implements Composite {
- public enum BlendingMode {
- MULTIPLY(),
- SCREEN(),
- DARKEN(),
- LIGHTEN(),
- OVERLAY(),
- ADD();
-
- private final BlendComposite mComposite;
-
- BlendingMode() {
- mComposite = new BlendComposite(this);
- }
-
- BlendComposite getBlendComposite() {
- return mComposite;
- }
- }
-
- private float alpha;
- private BlendingMode mode;
-
- private BlendComposite(BlendingMode mode) {
- this(mode, 1.0f);
- }
-
- private BlendComposite(BlendingMode mode, float alpha) {
- this.mode = mode;
- setAlpha(alpha);
- }
-
- public static BlendComposite getInstance(BlendingMode mode) {
- return mode.getBlendComposite();
- }
-
- public static BlendComposite getInstance(BlendingMode mode, float alpha) {
- if (alpha > 0.9999f) {
- return getInstance(mode);
- }
- return new BlendComposite(mode, alpha);
- }
-
- public float getAlpha() {
- return alpha;
- }
-
- public BlendingMode getMode() {
- return mode;
- }
-
- private void setAlpha(float alpha) {
- if (alpha < 0.0f || alpha > 1.0f) {
- assert false : "alpha must be comprised between 0.0f and 1.0f";
- alpha = Math.min(alpha, 1.0f);
- alpha = Math.max(alpha, 0.0f);
- }
-
- this.alpha = alpha;
- }
-
- @Override
- public int hashCode() {
- return Float.floatToIntBits(alpha) * 31 + mode.ordinal();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof BlendComposite)) {
- return false;
- }
-
- BlendComposite bc = (BlendComposite) obj;
-
- return mode == bc.mode && alpha == bc.alpha;
- }
-
- public CompositeContext createContext(ColorModel srcColorModel,
- ColorModel dstColorModel,
- RenderingHints hints) {
- return new BlendingContext(this);
- }
-
- private static final class BlendingContext implements CompositeContext {
- private final Blender blender;
- private final BlendComposite composite;
-
- private BlendingContext(BlendComposite composite) {
- this.composite = composite;
- this.blender = Blender.getBlenderFor(composite);
- }
-
- public void dispose() {
- }
-
- public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
- if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT ||
- dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT ||
- dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) {
- throw new IllegalStateException(
- "Source and destination must store pixels as INT.");
- }
-
- int width = Math.min(src.getWidth(), dstIn.getWidth());
- int height = Math.min(src.getHeight(), dstIn.getHeight());
-
- float alpha = composite.getAlpha();
-
- int[] srcPixel = new int[4];
- int[] dstPixel = new int[4];
- int[] result = new int[4];
- int[] srcPixels = new int[width];
- int[] dstPixels = new int[width];
-
- for (int y = 0; y < height; y++) {
- dstIn.getDataElements(0, y, width, 1, dstPixels);
- if (alpha != 0) {
- src.getDataElements(0, y, width, 1, srcPixels);
- for (int x = 0; x < width; x++) {
- // pixels are stored as INT_ARGB
- // our arrays are [R, G, B, A]
- int pixel = srcPixels[x];
- srcPixel[0] = (pixel >> 16) & 0xFF;
- srcPixel[1] = (pixel >> 8) & 0xFF;
- srcPixel[2] = (pixel ) & 0xFF;
- srcPixel[3] = (pixel >> 24) & 0xFF;
-
- pixel = dstPixels[x];
- dstPixel[0] = (pixel >> 16) & 0xFF;
- dstPixel[1] = (pixel >> 8) & 0xFF;
- dstPixel[2] = (pixel ) & 0xFF;
- dstPixel[3] = (pixel >> 24) & 0xFF;
-
- // ---- Modified from original ----
- // recompute src pixel for transparency.
- srcPixel[3] *= dstPixel[3] / 0xFF;
- // ---- Modification ends ----
-
- result = blender.blend(srcPixel, dstPixel, result);
-
- // mixes the result with the opacity
- if (alpha == 1) {
- dstPixels[x] = (result[3] & 0xFF) << 24 |
- (result[0] & 0xFF) << 16 |
- (result[1] & 0xFF) << 8 |
- result[2] & 0xFF;
- } else {
- dstPixels[x] =
- ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 |
- ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 |
- ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 |
- (int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF;
- }
-
- }
- }
- dstOut.setDataElements(0, y, width, 1, dstPixels);
- }
- }
- }
-
- private static abstract class Blender {
- public abstract int[] blend(int[] src, int[] dst, int[] result);
-
- public static Blender getBlenderFor(BlendComposite composite) {
- switch (composite.getMode()) {
- case ADD:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- for (int i = 0; i < 4; i++) {
- result[i] = Math.min(255, src[i] + dst[i]);
- }
- return result;
- }
- };
- case DARKEN:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- for (int i = 0; i < 3; i++) {
- result[i] = Math.min(src[i], dst[i]);
- }
- result[3] = Math.min(255, src[3] + dst[3]);
- return result;
- }
- };
- case LIGHTEN:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- for (int i = 0; i < 3; i++) {
- result[i] = Math.max(src[i], dst[i]);
- }
- result[3] = Math.min(255, src[3] + dst[3]);
- return result;
- }
- };
- case MULTIPLY:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- for (int i = 0; i < 3; i++) {
- result[i] = (src[i] * dst[i]) >> 8;
- }
- result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255);
- return result;
- }
- };
- case OVERLAY:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- for (int i = 0; i < 3; i++) {
- result[i] = dst[i] < 128 ? dst[i] * src[i] >> 7 :
- 255 - ((255 - dst[i]) * (255 - src[i]) >> 7);
- }
- result[3] = Math.min(255, src[3] + dst[3]);
- return result;
- }
- };
- case SCREEN:
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- result[0] = 255 - ((255 - src[0]) * (255 - dst[0]) >> 8);
- result[1] = 255 - ((255 - src[1]) * (255 - dst[1]) >> 8);
- result[2] = 255 - ((255 - src[2]) * (255 - dst[2]) >> 8);
- result[3] = Math.min(255, src[3] + dst[3]);
- return result;
- }
- };
- default:
- assert false : "Blender not implement for " + composite.getMode().name();
-
- // Ignore the blend
- return new Blender() {
- @Override
- public int[] blend(int[] src, int[] dst, int[] result) {
- result[0] = dst[0];
- result[1] = dst[1];
- result[2] = dst[2];
- result[3] = dst[3];
- return result;
- }
- };
- }
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java
deleted file mode 100644
index d2569c777527f..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/BlurMaskFilter_Delegate.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.BlurMaskFilter
- *
- * Through the layoutlib_create tool, the original native methods of BlurMaskFilter have
- * been replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original BlurMaskFilter class.
- *
- * Because this extends {@link MaskFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the Shader classes will be added to the manager
- * owned by {@link MaskFilter_Delegate}.
- *
- * @see MaskFilter_Delegate
- *
- */
-public class BlurMaskFilter_Delegate extends MaskFilter_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Blur Mask Filters are not supported.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeConstructor(float radius, int style) {
- BlurMaskFilter_Delegate newDelegate = new BlurMaskFilter_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
deleted file mode 100644
index 47216eec03bdc..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
+++ /dev/null
@@ -1,484 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.impl.GcSnapshot;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.Nullable;
-import android.graphics.Bitmap.Config;
-
-import java.awt.Graphics2D;
-import java.awt.Rectangle;
-import java.awt.geom.AffineTransform;
-
-import libcore.util.NativeAllocationRegistry_Delegate;
-
-
-/**
- * Delegate implementing the native methods of android.graphics.Canvas
- *
- * Through the layoutlib_create tool, the original native methods of Canvas have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Canvas class.
- *
- * @see DelegateManager
- *
- */
-public final class Canvas_Delegate extends BaseCanvas_Delegate {
-
- // ---- delegate manager ----
- private static long sFinalizer = -1;
-
- private DrawFilter_Delegate mDrawFilter = null;
-
- // ---- Public Helper methods ----
-
- /**
- * Returns the native delegate associated to a given {@link Canvas} object.
- */
- public static Canvas_Delegate getDelegate(Canvas canvas) {
- return (Canvas_Delegate) sManager.getDelegate(canvas.getNativeCanvasWrapper());
- }
-
- /**
- * Returns the native delegate associated to a given an int referencing a {@link Canvas} object.
- */
- public static Canvas_Delegate getDelegate(long native_canvas) {
- return (Canvas_Delegate) sManager.getDelegate(native_canvas);
- }
-
- /**
- * Returns the current {@link Graphics2D} used to draw.
- */
- public GcSnapshot getSnapshot() {
- return mSnapshot;
- }
-
- /**
- * Returns the {@link DrawFilter} delegate or null if none have been set.
- *
- * @return the delegate or null.
- */
- public DrawFilter_Delegate getDrawFilter() {
- return mDrawFilter;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nFreeCaches() {
- // nothing to be done here.
- }
-
- @LayoutlibDelegate
- /*package*/ static void nFreeTextLayoutCaches() {
- // nothing to be done here yet.
- }
-
- @LayoutlibDelegate
- /*package*/ static long nInitRaster(@Nullable Bitmap bitmap) {
- long nativeBitmapOrZero = 0;
- if (bitmap != null) {
- nativeBitmapOrZero = bitmap.getNativeInstance();
- }
- if (nativeBitmapOrZero > 0) {
- // get the Bitmap from the int
- Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(nativeBitmapOrZero);
-
- // create a new Canvas_Delegate with the given bitmap and return its new native int.
- Canvas_Delegate newDelegate = new Canvas_Delegate(bitmapDelegate);
-
- return sManager.addNewDelegate(newDelegate);
- }
-
- // create a new Canvas_Delegate and return its new native int.
- Canvas_Delegate newDelegate = new Canvas_Delegate();
-
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- public static void nSetBitmap(long canvas, Bitmap bitmap) {
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(canvas);
- Bitmap_Delegate bitmapDelegate = Bitmap_Delegate.getDelegate(bitmap);
- if (canvasDelegate == null || bitmapDelegate==null) {
- return;
- }
- canvasDelegate.mBitmap = bitmapDelegate;
- canvasDelegate.mSnapshot = GcSnapshot.createDefaultSnapshot(bitmapDelegate);
- }
-
- @LayoutlibDelegate
- public static boolean nIsOpaque(long nativeCanvas) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return false;
- }
-
- return canvasDelegate.mBitmap.getConfig() == Config.RGB_565;
- }
-
- @LayoutlibDelegate
- public static void nSetHighContrastText(long nativeCanvas, boolean highContrastText){}
-
- @LayoutlibDelegate
- public static int nGetWidth(long nativeCanvas) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.mBitmap.getImage().getWidth();
- }
-
- @LayoutlibDelegate
- public static int nGetHeight(long nativeCanvas) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.mBitmap.getImage().getHeight();
- }
-
- @LayoutlibDelegate
- public static int nSave(long nativeCanvas, int saveFlags) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.save(saveFlags);
- }
-
- @LayoutlibDelegate
- public static int nSaveLayer(long nativeCanvas, float l,
- float t, float r, float b,
- long paint, int layerFlags) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- Paint_Delegate paintDelegate = Paint_Delegate.getDelegate(paint);
- if (paintDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.saveLayer(new RectF(l, t, r, b),
- paintDelegate, layerFlags);
- }
-
- @LayoutlibDelegate
- public static int nSaveLayerAlpha(long nativeCanvas, float l,
- float t, float r, float b,
- int alpha, int layerFlags) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.saveLayerAlpha(new RectF(l, t, r, b), alpha, layerFlags);
- }
-
- @LayoutlibDelegate
- public static boolean nRestore(long nativeCanvas) {
- // FIXME: implement throwOnUnderflow.
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return false;
- }
-
- canvasDelegate.restore();
- return true;
- }
-
- @LayoutlibDelegate
- public static void nRestoreToCount(long nativeCanvas, int saveCount) {
- // FIXME: implement throwOnUnderflow.
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.restoreTo(saveCount);
- }
-
- @LayoutlibDelegate
- public static int nGetSaveCount(long nativeCanvas) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return 0;
- }
-
- return canvasDelegate.getSnapshot().size();
- }
-
- @LayoutlibDelegate
- public static void nTranslate(long nativeCanvas, float dx, float dy) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.getSnapshot().translate(dx, dy);
- }
-
- @LayoutlibDelegate
- public static void nScale(long nativeCanvas, float sx, float sy) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.getSnapshot().scale(sx, sy);
- }
-
- @LayoutlibDelegate
- public static void nRotate(long nativeCanvas, float degrees) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.getSnapshot().rotate(Math.toRadians(degrees));
- }
-
- @LayoutlibDelegate
- public static void nSkew(long nativeCanvas, float kx, float ky) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- // get the current top graphics2D object.
- GcSnapshot g = canvasDelegate.getSnapshot();
-
- // get its current matrix
- AffineTransform currentTx = g.getTransform();
- // get the AffineTransform for the given skew.
- float[] mtx = Matrix_Delegate.getSkew(kx, ky);
- AffineTransform matrixTx = Matrix_Delegate.getAffineTransform(mtx);
-
- // combine them so that the given matrix is applied after.
- currentTx.preConcatenate(matrixTx);
-
- // give it to the graphics2D as a new matrix replacing all previous transform
- g.setTransform(currentTx);
- }
-
- @LayoutlibDelegate
- public static void nConcat(long nCanvas, long nMatrix) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
- if (matrixDelegate == null) {
- return;
- }
-
- // get the current top graphics2D object.
- GcSnapshot snapshot = canvasDelegate.getSnapshot();
-
- // get its current matrix
- AffineTransform currentTx = snapshot.getTransform();
- // get the AffineTransform of the given matrix
- AffineTransform matrixTx = matrixDelegate.getAffineTransform();
-
- // combine them so that the given matrix is applied after.
- currentTx.concatenate(matrixTx);
-
- // give it to the graphics2D as a new matrix replacing all previous transform
- snapshot.setTransform(currentTx);
- }
-
- @LayoutlibDelegate
- public static void nSetMatrix(long nCanvas, long nMatrix) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(nMatrix);
- if (matrixDelegate == null) {
- return;
- }
-
- // get the current top graphics2D object.
- GcSnapshot snapshot = canvasDelegate.getSnapshot();
-
- // get the AffineTransform of the given matrix
- AffineTransform matrixTx = matrixDelegate.getAffineTransform();
-
- // give it to the graphics2D as a new matrix replacing all previous transform
- snapshot.setTransform(matrixTx);
-
- if (matrixDelegate.hasPerspective()) {
- assert false;
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_AFFINE,
- "android.graphics.Canvas#setMatrix(android.graphics.Matrix) only " +
- "supports affine transformations.", null, null /*data*/);
- }
- }
-
- @LayoutlibDelegate
- public static boolean nClipRect(long nCanvas,
- float left, float top,
- float right, float bottom,
- int regionOp) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nCanvas);
- if (canvasDelegate == null) {
- return false;
- }
-
- return canvasDelegate.clipRect(left, top, right, bottom, regionOp);
- }
-
- @LayoutlibDelegate
- public static boolean nClipPath(long nativeCanvas,
- long nativePath,
- int regionOp) {
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return true;
- }
-
- Path_Delegate pathDelegate = Path_Delegate.getDelegate(nativePath);
- if (pathDelegate == null) {
- return true;
- }
-
- return canvasDelegate.mSnapshot.clip(pathDelegate.getJavaShape(), regionOp);
- }
-
- @LayoutlibDelegate
- public static void nSetDrawFilter(long nativeCanvas, long nativeFilter) {
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return;
- }
-
- canvasDelegate.mDrawFilter = DrawFilter_Delegate.getDelegate(nativeFilter);
-
- if (canvasDelegate.mDrawFilter != null && !canvasDelegate.mDrawFilter.isSupported()) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_DRAWFILTER,
- canvasDelegate.mDrawFilter.getSupportMessage(), null, null /*data*/);
- }
- }
-
- @LayoutlibDelegate
- public static boolean nGetClipBounds(long nativeCanvas,
- Rect bounds) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(nativeCanvas);
- if (canvasDelegate == null) {
- return false;
- }
-
- Rectangle rect = canvasDelegate.getSnapshot().getClip().getBounds();
- if (rect != null && !rect.isEmpty()) {
- bounds.left = rect.x;
- bounds.top = rect.y;
- bounds.right = rect.x + rect.width;
- bounds.bottom = rect.y + rect.height;
- return true;
- }
-
- return false;
- }
-
- @LayoutlibDelegate
- public static void nGetMatrix(long canvas, long matrix) {
- // get the delegate from the native int.
- Canvas_Delegate canvasDelegate = Canvas_Delegate.getDelegate(canvas);
- if (canvasDelegate == null) {
- return;
- }
-
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
- if (matrixDelegate == null) {
- return;
- }
-
- AffineTransform transform = canvasDelegate.getSnapshot().getTransform();
- matrixDelegate.set(Matrix_Delegate.makeValues(transform));
- }
-
- @LayoutlibDelegate
- public static boolean nQuickReject(long nativeCanvas, long path) {
- // FIXME properly implement quickReject
- return false;
- }
-
- @LayoutlibDelegate
- public static boolean nQuickReject(long nativeCanvas,
- float left, float top,
- float right, float bottom) {
- // FIXME properly implement quickReject
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetNativeFinalizer() {
- synchronized (Canvas_Delegate.class) {
- if (sFinalizer == -1) {
- sFinalizer = NativeAllocationRegistry_Delegate.createFinalizer(nativePtr -> {
- Canvas_Delegate delegate = Canvas_Delegate.getDelegate(nativePtr);
- if (delegate != null) {
- delegate.dispose();
- }
- sManager.removeJavaReferenceFor(nativePtr);
- });
- }
- }
- return sFinalizer;
- }
-
- private Canvas_Delegate(Bitmap_Delegate bitmap) {
- super(bitmap);
- }
-
- private Canvas_Delegate() {
- super();
- }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java
deleted file mode 100644
index cb013b60a06cc..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/ColorFilter_Delegate.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Graphics2D;
-
-/**
- * Delegate implementing the native methods of android.graphics.ColorFilter
- *
- * Through the layoutlib_create tool, the original native methods of ColorFilter have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original ColorFilter class.
- *
- * This also serve as a base class for all ColorFilter delegate classes.
- *
- * @see DelegateManager
- *
- */
-public abstract class ColorFilter_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(ColorFilter_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- public static ColorFilter_Delegate getDelegate(long nativeShader) {
- return sManager.getDelegate(nativeShader);
- }
-
- public abstract String getSupportMessage();
-
- public boolean isSupported() {
- return false;
- }
-
- public void applyFilter(Graphics2D g, int width, int height) {
- // This should never be called directly. If supported, the sub class should override this.
- assert false;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nSafeUnref(long native_instance) {
- sManager.removeJavaReferenceFor(native_instance);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java
deleted file mode 100644
index 67394847fa444..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/ColorMatrixColorFilter_Delegate.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.ColorMatrixColorFilter
- *
- * Through the layoutlib_create tool, the original native methods of ColorMatrixColorFilter have
- * been replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original ColorMatrixColorFilter class.
- *
- * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the Shader classes will be added to the manager
- * owned by {@link ColorFilter_Delegate}.
- *
- * @see ColorFilter_Delegate
- *
- */
-public class ColorMatrixColorFilter_Delegate extends ColorFilter_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public String getSupportMessage() {
- return "ColorMatrix Color Filters are not supported.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeColorMatrixFilter(float[] array) {
- ColorMatrixColorFilter_Delegate newDelegate = new ColorMatrixColorFilter_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java
deleted file mode 100644
index bc3df7d848945..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/ComposePathEffect_Delegate.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.ComposePathEffect
- *
- * Through the layoutlib_create tool, the original native methods of ComposePathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original ComposePathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public class ComposePathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Compose Path Effects are not supported in Layout Preview mode.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(long outerpe, long innerpe) {
- ComposePathEffect_Delegate newDelegate = new ComposePathEffect_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java
deleted file mode 100644
index ab37968a1dea4..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/ComposeShader_Delegate.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Paint;
-
-/**
- * Delegate implementing the native methods of android.graphics.ComposeShader
- *
- * Through the layoutlib_create tool, the original native methods of ComposeShader have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original ComposeShader class.
- *
- * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
- *
- * @see Shader_Delegate
- *
- */
-public class ComposeShader_Delegate extends Shader_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Paint getJavaPaint() {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Compose Shaders are not supported in Layout Preview mode.";
- }
-
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(long nativeMatrix, long native_shaderA,
- long native_shaderB, int native_mode) {
- // FIXME not supported yet.
- ComposeShader_Delegate newDelegate = new ComposeShader_Delegate(nativeMatrix);
- return sManager.addNewDelegate(newDelegate);
- }
-
-
- // ---- Private delegate/helper methods ----
-
- private ComposeShader_Delegate(long nativeMatrix) {
- super(nativeMatrix);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java
deleted file mode 100644
index 73745c3b0c002..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/CornerPathEffect_Delegate.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.CornerPathEffect
- *
- * Through the layoutlib_create tool, the original native methods of CornerPathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original CornerPathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public class CornerPathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Corner Path Effects are not supported in Layout Preview mode.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(float radius) {
- CornerPathEffect_Delegate newDelegate = new CornerPathEffect_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java
deleted file mode 100644
index 881afded11589..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/DashPathEffect_Delegate.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.BasicStroke;
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.DashPathEffect
- *
- * Through the layoutlib_create tool, the original native methods of DashPathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original DashPathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the PathEffect classes will be added to the manager owned by
- * {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public final class DashPathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- private final float[] mIntervals;
- private final float mPhase;
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- return new BasicStroke(
- paint.getStrokeWidth(),
- paint.getJavaCap(),
- paint.getJavaJoin(),
- paint.getJavaStrokeMiter(),
- mIntervals,
- mPhase);
- }
-
- @Override
- public boolean isSupported() {
- return true;
- }
-
- @Override
- public String getSupportMessage() {
- // no message since isSupported returns true;
- return null;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(float intervals[], float phase) {
- DashPathEffect_Delegate newDelegate = new DashPathEffect_Delegate(intervals, phase);
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-
- private DashPathEffect_Delegate(float intervals[], float phase) {
- mIntervals = new float[intervals.length];
- System.arraycopy(intervals, 0, mIntervals, 0, intervals.length);
- mPhase = phase;
- }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java
deleted file mode 100644
index 46109f3018e1a..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/DiscretePathEffect_Delegate.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.DiscretePathEffect
- *
- * Through the layoutlib_create tool, the original native methods of DiscretePathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original DiscretePathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public class DiscretePathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Discrete Path Effects are not supported in Layout Preview mode.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(float length, float deviation) {
- DiscretePathEffect_Delegate newDelegate = new DiscretePathEffect_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java
deleted file mode 100644
index 2e1074080bded..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/DrawFilter_Delegate.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.DrawFilter
- *
- * Through the layoutlib_create tool, the original native methods of DrawFilter have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original DrawFilter class.
- *
- * This also serve as a base class for all DrawFilter delegate classes.
- *
- * @see DelegateManager
- *
- */
-public abstract class DrawFilter_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(DrawFilter_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- public static DrawFilter_Delegate getDelegate(long nativeDrawFilter) {
- return sManager.getDelegate(nativeDrawFilter);
- }
-
- public abstract boolean isSupported();
- public abstract String getSupportMessage();
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nativeDestructor(long nativeDrawFilter) {
- sManager.removeJavaReferenceFor(nativeDrawFilter);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java
deleted file mode 100644
index e5040ccc4b1ef..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/EmbossMaskFilter_Delegate.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.EmbossMaskFilter
- *
- * Through the layoutlib_create tool, the original native methods of EmbossMaskFilter have
- * been replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original EmbossMaskFilter class.
- *
- * Because this extends {@link MaskFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the Shader classes will be added to the manager
- * owned by {@link MaskFilter_Delegate}.
- *
- * @see MaskFilter_Delegate
- *
- */
-public class EmbossMaskFilter_Delegate extends MaskFilter_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Emboss Mask Filters are not supported.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeConstructor(float[] direction, float ambient,
- float specular, float blurRadius) {
- EmbossMaskFilter_Delegate newDelegate = new EmbossMaskFilter_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/FontFamily_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/FontFamily_Delegate.java
deleted file mode 100644
index d8e049a990ed2..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/FontFamily_Delegate.java
+++ /dev/null
@@ -1,523 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.AssetRepository;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.res.AssetManager;
-import android.content.res.BridgeAssetManager;
-import android.graphics.fonts.FontVariationAxis;
-import android.text.FontConfig;
-
-import java.awt.Font;
-import java.awt.FontFormatException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Scanner;
-import java.util.Set;
-
-import static android.graphics.Typeface.RESOLVE_BY_FONT_TABLE;
-import static android.graphics.Typeface_Delegate.SYSTEM_FONTS;
-
-/**
- * Delegate implementing the native methods of android.graphics.FontFamily
- *
- * Through the layoutlib_create tool, the original native methods of FontFamily have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original FontFamily class.
- *
- * @see DelegateManager
- */
-public class FontFamily_Delegate {
-
- public static final int DEFAULT_FONT_WEIGHT = 400;
- public static final int BOLD_FONT_WEIGHT_DELTA = 300;
- public static final int BOLD_FONT_WEIGHT = 700;
-
- private static final String FONT_SUFFIX_ITALIC = "Italic.ttf";
- private static final String FN_ALL_FONTS_LIST = "fontsInSdk.txt";
- private static final String EXTENSION_OTF = ".otf";
-
- private static final int CACHE_SIZE = 10;
- // The cache has a drawback that if the font file changed after the font object was created,
- // we will not update it.
- private static final Map sCache =
- new LinkedHashMap(CACHE_SIZE) {
- @Override
- protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > CACHE_SIZE;
- }
-
- @Override
- public FontInfo put(String key, FontInfo value) {
- // renew this entry.
- FontInfo removed = remove(key);
- super.put(key, value);
- return removed;
- }
- };
-
- /**
- * A class associating {@link Font} with its metadata.
- */
- private static final class FontInfo {
- @Nullable
- Font mFont;
- int mWeight;
- boolean mIsItalic;
- }
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(FontFamily_Delegate.class);
-
- // ---- delegate helper data ----
- private static String sFontLocation;
- private static final List sPostInitDelegate = new
- ArrayList();
- private static Set SDK_FONTS;
-
-
- // ---- delegate data ----
- private List mFonts = new ArrayList();
-
- /**
- * The variant of the Font Family - compact or elegant.
- *
- * 0 is unspecified, 1 is compact and 2 is elegant. This needs to be kept in sync with values in
- * android.graphics.FontFamily
- *
- * @see Paint#setElegantTextHeight(boolean)
- */
- private FontVariant mVariant;
- // List of runnables to process fonts after sFontLoader is initialized.
- private List mPostInitRunnables = new ArrayList();
- /** @see #isValid() */
- private boolean mValid = false;
-
-
- // ---- Public helper class ----
-
- public enum FontVariant {
- // The order needs to be kept in sync with android.graphics.FontFamily.
- NONE, COMPACT, ELEGANT
- }
-
- // ---- Public Helper methods ----
-
- public static FontFamily_Delegate getDelegate(long nativeFontFamily) {
- return sManager.getDelegate(nativeFontFamily);
- }
-
- public static synchronized void setFontLocation(String fontLocation) {
- sFontLocation = fontLocation;
- // init list of bundled fonts.
- File allFonts = new File(fontLocation, FN_ALL_FONTS_LIST);
- // Current number of fonts is 103. Use the next round number to leave scope for more fonts
- // in the future.
- Set allFontsList = new HashSet(128);
- Scanner scanner = null;
- try {
- scanner = new Scanner(allFonts);
- while (scanner.hasNext()) {
- String name = scanner.next();
- // Skip font configuration files.
- if (!name.endsWith(".xml")) {
- allFontsList.add(name);
- }
- }
- } catch (FileNotFoundException e) {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Unable to load the list of fonts. Try re-installing the SDK Platform from the SDK Manager.",
- e, null);
- } finally {
- if (scanner != null) {
- scanner.close();
- }
- }
- SDK_FONTS = Collections.unmodifiableSet(allFontsList);
- for (FontFamily_Delegate fontFamily : sPostInitDelegate) {
- fontFamily.init();
- }
- sPostInitDelegate.clear();
- }
-
- @Nullable
- public Font getFont(int desiredWeight, boolean isItalic) {
- FontInfo desiredStyle = new FontInfo();
- desiredStyle.mWeight = desiredWeight;
- desiredStyle.mIsItalic = isItalic;
- FontInfo bestFont = null;
- int bestMatch = Integer.MAX_VALUE;
- //noinspection ForLoopReplaceableByForEach (avoid iterator instantiation)
- for (int i = 0, n = mFonts.size(); i < n; i++) {
- FontInfo font = mFonts.get(i);
- int match = computeMatch(font, desiredStyle);
- if (match < bestMatch) {
- bestMatch = match;
- bestFont = font;
- }
- }
- if (bestFont == null) {
- return null;
- }
- if (bestMatch == 0) {
- return bestFont.mFont;
- }
- // Derive the font as required and add it to the list of Fonts.
- deriveFont(bestFont, desiredStyle);
- addFont(desiredStyle);
- return desiredStyle.mFont;
- }
-
- public FontVariant getVariant() {
- return mVariant;
- }
-
- /**
- * Returns if the FontFamily should contain any fonts. If this returns true and
- * {@link #getFont(int, boolean)} returns an empty list, it means that an error occurred while
- * loading the fonts. However, some fonts are deliberately skipped, for example they are not
- * bundled with the SDK. In such a case, this method returns false.
- */
- public boolean isValid() {
- return mValid;
- }
-
- private static Font loadFont(String path) {
- if (path.startsWith(SYSTEM_FONTS) ) {
- String relativePath = path.substring(SYSTEM_FONTS.length());
- File f = new File(sFontLocation, relativePath);
-
- try {
- return Font.createFont(Font.TRUETYPE_FONT, f);
- } catch (Exception e) {
- if (path.endsWith(EXTENSION_OTF) && e instanceof FontFormatException) {
- // If we aren't able to load an Open Type font, don't log a warning just yet.
- // We wait for a case where font is being used. Only then we try to log the
- // warning.
- return null;
- }
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN,
- String.format("Unable to load font %1$s", relativePath),
- e, null);
- }
- } else {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Only platform fonts located in " + SYSTEM_FONTS + "can be loaded.",
- null, null);
- }
-
- return null;
- }
-
- @Nullable
- /*package*/ static String getFontLocation() {
- return sFontLocation;
- }
-
- // ---- delegate methods ----
- @LayoutlibDelegate
- /*package*/ static boolean addFont(FontFamily thisFontFamily, String path, int ttcIndex,
- FontVariationAxis[] axes, int weight, int italic) {
- if (thisFontFamily.mBuilderPtr == 0) {
- assert false : "Unable to call addFont after freezing.";
- return false;
- }
- final FontFamily_Delegate delegate = getDelegate(thisFontFamily.mBuilderPtr);
- return delegate != null && delegate.addFont(path, ttcIndex, weight, italic);
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nInitBuilder(String lang, int variant) {
- // TODO: support lang. This is required for japanese locale.
- FontFamily_Delegate delegate = new FontFamily_Delegate();
- // variant can be 0, 1 or 2.
- assert variant < 3;
- delegate.mVariant = FontVariant.values()[variant];
- if (sFontLocation != null) {
- delegate.init();
- } else {
- sPostInitDelegate.add(delegate);
- }
- return sManager.addNewDelegate(delegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreateFamily(long builderPtr) {
- return builderPtr;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nUnrefFamily(long nativePtr) {
- // Removing the java reference for the object doesn't mean that it's freed for garbage
- // collection. Typeface_Delegate may still hold a reference for it.
- sManager.removeJavaReferenceFor(nativePtr);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nAddFont(long builderPtr, ByteBuffer font, int ttcIndex,
- int weight, int isItalic) {
- assert false : "The only client of this method has been overridden.";
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nAddFontWeightStyle(long builderPtr, ByteBuffer font,
- int ttcIndex, int weight, int isItalic) {
- assert false : "The only client of this method has been overridden.";
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddAxisValue(long builderPtr, int tag, float value) {
- assert false : "The only client of this method has been overridden.";
- }
-
- static boolean addFont(long builderPtr, final String path, final int weight,
- final boolean isItalic) {
- final FontFamily_Delegate delegate = getDelegate(builderPtr);
- int italic = isItalic ? 1 : 0;
- if (delegate != null) {
- if (sFontLocation == null) {
- delegate.mPostInitRunnables.add(() -> delegate.addFont(path, weight, italic));
- return true;
- }
- return delegate.addFont(path, weight, italic);
- }
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nAddFontFromAssetManager(long builderPtr, AssetManager mgr, String path,
- int cookie, boolean isAsset, int ttcIndex, int weight, int isItalic) {
- FontFamily_Delegate ffd = sManager.getDelegate(builderPtr);
- if (ffd == null) {
- return false;
- }
- ffd.mValid = true;
- if (mgr == null) {
- return false;
- }
- if (mgr instanceof BridgeAssetManager) {
- InputStream fontStream = null;
- try {
- AssetRepository assetRepository = ((BridgeAssetManager) mgr).getAssetRepository();
- if (assetRepository == null) {
- Bridge.getLog().error(LayoutLog.TAG_MISSING_ASSET, "Asset not found: " + path,
- null);
- return false;
- }
- if (!assetRepository.isSupported()) {
- // Don't log any warnings on unsupported IDEs.
- return false;
- }
- // Check cache
- FontInfo fontInfo = sCache.get(path);
- if (fontInfo != null) {
- // renew the font's lease.
- sCache.put(path, fontInfo);
- ffd.addFont(fontInfo);
- return true;
- }
- fontStream = isAsset ?
- assetRepository.openAsset(path, AssetManager.ACCESS_STREAMING) :
- assetRepository.openNonAsset(cookie, path, AssetManager.ACCESS_STREAMING);
- if (fontStream == null) {
- Bridge.getLog().error(LayoutLog.TAG_MISSING_ASSET, "Asset not found: " + path,
- path);
- return false;
- }
- Font font = Font.createFont(Font.TRUETYPE_FONT, fontStream);
- fontInfo = new FontInfo();
- fontInfo.mFont = font;
- if (weight == RESOLVE_BY_FONT_TABLE) {
- fontInfo.mWeight = font.isBold() ? BOLD_FONT_WEIGHT : DEFAULT_FONT_WEIGHT;
- } else {
- fontInfo.mWeight = weight;
- }
- fontInfo.mIsItalic = isItalic == RESOLVE_BY_FONT_TABLE ? font.isItalic() :
- isItalic == 1;
- ffd.addFont(fontInfo);
- return true;
- } catch (IOException e) {
- Bridge.getLog().error(LayoutLog.TAG_MISSING_ASSET, "Unable to load font " + path, e,
- path);
- } catch (FontFormatException e) {
- if (path.endsWith(EXTENSION_OTF)) {
- // otf fonts are not supported on the user's config (JRE version + OS)
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "OpenType fonts are not supported yet: " + path, null, path);
- } else {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Unable to load font " + path, e, path);
- }
- } finally {
- if (fontStream != null) {
- try {
- fontStream.close();
- } catch (IOException ignored) {
- }
- }
- }
- return false;
- }
- // This should never happen. AssetManager is a final class (from user's perspective), and
- // we've replaced every creation of AssetManager with our implementation. We create an
- // exception and log it, but continue with rest of the rendering, without loading this font.
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "You have found a bug in the rendering library. Please file a bug at b.android.com.",
- new RuntimeException("Asset Manager is not an instance of BridgeAssetManager"),
- null);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAbort(long builderPtr) {
- sManager.removeJavaReferenceFor(builderPtr);
- }
-
- /**
- * @see FontFamily#allowUnsupportedFont
- */
- @LayoutlibDelegate
- /*package*/ static void nAllowUnsupportedFont(long builderPtr) {
- // Do nothing here as this is used for Minikin fonts
- }
-
- // ---- private helper methods ----
-
- private void init() {
- for (Runnable postInitRunnable : mPostInitRunnables) {
- postInitRunnable.run();
- }
- mPostInitRunnables = null;
- }
-
- private boolean addFont(final String path, int ttcIndex, int weight, int italic) {
- // FIXME: support ttc fonts. Hack JRE??
- if (sFontLocation == null) {
- mPostInitRunnables.add(() -> addFont(path, weight, italic));
- return true;
- }
- return addFont(path, weight, italic);
- }
-
- private boolean addFont(@NonNull String path) {
- return addFont(path, DEFAULT_FONT_WEIGHT, path.endsWith(FONT_SUFFIX_ITALIC) ? 1 : RESOLVE_BY_FONT_TABLE);
- }
-
- private boolean addFont(@NonNull String path, int weight, int italic) {
- if (path.startsWith(SYSTEM_FONTS) &&
- !SDK_FONTS.contains(path.substring(SYSTEM_FONTS.length()))) {
- return mValid = false;
- }
- // Set valid to true, even if the font fails to load.
- mValid = true;
- Font font = loadFont(path);
- if (font == null) {
- return false;
- }
- FontInfo fontInfo = new FontInfo();
- fontInfo.mFont = font;
- fontInfo.mWeight = weight;
- fontInfo.mIsItalic = italic == RESOLVE_BY_FONT_TABLE ? font.isItalic() : italic == 1;
- addFont(fontInfo);
- return true;
- }
-
- private boolean addFont(@NonNull FontInfo fontInfo) {
- int weight = fontInfo.mWeight;
- boolean isItalic = fontInfo.mIsItalic;
- // The list is usually just two fonts big. So iterating over all isn't as bad as it looks.
- // It's biggest for roboto where the size is 12.
- //noinspection ForLoopReplaceableByForEach (avoid iterator instantiation)
- for (int i = 0, n = mFonts.size(); i < n; i++) {
- FontInfo font = mFonts.get(i);
- if (font.mWeight == weight && font.mIsItalic == isItalic) {
- return false;
- }
- }
- mFonts.add(fontInfo);
- return true;
- }
-
- /**
- * Compute matching metric between two styles - 0 is an exact match.
- */
- private static int computeMatch(@NonNull FontInfo font1, @NonNull FontInfo font2) {
- int score = Math.abs(font1.mWeight - font2.mWeight);
- if (font1.mIsItalic != font2.mIsItalic) {
- score += 200;
- }
- return score;
- }
-
- /**
- * Try to derive a font from {@code srcFont} for the style in {@code outFont}.
- *
- * {@code outFont} is updated to reflect the style of the derived font.
- * @param srcFont the source font
- * @param outFont contains the desired font style. Updated to contain the derived font and
- * its style
- * @return outFont
- */
- @NonNull
- private FontInfo deriveFont(@NonNull FontInfo srcFont, @NonNull FontInfo outFont) {
- int desiredWeight = outFont.mWeight;
- int srcWeight = srcFont.mWeight;
- assert srcFont.mFont != null;
- Font derivedFont = srcFont.mFont;
- // Embolden the font if required.
- if (desiredWeight >= BOLD_FONT_WEIGHT && desiredWeight - srcWeight > BOLD_FONT_WEIGHT_DELTA / 2) {
- derivedFont = derivedFont.deriveFont(Font.BOLD);
- srcWeight += BOLD_FONT_WEIGHT_DELTA;
- }
- // Italicize the font if required.
- if (outFont.mIsItalic && !srcFont.mIsItalic) {
- derivedFont = derivedFont.deriveFont(Font.ITALIC);
- } else if (outFont.mIsItalic != srcFont.mIsItalic) {
- // The desired font is plain, but the src font is italics. We can't convert it back. So
- // we update the value to reflect the true style of the font we're deriving.
- outFont.mIsItalic = srcFont.mIsItalic;
- }
- outFont.mFont = derivedFont;
- outFont.mWeight = srcWeight;
- // No need to update mIsItalics, as it's already been handled above.
- return outFont;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java
deleted file mode 100644
index 64410e4c6a053..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Gradient_Delegate.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import android.graphics.Shader.TileMode;
-
-/**
- * Base class for true Gradient shader delegate.
- */
-public abstract class Gradient_Delegate extends Shader_Delegate {
-
- protected final int[] mColors;
- protected final float[] mPositions;
-
- @Override
- public boolean isSupported() {
- // all gradient shaders are supported.
- return true;
- }
-
- @Override
- public String getSupportMessage() {
- // all gradient shaders are supported, no need for a gradient support
- return null;
- }
-
- /**
- * Creates the base shader and do some basic test on the parameters.
- *
- * @param nativeMatrix reference to the shader's native transformation matrix
- * @param colors The colors to be distributed along the gradient line
- * @param positions May be null. The relative positions [0..1] of each
- * corresponding color in the colors array. If this is null, the
- * the colors are distributed evenly along the gradient line.
- */
- protected Gradient_Delegate(long nativeMatrix, int colors[], float positions[]) {
- super(nativeMatrix);
- assert colors.length >= 2 : "needs >= 2 number of colors";
-
- if (positions == null) {
- float spacing = 1.f / (colors.length - 1);
- positions = new float[colors.length];
- positions[0] = 0.f;
- positions[colors.length - 1] = 1.f;
- for (int i = 1; i < colors.length - 1; i++) {
- positions[i] = spacing * i;
- }
- } else {
- assert colors.length == positions.length :
- "color and position " + "arrays must be of equal length";
- }
-
- mColors = colors;
- mPositions = positions;
- }
-
- /**
- * Base class for (Java) Gradient Paints. This handles computing the gradient colors based
- * on the color and position lists, as well as the {@link TileMode}
- *
- */
- protected abstract static class GradientPaint implements java.awt.Paint {
- private final static int GRADIENT_SIZE = 100;
-
- private final int[] mColors;
- private final float[] mPositions;
- private final TileMode mTileMode;
- private int[] mGradient;
-
- protected GradientPaint(int[] colors, float[] positions, TileMode tileMode) {
- mColors = colors;
- mPositions = positions;
- mTileMode = tileMode;
- }
-
- @Override
- public int getTransparency() {
- return java.awt.Paint.TRANSLUCENT;
- }
-
- /**
- * Pre-computes the colors for the gradient. This must be called once before any call
- * to {@link #getGradientColor(float)}
- */
- protected void precomputeGradientColors() {
- if (mGradient == null) {
- // actually create an array with an extra size, so that we can really go
- // from 0 to SIZE (100%), or currentPos in the loop below will never equal 1.0
- mGradient = new int[GRADIENT_SIZE+1];
-
- int prevPos = 0;
- int nextPos = 1;
- for (int i = 0 ; i <= GRADIENT_SIZE ; i++) {
- // compute current position
- float currentPos = (float)i/GRADIENT_SIZE;
- while (currentPos > mPositions[nextPos]) {
- prevPos = nextPos++;
- }
-
- float percent = (currentPos - mPositions[prevPos]) /
- (mPositions[nextPos] - mPositions[prevPos]);
-
- mGradient[i] = computeColor(mColors[prevPos], mColors[nextPos], percent);
- }
- }
- }
-
- /**
- * Returns the color based on the position in the gradient.
- * pos can be anything, even < 0 or > > 1, as the gradient
- * will use {@link TileMode} value to convert it into a [0,1] value.
- */
- protected int getGradientColor(float pos) {
- if (pos < 0.f) {
- if (mTileMode != null) {
- switch (mTileMode) {
- case CLAMP:
- pos = 0.f;
- break;
- case REPEAT:
- // remove the integer part to stay in the [0,1] range.
- // we also need to invert the value from [-1,0] to [0, 1]
- pos = pos - (float)Math.floor(pos);
- break;
- case MIRROR:
- // this is the same as the positive side, just make the value positive
- // first.
- pos = Math.abs(pos);
-
- // get the integer and the decimal part
- int intPart = (int)Math.floor(pos);
- pos = pos - intPart;
- // 0 -> 1 : normal order
- // 1 -> 2: mirrored
- // etc..
- // this means if the intpart is odd we invert
- if ((intPart % 2) == 1) {
- pos = 1.f - pos;
- }
- break;
- }
- } else {
- pos = 0.0f;
- }
- } else if (pos > 1f) {
- if (mTileMode != null) {
- switch (mTileMode) {
- case CLAMP:
- pos = 1.f;
- break;
- case REPEAT:
- // remove the integer part to stay in the [0,1] range
- pos = pos - (float)Math.floor(pos);
- break;
- case MIRROR:
- // get the integer and the decimal part
- int intPart = (int)Math.floor(pos);
- pos = pos - intPart;
- // 0 -> 1 : normal order
- // 1 -> 2: mirrored
- // etc..
- // this means if the intpart is odd we invert
- if ((intPart % 2) == 1) {
- pos = 1.f - pos;
- }
- break;
- }
- } else {
- pos = 1.0f;
- }
- }
-
- int index = (int)((pos * GRADIENT_SIZE) + .5);
-
- return mGradient[index];
- }
-
- /**
- * Returns the color between c1, and c2, based on the percent of the distance
- * between c1 and c2.
- */
- private int computeColor(int c1, int c2, float percent) {
- int a = computeChannel((c1 >> 24) & 0xFF, (c2 >> 24) & 0xFF, percent);
- int r = computeChannel((c1 >> 16) & 0xFF, (c2 >> 16) & 0xFF, percent);
- int g = computeChannel((c1 >> 8) & 0xFF, (c2 >> 8) & 0xFF, percent);
- int b = computeChannel((c1 ) & 0xFF, (c2 ) & 0xFF, percent);
- return a << 24 | r << 16 | g << 8 | b;
- }
-
- /**
- * Returns the channel value between 2 values based on the percent of the distance between
- * the 2 values..
- */
- private int computeChannel(int c1, int c2, float percent) {
- return c1 + (int)((percent * (c2-c1)) + .5);
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java
deleted file mode 100644
index 0dd9703503139..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/LightingColorFilter_Delegate.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.LightingColorFilter
- *
- * Through the layoutlib_create tool, the original native methods of LightingColorFilter have
- * been replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original LightingColorFilter class.
- *
- * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the Shader classes will be added to the manager
- * owned by {@link ColorFilter_Delegate}.
- *
- * @see ColorFilter_Delegate
- *
- */
-public class LightingColorFilter_Delegate extends ColorFilter_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public String getSupportMessage() {
- return "Lighting Color Filters are not supported.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long native_CreateLightingFilter(int mul, int add) {
- LightingColorFilter_Delegate newDelegate = new LightingColorFilter_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java
deleted file mode 100644
index cd4393abdf855..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/LinearGradient_Delegate.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Shader.TileMode;
-
-import java.awt.image.ColorModel;
-
-/**
- * Delegate implementing the native methods of android.graphics.LinearGradient
- *
- * Through the layoutlib_create tool, the original native methods of LinearGradient have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original LinearGradient class.
- *
- * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
- *
- * @see Shader_Delegate
- *
- */
-public final class LinearGradient_Delegate extends Gradient_Delegate {
-
- // ---- delegate data ----
- private java.awt.Paint mJavaPaint;
-
- // ---- Public Helper methods ----
-
- @Override
- public java.awt.Paint getJavaPaint() {
- return mJavaPaint;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate1(LinearGradient thisGradient, long matrix,
- float x0, float y0, float x1, float y1,
- int colors[], float positions[], int tileMode) {
- LinearGradient_Delegate newDelegate = new LinearGradient_Delegate(matrix, x0, y0,
- x1, y1, colors, positions, Shader_Delegate.getTileMode(tileMode));
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate2(LinearGradient thisGradient, long matrix,
- float x0, float y0, float x1, float y1,
- int color0, int color1, int tileMode) {
- return nativeCreate1(thisGradient, matrix, x0, y0, x1, y1, new int[] { color0, color1},
- null /*positions*/, tileMode);
- }
-
- // ---- Private delegate/helper methods ----
-
- /**
- * Create a shader that draws a linear gradient along a line.
- *
- * @param nativeMatrix reference to the shader's native transformation matrix
- * @param x0 The x-coordinate for the start of the gradient line
- * @param y0 The y-coordinate for the start of the gradient line
- * @param x1 The x-coordinate for the end of the gradient line
- * @param y1 The y-coordinate for the end of the gradient line
- * @param colors The colors to be distributed along the gradient line
- * @param positions May be null. The relative positions [0..1] of each
- * corresponding color in the colors array. If this is null, the
- * the colors are distributed evenly along the gradient line.
- * @param tile The Shader tiling mode
- */
- private LinearGradient_Delegate(long nativeMatrix, float x0, float y0, float x1,
- float y1, int colors[], float positions[], TileMode tile) {
- super(nativeMatrix, colors, positions);
- mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
- }
-
- // ---- Custom Java Paint ----
- /**
- * Linear Gradient (Java) Paint able to handle more than 2 points, as
- * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
- * modes.
- */
- private class LinearGradientPaint extends GradientPaint {
-
- private final float mX0;
- private final float mY0;
- private final float mDx;
- private final float mDy;
- private final float mDSize2;
-
- public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
- float positions[], TileMode tile) {
- super(colors, positions, tile);
- mX0 = x0;
- mY0 = y0;
- mDx = x1 - x0;
- mDy = y1 - y0;
- mDSize2 = mDx * mDx + mDy * mDy;
- }
-
- @Override
- public java.awt.PaintContext createContext(
- java.awt.image.ColorModel colorModel,
- java.awt.Rectangle deviceBounds,
- java.awt.geom.Rectangle2D userBounds,
- java.awt.geom.AffineTransform xform,
- java.awt.RenderingHints hints) {
- precomputeGradientColors();
-
- java.awt.geom.AffineTransform canvasMatrix;
- try {
- canvasMatrix = xform.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in LinearGradient", e, null /*data*/);
- canvasMatrix = new java.awt.geom.AffineTransform();
- }
-
- java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
- try {
- localMatrix = localMatrix.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in LinearGradient", e, null /*data*/);
- localMatrix = new java.awt.geom.AffineTransform();
- }
-
- return new LinearGradientPaintContext(canvasMatrix, localMatrix, colorModel);
- }
-
- private class LinearGradientPaintContext implements java.awt.PaintContext {
-
- private final java.awt.geom.AffineTransform mCanvasMatrix;
- private final java.awt.geom.AffineTransform mLocalMatrix;
- private final java.awt.image.ColorModel mColorModel;
-
- private LinearGradientPaintContext(
- java.awt.geom.AffineTransform canvasMatrix,
- java.awt.geom.AffineTransform localMatrix,
- java.awt.image.ColorModel colorModel) {
- mCanvasMatrix = canvasMatrix;
- mLocalMatrix = localMatrix;
- mColorModel = colorModel.hasAlpha() ? colorModel : ColorModel.getRGBdefault();
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public java.awt.image.ColorModel getColorModel() {
- return mColorModel;
- }
-
- @Override
- public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
- java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
- mColorModel, mColorModel.createCompatibleWritableRaster(w, h),
- mColorModel.isAlphaPremultiplied(), null);
-
- int[] data = new int[w*h];
-
- int index = 0;
- float[] pt1 = new float[2];
- float[] pt2 = new float[2];
- for (int iy = 0 ; iy < h ; iy++) {
- for (int ix = 0 ; ix < w ; ix++) {
- // handle the canvas transform
- pt1[0] = x + ix;
- pt1[1] = y + iy;
- mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
-
- // handle the local matrix.
- pt1[0] = pt2[0];
- pt1[1] = pt2[1];
- mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
-
- data[index++] = getColor(pt2[0], pt2[1]);
- }
- }
-
- image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
- return image.getRaster();
- }
- }
-
- /**
- * Returns a color for an arbitrary point.
- */
- private int getColor(float x, float y) {
- float pos;
- if (mDx == 0) {
- pos = (y - mY0) / mDy;
- } else if (mDy == 0) {
- pos = (x - mX0) / mDx;
- } else {
- // find the x position on the gradient vector.
- float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
- // from it get the position relative to the vector
- pos = (_x - mX0) / mDx;
- }
-
- return getGradientColor(pos);
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java
deleted file mode 100644
index e726c5982be29..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/MaskFilter_Delegate.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.MaskFilter
- *
- * Through the layoutlib_create tool, the original native methods of MaskFilter have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original MaskFilter class.
- *
- * This also serve as a base class for all MaskFilter delegate classes.
- *
- * @see DelegateManager
- *
- */
-public abstract class MaskFilter_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(MaskFilter_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- public static MaskFilter_Delegate getDelegate(long nativeShader) {
- return sManager.getDelegate(nativeShader);
- }
-
- public abstract boolean isSupported();
- public abstract String getSupportMessage();
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nativeDestructor(long native_filter) {
- sManager.removeJavaReferenceFor(native_filter);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
deleted file mode 100644
index 354f9191bedac..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
+++ /dev/null
@@ -1,1077 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Matrix.ScaleToFit;
-
-import java.awt.geom.AffineTransform;
-import java.awt.geom.NoninvertibleTransformException;
-
-import libcore.util.NativeAllocationRegistry_Delegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.Matrix
- *
- * Through the layoutlib_create tool, the original native methods of Matrix have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Matrix class.
- *
- * @see DelegateManager
- *
- */
-public final class Matrix_Delegate {
-
- private final static int MATRIX_SIZE = 9;
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(Matrix_Delegate.class);
- private static long sFinalizer = -1;
-
- // ---- delegate data ----
- private float mValues[] = new float[MATRIX_SIZE];
-
- // ---- Public Helper methods ----
-
- public static Matrix_Delegate getDelegate(long native_instance) {
- return sManager.getDelegate(native_instance);
- }
-
- /**
- * Returns an {@link AffineTransform} matching the given Matrix.
- */
- public static AffineTransform getAffineTransform(Matrix m) {
- Matrix_Delegate delegate = sManager.getDelegate(m.native_instance);
- if (delegate == null) {
- return null;
- }
-
- return delegate.getAffineTransform();
- }
-
- public static boolean hasPerspective(Matrix m) {
- Matrix_Delegate delegate = sManager.getDelegate(m.native_instance);
- if (delegate == null) {
- return false;
- }
-
- return delegate.hasPerspective();
- }
-
- /**
- * Sets the content of the matrix with the content of another matrix.
- */
- public void set(Matrix_Delegate matrix) {
- System.arraycopy(matrix.mValues, 0, mValues, 0, MATRIX_SIZE);
- }
-
- /**
- * Sets the content of the matrix with the content of another matrix represented as an array
- * of values.
- */
- public void set(float[] values) {
- System.arraycopy(values, 0, mValues, 0, MATRIX_SIZE);
- }
-
- /**
- * Resets the matrix to be the identity matrix.
- */
- public void reset() {
- reset(mValues);
- }
-
- /**
- * Returns whether or not the matrix is identity.
- */
- public boolean isIdentity() {
- for (int i = 0, k = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++, k++) {
- if (mValues[k] != ((i==j) ? 1 : 0)) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- public static float[] makeValues(AffineTransform matrix) {
- float[] values = new float[MATRIX_SIZE];
- values[0] = (float) matrix.getScaleX();
- values[1] = (float) matrix.getShearX();
- values[2] = (float) matrix.getTranslateX();
- values[3] = (float) matrix.getShearY();
- values[4] = (float) matrix.getScaleY();
- values[5] = (float) matrix.getTranslateY();
- values[6] = 0.f;
- values[7] = 0.f;
- values[8] = 1.f;
-
- return values;
- }
-
- public static Matrix_Delegate make(AffineTransform matrix) {
- return new Matrix_Delegate(makeValues(matrix));
- }
-
- public boolean mapRect(RectF dst, RectF src) {
- // array with 4 corners
- float[] corners = new float[] {
- src.left, src.top,
- src.right, src.top,
- src.right, src.bottom,
- src.left, src.bottom,
- };
-
- // apply the transform to them.
- mapPoints(corners);
-
- // now put the result in the rect. We take the min/max of Xs and min/max of Ys
- dst.left = Math.min(Math.min(corners[0], corners[2]), Math.min(corners[4], corners[6]));
- dst.right = Math.max(Math.max(corners[0], corners[2]), Math.max(corners[4], corners[6]));
-
- dst.top = Math.min(Math.min(corners[1], corners[3]), Math.min(corners[5], corners[7]));
- dst.bottom = Math.max(Math.max(corners[1], corners[3]), Math.max(corners[5], corners[7]));
-
-
- return (computeTypeMask() & kRectStaysRect_Mask) != 0;
- }
-
-
- /**
- * Returns an {@link AffineTransform} matching the matrix.
- */
- public AffineTransform getAffineTransform() {
- return getAffineTransform(mValues);
- }
-
- public boolean hasPerspective() {
- return (mValues[6] != 0 || mValues[7] != 0 || mValues[8] != 1);
- }
-
-
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nCreate(long native_src_or_zero) {
- // create the delegate
- Matrix_Delegate newDelegate = new Matrix_Delegate();
-
- // copy from values if needed.
- if (native_src_or_zero > 0) {
- Matrix_Delegate oldDelegate = sManager.getDelegate(native_src_or_zero);
- if (oldDelegate != null) {
- System.arraycopy(
- oldDelegate.mValues, 0,
- newDelegate.mValues, 0,
- MATRIX_SIZE);
- }
- }
-
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsIdentity(long native_object) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return false;
- }
-
- return d.isIdentity();
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsAffine(long native_object) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return true;
- }
-
- return (d.computeTypeMask() & kPerspective_Mask) == 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nRectStaysRect(long native_object) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return true;
- }
-
- return (d.computeTypeMask() & kRectStaysRect_Mask) != 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nReset(long native_object) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- reset(d.mValues);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSet(long native_object, long other) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- Matrix_Delegate src = sManager.getDelegate(other);
- if (src == null) {
- return;
- }
-
- System.arraycopy(src.mValues, 0, d.mValues, 0, MATRIX_SIZE);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTranslate(long native_object, float dx, float dy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- setTranslate(d.mValues, dx, dy);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetScale(long native_object, float sx, float sy,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- d.mValues = getScale(sx, sy, px, py);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetScale(long native_object, float sx, float sy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- d.mValues[0] = sx;
- d.mValues[1] = 0;
- d.mValues[2] = 0;
- d.mValues[3] = 0;
- d.mValues[4] = sy;
- d.mValues[5] = 0;
- d.mValues[6] = 0;
- d.mValues[7] = 0;
- d.mValues[8] = 1;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetRotate(long native_object, float degrees, float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- d.mValues = getRotate(degrees, px, py);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetRotate(long native_object, float degrees) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- setRotate(d.mValues, degrees);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetSinCos(long native_object, float sinValue, float cosValue,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- // TODO: do it in one pass
-
- // translate so that the pivot is in 0,0
- setTranslate(d.mValues, -px, -py);
-
- // scale
- d.postTransform(getRotate(sinValue, cosValue));
- // translate back the pivot
- d.postTransform(getTranslate(px, py));
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetSinCos(long native_object, float sinValue, float cosValue) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- setRotate(d.mValues, sinValue, cosValue);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetSkew(long native_object, float kx, float ky,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- d.mValues = getSkew(kx, ky, px, py);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetSkew(long native_object, float kx, float ky) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- d.mValues[0] = 1;
- d.mValues[1] = kx;
- d.mValues[2] = -0;
- d.mValues[3] = ky;
- d.mValues[4] = 1;
- d.mValues[5] = 0;
- d.mValues[6] = 0;
- d.mValues[7] = 0;
- d.mValues[8] = 1;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetConcat(long native_object, long a, long b) {
- if (a == native_object) {
- nPreConcat(native_object, b);
- return;
- } else if (b == native_object) {
- nPostConcat(native_object, a);
- return;
- }
-
- Matrix_Delegate d = sManager.getDelegate(native_object);
- Matrix_Delegate a_mtx = sManager.getDelegate(a);
- Matrix_Delegate b_mtx = sManager.getDelegate(b);
- if (d != null && a_mtx != null && b_mtx != null) {
- multiply(d.mValues, a_mtx.mValues, b_mtx.mValues);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreTranslate(long native_object, float dx, float dy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getTranslate(dx, dy));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreScale(long native_object, float sx, float sy,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getScale(sx, sy, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreScale(long native_object, float sx, float sy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getScale(sx, sy));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreRotate(long native_object, float degrees,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getRotate(degrees, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreRotate(long native_object, float degrees) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
-
- double rad = Math.toRadians(degrees);
- float sin = (float) Math.sin(rad);
- float cos = (float) Math.cos(rad);
-
- d.preTransform(getRotate(sin, cos));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreSkew(long native_object, float kx, float ky,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getSkew(kx, ky, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreSkew(long native_object, float kx, float ky) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.preTransform(getSkew(kx, ky));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPreConcat(long native_object, long other_matrix) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- Matrix_Delegate other = sManager.getDelegate(other_matrix);
- if (d != null && other != null) {
- d.preTransform(other.mValues);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostTranslate(long native_object, float dx, float dy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getTranslate(dx, dy));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostScale(long native_object, float sx, float sy,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getScale(sx, sy, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostScale(long native_object, float sx, float sy) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getScale(sx, sy));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostRotate(long native_object, float degrees,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getRotate(degrees, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostRotate(long native_object, float degrees) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getRotate(degrees));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostSkew(long native_object, float kx, float ky,
- float px, float py) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getSkew(kx, ky, px, py));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostSkew(long native_object, float kx, float ky) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d != null) {
- d.postTransform(getSkew(kx, ky));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nPostConcat(long native_object, long other_matrix) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- Matrix_Delegate other = sManager.getDelegate(other_matrix);
- if (d != null && other != null) {
- d.postTransform(other.mValues);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nSetRectToRect(long native_object, RectF src,
- RectF dst, int stf) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return false;
- }
-
- if (src.isEmpty()) {
- reset(d.mValues);
- return false;
- }
-
- if (dst.isEmpty()) {
- d.mValues[0] = d.mValues[1] = d.mValues[2] = d.mValues[3] = d.mValues[4] = d.mValues[5]
- = d.mValues[6] = d.mValues[7] = 0;
- d.mValues[8] = 1;
- } else {
- float tx, sx = dst.width() / src.width();
- float ty, sy = dst.height() / src.height();
- boolean xLarger = false;
-
- if (stf != ScaleToFit.FILL.nativeInt) {
- if (sx > sy) {
- xLarger = true;
- sx = sy;
- } else {
- sy = sx;
- }
- }
-
- tx = dst.left - src.left * sx;
- ty = dst.top - src.top * sy;
- if (stf == ScaleToFit.CENTER.nativeInt || stf == ScaleToFit.END.nativeInt) {
- float diff;
-
- if (xLarger) {
- diff = dst.width() - src.width() * sy;
- } else {
- diff = dst.height() - src.height() * sy;
- }
-
- if (stf == ScaleToFit.CENTER.nativeInt) {
- diff = diff / 2;
- }
-
- if (xLarger) {
- tx += diff;
- } else {
- ty += diff;
- }
- }
-
- d.mValues[0] = sx;
- d.mValues[4] = sy;
- d.mValues[2] = tx;
- d.mValues[5] = ty;
- d.mValues[1] = d.mValues[3] = d.mValues[6] = d.mValues[7] = 0;
-
- }
- // shared cleanup
- d.mValues[8] = 1;
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nSetPolyToPoly(long native_object, float[] src, int srcIndex,
- float[] dst, int dstIndex, int pointCount) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Matrix.setPolyToPoly is not supported.",
- null, null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nInvert(long native_object, long inverse) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return false;
- }
-
- Matrix_Delegate inv_mtx = sManager.getDelegate(inverse);
- if (inv_mtx == null) {
- return false;
- }
-
- try {
- AffineTransform affineTransform = d.getAffineTransform();
- AffineTransform inverseTransform = affineTransform.createInverse();
- inv_mtx.mValues[0] = (float)inverseTransform.getScaleX();
- inv_mtx.mValues[1] = (float)inverseTransform.getShearX();
- inv_mtx.mValues[2] = (float)inverseTransform.getTranslateX();
- inv_mtx.mValues[3] = (float)inverseTransform.getScaleX();
- inv_mtx.mValues[4] = (float)inverseTransform.getShearY();
- inv_mtx.mValues[5] = (float)inverseTransform.getTranslateY();
-
- return true;
- } catch (NoninvertibleTransformException e) {
- return false;
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void nMapPoints(long native_object, float[] dst, int dstIndex,
- float[] src, int srcIndex, int ptCount, boolean isPts) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- if (isPts) {
- d.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
- } else {
- d.mapVectors(dst, dstIndex, src, srcIndex, ptCount);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nMapRect(long native_object, RectF dst, RectF src) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return false;
- }
-
- return d.mapRect(dst, src);
- }
-
- @LayoutlibDelegate
- /*package*/ static float nMapRadius(long native_object, float radius) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return 0.f;
- }
-
- float[] src = new float[] { radius, 0.f, 0.f, radius };
- d.mapVectors(src, 0, src, 0, 2);
-
- float l1 = (float) Math.hypot(src[0], src[1]);
- float l2 = (float) Math.hypot(src[2], src[3]);
- return (float) Math.sqrt(l1 * l2);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nGetValues(long native_object, float[] values) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- System.arraycopy(d.mValues, 0, values, 0, MATRIX_SIZE);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetValues(long native_object, float[] values) {
- Matrix_Delegate d = sManager.getDelegate(native_object);
- if (d == null) {
- return;
- }
-
- System.arraycopy(values, 0, d.mValues, 0, MATRIX_SIZE);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nEquals(long native_a, long native_b) {
- Matrix_Delegate a = sManager.getDelegate(native_a);
- if (a == null) {
- return false;
- }
-
- Matrix_Delegate b = sManager.getDelegate(native_b);
- if (b == null) {
- return false;
- }
-
- for (int i = 0 ; i < MATRIX_SIZE ; i++) {
- if (a.mValues[i] != b.mValues[i]) {
- return false;
- }
- }
-
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetNativeFinalizer() {
- synchronized (Matrix_Delegate.class) {
- if (sFinalizer == -1) {
- sFinalizer = NativeAllocationRegistry_Delegate.createFinalizer(sManager::removeJavaReferenceFor);
- }
- }
- return sFinalizer;
- }
-
- // ---- Private helper methods ----
-
- /*package*/ static AffineTransform getAffineTransform(float[] matrix) {
- // the AffineTransform constructor takes the value in a different order
- // for a matrix [ 0 1 2 ]
- // [ 3 4 5 ]
- // the order is 0, 3, 1, 4, 2, 5...
- return new AffineTransform(
- matrix[0], matrix[3], matrix[1],
- matrix[4], matrix[2], matrix[5]);
- }
-
- /**
- * Reset a matrix to the identity
- */
- private static void reset(float[] mtx) {
- for (int i = 0, k = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++, k++) {
- mtx[k] = ((i==j) ? 1 : 0);
- }
- }
- }
-
- @SuppressWarnings("unused")
- private final static int kIdentity_Mask = 0;
- private final static int kTranslate_Mask = 0x01; //!< set if the matrix has translation
- private final static int kScale_Mask = 0x02; //!< set if the matrix has X or Y scale
- private final static int kAffine_Mask = 0x04; //!< set if the matrix skews or rotates
- private final static int kPerspective_Mask = 0x08; //!< set if the matrix is in perspective
- private final static int kRectStaysRect_Mask = 0x10;
- @SuppressWarnings("unused")
- private final static int kUnknown_Mask = 0x80;
-
- @SuppressWarnings("unused")
- private final static int kAllMasks = kTranslate_Mask |
- kScale_Mask |
- kAffine_Mask |
- kPerspective_Mask |
- kRectStaysRect_Mask;
-
- // these guys align with the masks, so we can compute a mask from a variable 0/1
- @SuppressWarnings("unused")
- private final static int kTranslate_Shift = 0;
- @SuppressWarnings("unused")
- private final static int kScale_Shift = 1;
- @SuppressWarnings("unused")
- private final static int kAffine_Shift = 2;
- @SuppressWarnings("unused")
- private final static int kPerspective_Shift = 3;
- private final static int kRectStaysRect_Shift = 4;
-
- private int computeTypeMask() {
- int mask = 0;
-
- if (mValues[6] != 0. || mValues[7] != 0. || mValues[8] != 1.) {
- mask |= kPerspective_Mask;
- }
-
- if (mValues[2] != 0. || mValues[5] != 0.) {
- mask |= kTranslate_Mask;
- }
-
- float m00 = mValues[0];
- float m01 = mValues[1];
- float m10 = mValues[3];
- float m11 = mValues[4];
-
- if (m01 != 0. || m10 != 0.) {
- mask |= kAffine_Mask;
- }
-
- if (m00 != 1. || m11 != 1.) {
- mask |= kScale_Mask;
- }
-
- if ((mask & kPerspective_Mask) == 0) {
- // map non-zero to 1
- int im00 = m00 != 0 ? 1 : 0;
- int im01 = m01 != 0 ? 1 : 0;
- int im10 = m10 != 0 ? 1 : 0;
- int im11 = m11 != 0 ? 1 : 0;
-
- // record if the (p)rimary and (s)econdary diagonals are all 0 or
- // all non-zero (answer is 0 or 1)
- int dp0 = (im00 | im11) ^ 1; // true if both are 0
- int dp1 = im00 & im11; // true if both are 1
- int ds0 = (im01 | im10) ^ 1; // true if both are 0
- int ds1 = im01 & im10; // true if both are 1
-
- // return 1 if primary is 1 and secondary is 0 or
- // primary is 0 and secondary is 1
- mask |= ((dp0 & ds1) | (dp1 & ds0)) << kRectStaysRect_Shift;
- }
-
- return mask;
- }
-
- private Matrix_Delegate() {
- reset();
- }
-
- private Matrix_Delegate(float[] values) {
- System.arraycopy(values, 0, mValues, 0, MATRIX_SIZE);
- }
-
- /**
- * Adds the given transformation to the current Matrix
- * This in effect does this = this*matrix
- * @param matrix
- */
- private void postTransform(float[] matrix) {
- float[] tmp = new float[9];
- multiply(tmp, mValues, matrix);
- mValues = tmp;
- }
-
- /**
- * Adds the given transformation to the current Matrix
- * This in effect does this = matrix*this
- * @param matrix
- */
- private void preTransform(float[] matrix) {
- float[] tmp = new float[9];
- multiply(tmp, matrix, mValues);
- mValues = tmp;
- }
-
- /**
- * Apply this matrix to the array of 2D points specified by src, and write
- * the transformed points into the array of points specified by dst. The
- * two arrays represent their "points" as pairs of floats [x, y].
- *
- * @param dst The array of dst points (x,y pairs)
- * @param dstIndex The index of the first [x,y] pair of dst floats
- * @param src The array of src points (x,y pairs)
- * @param srcIndex The index of the first [x,y] pair of src floats
- * @param pointCount The number of points (x,y pairs) to transform
- */
-
- private void mapPoints(float[] dst, int dstIndex, float[] src, int srcIndex,
- int pointCount) {
- final int count = pointCount * 2;
-
- float[] tmpDest = dst;
- boolean inPlace = dst == src;
- if (inPlace) {
- tmpDest = new float[dstIndex + count];
- }
-
- for (int i = 0 ; i < count ; i += 2) {
- // just in case we are doing in place, we better put this in temp vars
- float x = mValues[0] * src[i + srcIndex] +
- mValues[1] * src[i + srcIndex + 1] +
- mValues[2];
- float y = mValues[3] * src[i + srcIndex] +
- mValues[4] * src[i + srcIndex + 1] +
- mValues[5];
-
- tmpDest[i + dstIndex] = x;
- tmpDest[i + dstIndex + 1] = y;
- }
-
- if (inPlace) {
- System.arraycopy(tmpDest, dstIndex, dst, dstIndex, count);
- }
- }
-
- /**
- * Apply this matrix to the array of 2D points, and write the transformed
- * points back into the array
- *
- * @param pts The array [x0, y0, x1, y1, ...] of points to transform.
- */
-
- private void mapPoints(float[] pts) {
- mapPoints(pts, 0, pts, 0, pts.length >> 1);
- }
-
- private void mapVectors(float[] dst, int dstIndex, float[] src, int srcIndex, int ptCount) {
- if (hasPerspective()) {
- // transform the (0,0) point
- float[] origin = new float[] { 0.f, 0.f};
- mapPoints(origin);
-
- // translate the vector data as points
- mapPoints(dst, dstIndex, src, srcIndex, ptCount);
-
- // then substract the transformed origin.
- final int count = ptCount * 2;
- for (int i = 0 ; i < count ; i += 2) {
- dst[dstIndex + i] = dst[dstIndex + i] - origin[0];
- dst[dstIndex + i + 1] = dst[dstIndex + i + 1] - origin[1];
- }
- } else {
- // make a copy of the matrix
- Matrix_Delegate copy = new Matrix_Delegate(mValues);
-
- // remove the translation
- setTranslate(copy.mValues, 0, 0);
-
- // map the content as points.
- copy.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
- }
- }
-
- /**
- * multiply two matrices and store them in a 3rd.
- * This in effect does dest = a*b
- * dest cannot be the same as a or b.
- */
- /*package*/ static void multiply(float dest[], float[] a, float[] b) {
- // first row
- dest[0] = b[0] * a[0] + b[1] * a[3] + b[2] * a[6];
- dest[1] = b[0] * a[1] + b[1] * a[4] + b[2] * a[7];
- dest[2] = b[0] * a[2] + b[1] * a[5] + b[2] * a[8];
-
- // 2nd row
- dest[3] = b[3] * a[0] + b[4] * a[3] + b[5] * a[6];
- dest[4] = b[3] * a[1] + b[4] * a[4] + b[5] * a[7];
- dest[5] = b[3] * a[2] + b[4] * a[5] + b[5] * a[8];
-
- // 3rd row
- dest[6] = b[6] * a[0] + b[7] * a[3] + b[8] * a[6];
- dest[7] = b[6] * a[1] + b[7] * a[4] + b[8] * a[7];
- dest[8] = b[6] * a[2] + b[7] * a[5] + b[8] * a[8];
- }
-
- /**
- * Returns a matrix that represents a given translate
- * @param dx
- * @param dy
- * @return
- */
- /*package*/ static float[] getTranslate(float dx, float dy) {
- return setTranslate(new float[9], dx, dy);
- }
-
- /*package*/ static float[] setTranslate(float[] dest, float dx, float dy) {
- dest[0] = 1;
- dest[1] = 0;
- dest[2] = dx;
- dest[3] = 0;
- dest[4] = 1;
- dest[5] = dy;
- dest[6] = 0;
- dest[7] = 0;
- dest[8] = 1;
- return dest;
- }
-
- /*package*/ static float[] getScale(float sx, float sy) {
- return new float[] { sx, 0, 0, 0, sy, 0, 0, 0, 1 };
- }
-
- /**
- * Returns a matrix that represents the given scale info.
- * @param sx
- * @param sy
- * @param px
- * @param py
- */
- /*package*/ static float[] getScale(float sx, float sy, float px, float py) {
- float[] tmp = new float[9];
- float[] tmp2 = new float[9];
-
- // TODO: do it in one pass
-
- // translate tmp so that the pivot is in 0,0
- setTranslate(tmp, -px, -py);
-
- // scale into tmp2
- multiply(tmp2, tmp, getScale(sx, sy));
-
- // translate back the pivot back into tmp
- multiply(tmp, tmp2, getTranslate(px, py));
-
- return tmp;
- }
-
-
- /*package*/ static float[] getRotate(float degrees) {
- double rad = Math.toRadians(degrees);
- float sin = (float)Math.sin(rad);
- float cos = (float)Math.cos(rad);
-
- return getRotate(sin, cos);
- }
-
- /*package*/ static float[] getRotate(float sin, float cos) {
- return setRotate(new float[9], sin, cos);
- }
-
- /*package*/ static float[] setRotate(float[] dest, float degrees) {
- double rad = Math.toRadians(degrees);
- float sin = (float)Math.sin(rad);
- float cos = (float)Math.cos(rad);
-
- return setRotate(dest, sin, cos);
- }
-
- /*package*/ static float[] setRotate(float[] dest, float sin, float cos) {
- dest[0] = cos;
- dest[1] = -sin;
- dest[2] = 0;
- dest[3] = sin;
- dest[4] = cos;
- dest[5] = 0;
- dest[6] = 0;
- dest[7] = 0;
- dest[8] = 1;
- return dest;
- }
-
- /*package*/ static float[] getRotate(float degrees, float px, float py) {
- float[] tmp = new float[9];
- float[] tmp2 = new float[9];
-
- // TODO: do it in one pass
-
- // translate so that the pivot is in 0,0
- setTranslate(tmp, -px, -py);
-
- // rotate into tmp2
- double rad = Math.toRadians(degrees);
- float cos = (float)Math.cos(rad);
- float sin = (float)Math.sin(rad);
- multiply(tmp2, tmp, getRotate(sin, cos));
-
- // translate back the pivot back into tmp
- multiply(tmp, tmp2, getTranslate(px, py));
-
- return tmp;
- }
-
- /*package*/ static float[] getSkew(float kx, float ky) {
- return new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 };
- }
-
- /*package*/ static float[] getSkew(float kx, float ky, float px, float py) {
- float[] tmp = new float[9];
- float[] tmp2 = new float[9];
-
- // TODO: do it in one pass
-
- // translate so that the pivot is in 0,0
- setTranslate(tmp, -px, -py);
-
- // skew into tmp2
- multiply(tmp2, tmp, new float[] { 1, kx, 0, ky, 1, 0, 0, 0, 1 });
- // translate back the pivot back into tmp
- multiply(tmp, tmp2, getTranslate(px, py));
-
- return tmp;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
deleted file mode 100644
index 1f0eb3bab55b1..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.impl.GcSnapshot;
-import com.android.ninepatch.NinePatchChunk;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.drawable.NinePatchDrawable;
-
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.lang.ref.SoftReference;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Delegate implementing the native methods of android.graphics.NinePatch
- *
- * Through the layoutlib_create tool, the original native methods of NinePatch have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
- * around to map int to instance of the delegate.
- *
- */
-public final class NinePatch_Delegate {
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(NinePatch_Delegate.class);
-
- // ---- delegate helper data ----
- /**
- * Cache map for {@link NinePatchChunk}.
- * When the chunks are created they are serialized into a byte[], and both are put
- * in the cache, using a {@link SoftReference} for the chunk. The default Java classes
- * for {@link NinePatch} and {@link NinePatchDrawable} only reference to the byte[] data, and
- * provide this for drawing.
- * Using the cache map allows us to not have to deserialize the byte[] back into a
- * {@link NinePatchChunk} every time a rendering is done.
- */
- private final static Map> sChunkCache =
- new HashMap>();
-
- // ---- delegate data ----
- private byte[] chunk;
-
-
- // ---- Public Helper methods ----
-
- /**
- * Serializes the given chunk.
- *
- * @return the serialized data for the chunk.
- */
- public static byte[] serialize(NinePatchChunk chunk) {
- // serialize the chunk to get a byte[]
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = null;
- try {
- oos = new ObjectOutputStream(baos);
- oos.writeObject(chunk);
- } catch (IOException e) {
- Bridge.getLog().error(null, "Failed to serialize NinePatchChunk.", e, null /*data*/);
- return null;
- } finally {
- if (oos != null) {
- try {
- oos.close();
- } catch (IOException ignored) {
- }
- }
- }
-
- // get the array and add it to the cache
- byte[] array = baos.toByteArray();
- sChunkCache.put(array, new SoftReference(chunk));
- return array;
- }
-
- /**
- * Returns a {@link NinePatchChunk} object for the given serialized representation.
- *
- * If the chunk is present in the cache then the object from the cache is returned, otherwise
- * the array is deserialized into a {@link NinePatchChunk} object.
- *
- * @param array the serialized representation of the chunk.
- * @return the NinePatchChunk or null if deserialization failed.
- */
- public static NinePatchChunk getChunk(byte[] array) {
- SoftReference chunkRef = sChunkCache.get(array);
- NinePatchChunk chunk = chunkRef.get();
- if (chunk == null) {
- ByteArrayInputStream bais = new ByteArrayInputStream(array);
- ObjectInputStream ois = null;
- try {
- ois = new ObjectInputStream(bais);
- chunk = (NinePatchChunk) ois.readObject();
-
- // put back the chunk in the cache
- if (chunk != null) {
- sChunkCache.put(array, new SoftReference(chunk));
- }
- } catch (IOException e) {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Failed to deserialize NinePatchChunk content.", e, null /*data*/);
- return null;
- } catch (ClassNotFoundException e) {
- Bridge.getLog().error(LayoutLog.TAG_BROKEN,
- "Failed to deserialize NinePatchChunk class.", e, null /*data*/);
- return null;
- } finally {
- if (ois != null) {
- try {
- ois.close();
- } catch (IOException ignored) {
- }
- }
- }
- }
-
- return chunk;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static boolean isNinePatchChunk(byte[] chunk) {
- NinePatchChunk chunkObject = getChunk(chunk);
- return chunkObject != null;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static long validateNinePatchChunk(byte[] chunk) {
- // the default JNI implementation only checks that the byte[] has the same
- // size as the C struct it represent. Since we cannot do the same check (serialization
- // will return different size depending on content), we do nothing.
- NinePatch_Delegate newDelegate = new NinePatch_Delegate();
- newDelegate.chunk = chunk;
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeFinalize(long chunk) {
- sManager.removeJavaReferenceFor(chunk);
- }
-
-
- @LayoutlibDelegate
- /*package*/ static long nativeGetTransparentRegion(Bitmap bitmap, long chunk, Rect location) {
- return 0;
- }
-
- static byte[] getChunk(long nativeNinePatch) {
- NinePatch_Delegate delegate = sManager.getDelegate(nativeNinePatch);
- if (delegate != null) {
- return delegate.chunk;
- }
- return null;
- }
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java
deleted file mode 100644
index fa20746e4495b..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/PaintFlagsDrawFilter_Delegate.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.PaintFlagsDrawFilter
- *
- * Through the layoutlib_create tool, the original native methods of PaintFlagsDrawFilter have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original PaintFlagsDrawFilter class.
- *
- * Because this extends {@link DrawFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the DrawFilter classes will be added to the manager owned by
- * {@link DrawFilter_Delegate}.
- *
- * @see DrawFilter_Delegate
- *
- */
-public class PaintFlagsDrawFilter_Delegate extends DrawFilter_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Paint Flags Draw Filters are not supported.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeConstructor(int clearBits, int setBits) {
- PaintFlagsDrawFilter_Delegate newDelegate = new PaintFlagsDrawFilter_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
deleted file mode 100644
index 60e5cd99854a8..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
+++ /dev/null
@@ -1,1329 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.graphics.FontFamily_Delegate.FontVariant;
-import android.graphics.Paint.FontMetrics;
-import android.graphics.Paint.FontMetricsInt;
-import android.text.TextUtils;
-
-import java.awt.BasicStroke;
-import java.awt.Font;
-import java.awt.Shape;
-import java.awt.Stroke;
-import java.awt.Toolkit;
-import java.awt.geom.AffineTransform;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-
-import libcore.util.NativeAllocationRegistry_Delegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.Paint
- *
- * Through the layoutlib_create tool, the original native methods of Paint have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Paint class.
- *
- * @see DelegateManager
- *
- */
-public class Paint_Delegate {
-
- /**
- * Class associating a {@link Font} and its {@link java.awt.FontMetrics}.
- */
- /*package*/ static final class FontInfo {
- Font mFont;
- java.awt.FontMetrics mMetrics;
- }
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(Paint_Delegate.class);
- private static long sFinalizer = -1;
-
- // ---- delegate helper data ----
-
- // This list can contain null elements.
- private List mFonts;
-
- // ---- delegate data ----
- private int mFlags;
- private int mColor;
- private int mStyle;
- private int mCap;
- private int mJoin;
- private int mTextAlign;
- private Typeface_Delegate mTypeface;
- private float mStrokeWidth;
- private float mStrokeMiter;
- private float mTextSize;
- private float mTextScaleX;
- private float mTextSkewX;
- private int mHintingMode = Paint.HINTING_ON;
- private int mHyphenEdit;
- private float mLetterSpacing; // not used in actual text rendering.
- private float mWordSpacing; // not used in actual text rendering.
- // Variant of the font. A paint's variant can only be compact or elegant.
- private FontVariant mFontVariant = FontVariant.COMPACT;
-
- private int mPorterDuffMode = Xfermode.DEFAULT;
- private ColorFilter_Delegate mColorFilter;
- private Shader_Delegate mShader;
- private PathEffect_Delegate mPathEffect;
- private MaskFilter_Delegate mMaskFilter;
-
- private Locale mLocale = Locale.getDefault();
-
- // Used only to assert invariants.
- public long mNativeTypeface;
-
- // ---- Public Helper methods ----
-
- @Nullable
- public static Paint_Delegate getDelegate(long native_paint) {
- return sManager.getDelegate(native_paint);
- }
-
- /**
- * Returns the list of {@link Font} objects.
- */
- public List getFonts() {
- return mFonts;
- }
-
- public boolean isAntiAliased() {
- return (mFlags & Paint.ANTI_ALIAS_FLAG) != 0;
- }
-
- public boolean isFilterBitmap() {
- return (mFlags & Paint.FILTER_BITMAP_FLAG) != 0;
- }
-
- public int getStyle() {
- return mStyle;
- }
-
- public int getColor() {
- return mColor;
- }
-
- public int getAlpha() {
- return mColor >>> 24;
- }
-
- public void setAlpha(int alpha) {
- mColor = (alpha << 24) | (mColor & 0x00FFFFFF);
- }
-
- public int getTextAlign() {
- return mTextAlign;
- }
-
- public float getStrokeWidth() {
- return mStrokeWidth;
- }
-
- /**
- * returns the value of stroke miter needed by the java api.
- */
- public float getJavaStrokeMiter() {
- return mStrokeMiter;
- }
-
- public int getJavaCap() {
- switch (Paint.sCapArray[mCap]) {
- case BUTT:
- return BasicStroke.CAP_BUTT;
- case ROUND:
- return BasicStroke.CAP_ROUND;
- default:
- case SQUARE:
- return BasicStroke.CAP_SQUARE;
- }
- }
-
- public int getJavaJoin() {
- switch (Paint.sJoinArray[mJoin]) {
- default:
- case MITER:
- return BasicStroke.JOIN_MITER;
- case ROUND:
- return BasicStroke.JOIN_ROUND;
- case BEVEL:
- return BasicStroke.JOIN_BEVEL;
- }
- }
-
- public Stroke getJavaStroke() {
- if (mPathEffect != null) {
- if (mPathEffect.isSupported()) {
- Stroke stroke = mPathEffect.getStroke(this);
- assert stroke != null;
- if (stroke != null) {
- return stroke;
- }
- } else {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_PATHEFFECT,
- mPathEffect.getSupportMessage(),
- null, null /*data*/);
- }
- }
-
- // if no custom stroke as been set, set the default one.
- return new BasicStroke(
- getStrokeWidth(),
- getJavaCap(),
- getJavaJoin(),
- getJavaStrokeMiter());
- }
-
- /**
- * Returns the {@link PorterDuff.Mode} as an int
- */
- public int getPorterDuffMode() {
- return mPorterDuffMode;
- }
-
- /**
- * Returns the {@link ColorFilter} delegate or null if none have been set
- *
- * @return the delegate or null.
- */
- public ColorFilter_Delegate getColorFilter() {
- return mColorFilter;
- }
-
- public void setColorFilter(long colorFilterPtr) {
- mColorFilter = ColorFilter_Delegate.getDelegate(colorFilterPtr);
- }
-
- public void setShader(long shaderPtr) {
- mShader = Shader_Delegate.getDelegate(shaderPtr);
- }
-
- /**
- * Returns the {@link Shader} delegate or null if none have been set
- *
- * @return the delegate or null.
- */
- public Shader_Delegate getShader() {
- return mShader;
- }
-
- /**
- * Returns the {@link MaskFilter} delegate or null if none have been set
- *
- * @return the delegate or null.
- */
- public MaskFilter_Delegate getMaskFilter() {
- return mMaskFilter;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static int nGetFlags(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mFlags;
- }
-
-
-
- @LayoutlibDelegate
- /*package*/ static void nSetFlags(long nativePaint, int flags) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mFlags = flags;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetFilterBitmap(long nativePaint, boolean filter) {
- setFlag(nativePaint, Paint.FILTER_BITMAP_FLAG, filter);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetHinting(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return Paint.HINTING_ON;
- }
-
- return delegate.mHintingMode;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetHinting(long nativePaint, int mode) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mHintingMode = mode;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetAntiAlias(long nativePaint, boolean aa) {
- setFlag(nativePaint, Paint.ANTI_ALIAS_FLAG, aa);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetSubpixelText(long nativePaint,
- boolean subpixelText) {
- setFlag(nativePaint, Paint.SUBPIXEL_TEXT_FLAG, subpixelText);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetUnderlineText(long nativePaint,
- boolean underlineText) {
- setFlag(nativePaint, Paint.UNDERLINE_TEXT_FLAG, underlineText);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStrikeThruText(long nativePaint,
- boolean strikeThruText) {
- setFlag(nativePaint, Paint.STRIKE_THRU_TEXT_FLAG, strikeThruText);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetFakeBoldText(long nativePaint,
- boolean fakeBoldText) {
- setFlag(nativePaint, Paint.FAKE_BOLD_TEXT_FLAG, fakeBoldText);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetDither(long nativePaint, boolean dither) {
- setFlag(nativePaint, Paint.DITHER_FLAG, dither);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetLinearText(long nativePaint, boolean linearText) {
- setFlag(nativePaint, Paint.LINEAR_TEXT_FLAG, linearText);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetColor(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mColor;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetColor(long nativePaint, int color) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mColor = color;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetAlpha(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.getAlpha();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetAlpha(long nativePaint, int a) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.setAlpha(a);
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetStrokeWidth(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 1.f;
- }
-
- return delegate.mStrokeWidth;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStrokeWidth(long nativePaint, float width) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mStrokeWidth = width;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetStrokeMiter(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 1.f;
- }
-
- return delegate.mStrokeMiter;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStrokeMiter(long nativePaint, float miter) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mStrokeMiter = miter;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetShadowLayer(long paint, float radius, float dx, float dy,
- int color) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.setShadowLayer is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nHasShadowLayer(long paint) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.hasShadowLayer is not supported.", null, null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsElegantTextHeight(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- return delegate != null && delegate.mFontVariant == FontVariant.ELEGANT;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetElegantTextHeight(long nativePaint,
- boolean elegant) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- delegate.mFontVariant = elegant ? FontVariant.ELEGANT : FontVariant.COMPACT;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetTextSize(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 1.f;
- }
-
- return delegate.mTextSize;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTextSize(long nativePaint, float textSize) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- if (delegate.mTextSize != textSize) {
- delegate.mTextSize = textSize;
- delegate.updateFontObject();
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetTextScaleX(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 1.f;
- }
-
- return delegate.mTextScaleX;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTextScaleX(long nativePaint, float scaleX) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- if (delegate.mTextScaleX != scaleX) {
- delegate.mTextScaleX = scaleX;
- delegate.updateFontObject();
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetTextSkewX(long nativePaint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 1.f;
- }
-
- return delegate.mTextSkewX;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTextSkewX(long nativePaint, float skewX) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- if (delegate.mTextSkewX != skewX) {
- delegate.mTextSkewX = skewX;
- delegate.updateFontObject();
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static float nAscent(long nativePaint, long nativeTypeface) {
- // get the delegate
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- if (delegate.mFonts.size() > 0) {
- java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
- // Android expects negative ascent so we invert the value from Java.
- return - javaMetrics.getAscent();
- }
-
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nDescent(long nativePaint, long nativeTypeface) {
- // get the delegate
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- if (delegate.mFonts.size() > 0) {
- java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
- return javaMetrics.getDescent();
- }
-
- return 0;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetFontMetrics(long nativePaint, long nativeTypeface,
- FontMetrics metrics) {
- // get the delegate
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.getFontMetrics(metrics);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetFontMetricsInt(long nativePaint,
- long nativeTypeface, FontMetricsInt fmi) {
- // get the delegate
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- if (delegate.mFonts.size() > 0) {
- java.awt.FontMetrics javaMetrics = delegate.mFonts.get(0).mMetrics;
- if (fmi != null) {
- // Android expects negative ascent so we invert the value from Java.
- fmi.top = (int)(- javaMetrics.getMaxAscent() * 1.15);
- fmi.ascent = - javaMetrics.getAscent();
- fmi.descent = javaMetrics.getDescent();
- fmi.bottom = (int)(javaMetrics.getMaxDescent() * 1.15);
- fmi.leading = javaMetrics.getLeading();
- }
-
- return javaMetrics.getHeight();
- }
-
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nBreakText(long nativePaint, long nativeTypeface, char[] text,
- int index, int count, float maxWidth, int bidiFlags, float[] measuredWidth) {
-
- // get the delegate
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
-
- int inc = count > 0 ? 1 : -1;
-
- int measureIndex = 0;
- for (int i = index; i != index + count; i += inc, measureIndex++) {
- int start, end;
- if (i < index) {
- start = i;
- end = index;
- } else {
- start = index;
- end = i;
- }
-
- // measure from start to end
- RectF bounds = delegate.measureText(text, start, end - start + 1, null, 0, bidiFlags);
- float res = bounds.right - bounds.left;
-
- if (measuredWidth != null) {
- measuredWidth[measureIndex] = res;
- }
-
- if (res > maxWidth) {
- // we should not return this char index, but since it's 0-based
- // and we need to return a count, we simply return measureIndex;
- return measureIndex;
- }
-
- }
-
- return measureIndex;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nBreakText(long nativePaint, long nativeTypeface, String text,
- boolean measureForwards,
- float maxWidth, int bidiFlags, float[] measuredWidth) {
- return nBreakText(nativePaint, nativeTypeface, text.toCharArray(), 0, text.length(),
- maxWidth, bidiFlags, measuredWidth);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nInit() {
- Paint_Delegate newDelegate = new Paint_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nInitWithPaint(long paint) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(paint);
- if (delegate == null) {
- return 0;
- }
-
- Paint_Delegate newDelegate = new Paint_Delegate(delegate);
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nReset(long native_object) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
-
- delegate.reset();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSet(long native_dst, long native_src) {
- // get the delegate from the native int.
- Paint_Delegate delegate_dst = sManager.getDelegate(native_dst);
- if (delegate_dst == null) {
- return;
- }
-
- // get the delegate from the native int.
- Paint_Delegate delegate_src = sManager.getDelegate(native_src);
- if (delegate_src == null) {
- return;
- }
-
- delegate_dst.set(delegate_src);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetStyle(long native_object) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mStyle;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStyle(long native_object, int style) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
-
- delegate.mStyle = style;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetStrokeCap(long native_object) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mCap;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStrokeCap(long native_object, int cap) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
-
- delegate.mCap = cap;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetStrokeJoin(long native_object) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mJoin;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetStrokeJoin(long native_object, int join) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
-
- delegate.mJoin = join;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nGetFillPath(long native_object, long src, long dst) {
- Paint_Delegate paint = sManager.getDelegate(native_object);
- if (paint == null) {
- return false;
- }
-
- Path_Delegate srcPath = Path_Delegate.getDelegate(src);
- if (srcPath == null) {
- return true;
- }
-
- Path_Delegate dstPath = Path_Delegate.getDelegate(dst);
- if (dstPath == null) {
- return true;
- }
-
- Stroke stroke = paint.getJavaStroke();
- Shape strokeShape = stroke.createStrokedShape(srcPath.getJavaShape());
-
- dstPath.setJavaShape(strokeShape);
-
- // FIXME figure out the return value?
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nSetShader(long native_object, long shader) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return shader;
- }
-
- delegate.mShader = Shader_Delegate.getDelegate(shader);
-
- return shader;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nSetColorFilter(long native_object, long filter) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return filter;
- }
-
- delegate.mColorFilter = ColorFilter_Delegate.getDelegate(filter);
-
- // Log warning if it's not supported.
- if (delegate.mColorFilter != null && !delegate.mColorFilter.isSupported()) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_COLORFILTER,
- delegate.mColorFilter.getSupportMessage(), null, null /*data*/);
- }
-
- return filter;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetXfermode(long native_object, int xfermode) {
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
- delegate.mPorterDuffMode = xfermode;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nSetPathEffect(long native_object, long effect) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return effect;
- }
-
- delegate.mPathEffect = PathEffect_Delegate.getDelegate(effect);
-
- return effect;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nSetMaskFilter(long native_object, long maskfilter) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return maskfilter;
- }
-
- delegate.mMaskFilter = MaskFilter_Delegate.getDelegate(maskfilter);
-
- // since none of those are supported, display a fidelity warning right away
- if (delegate.mMaskFilter != null && !delegate.mMaskFilter.isSupported()) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MASKFILTER,
- delegate.mMaskFilter.getSupportMessage(), null, null /*data*/);
- }
-
- return maskfilter;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nSetTypeface(long native_object, long typeface) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- Typeface_Delegate typefaceDelegate = Typeface_Delegate.getDelegate(typeface);
- if (delegate.mTypeface != typefaceDelegate || delegate.mNativeTypeface != typeface) {
- delegate.mTypeface = Typeface_Delegate.getDelegate(typeface);
- delegate.mNativeTypeface = typeface;
- delegate.updateFontObject();
- }
- return typeface;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetTextAlign(long native_object) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mTextAlign;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTextAlign(long native_object, int align) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return;
- }
-
- delegate.mTextAlign = align;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nSetTextLocales(long native_object, String locale) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0;
- }
-
- delegate.setTextLocale(locale);
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetTextLocalesByMinikinLangListId(long paintPtr,
- int mMinikinLangListId) {
- // FIXME
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetTextAdvances(long native_object, long native_typeface,
- char[] text, int index, int count, int contextIndex, int contextCount,
- int bidiFlags, float[] advances, int advancesIndex) {
-
- if (advances != null)
- for (int i = advancesIndex; i< advancesIndex+count; i++)
- advances[i]=0;
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(native_object);
- if (delegate == null) {
- return 0.f;
- }
-
- // native_typeface is passed here since Framework's old implementation did not have the
- // typeface object associated with the Paint. Since, we follow the new framework way,
- // we store the typeface with the paint and use it directly.
- assert (native_typeface == delegate.mNativeTypeface);
-
- RectF bounds = delegate.measureText(text, index, count, advances, advancesIndex, bidiFlags);
- return bounds.right - bounds.left;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetTextAdvances(long native_object, long native_typeface,
- String text, int start, int end, int contextStart, int contextEnd,
- int bidiFlags, float[] advances, int advancesIndex) {
- // FIXME: support contextStart and contextEnd
- int count = end - start;
- char[] buffer = TemporaryBuffer.obtain(count);
- TextUtils.getChars(text, start, end, buffer, 0);
-
- return nGetTextAdvances(native_object, native_typeface, buffer, 0, count,
- contextStart, contextEnd - contextStart, bidiFlags, advances, advancesIndex);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetTextRunCursor(Paint paint, long native_object, long typefacePtr,
- char[] text, int contextStart, int contextLength, int flags, int offset,
- int cursorOpt) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.getTextRunCursor is not supported.", null, null /*data*/);
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetTextRunCursor(Paint paint, long native_object, long typefacePtr,
- String text, int contextStart, int contextEnd, int flags, int offset, int cursorOpt) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.getTextRunCursor is not supported.", null, null /*data*/);
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nGetTextPath(long native_object, long native_typeface,
- int bidiFlags, char[] text, int index, int count, float x, float y, long path) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.getTextPath is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nGetTextPath(long native_object, long native_typeface,
- int bidiFlags, String text, int start, int end, float x, float y, long path) {
- // FIXME
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Paint.getTextPath is not supported.", null, null /*data*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nGetStringBounds(long nativePaint, long native_typeface,
- String text, int start, int end, int bidiFlags, Rect bounds) {
- nGetCharArrayBounds(nativePaint, native_typeface, text.toCharArray(), start,
- end - start, bidiFlags, bounds);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nGetCharArrayBounds(long nativePaint, long native_typeface,
- char[] text, int index, int count, int bidiFlags, Rect bounds) {
-
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- // assert that the typeface passed is actually the one that we had stored.
- assert (native_typeface == delegate.mNativeTypeface);
-
- delegate.measureText(text, index, count, null, 0, bidiFlags).roundOut(bounds);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nGetNativeFinalizer() {
- synchronized (Paint_Delegate.class) {
- if (sFinalizer == -1) {
- sFinalizer = NativeAllocationRegistry_Delegate.createFinalizer(
- sManager::removeJavaReferenceFor);
- }
- }
- return sFinalizer;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetLetterSpacing(long nativePaint) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
- return delegate.mLetterSpacing;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetLetterSpacing(long nativePaint, float letterSpacing) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_TEXT_RENDERING,
- "Paint.setLetterSpacing() not supported.", null, null);
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
- delegate.mLetterSpacing = letterSpacing;
- }
-
- @LayoutlibDelegate
- /*package*/ static float nGetWordSpacing(long nativePaint) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
- return delegate.mWordSpacing;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetWordSpacing(long nativePaint, float wordSpacing) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
- delegate.mWordSpacing = wordSpacing;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetFontFeatureSettings(long nativePaint, String settings) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_TEXT_RENDERING,
- "Paint.setFontFeatureSettings() not supported.", null, null);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetHyphenEdit(long nativePaint) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return 0;
- }
- return delegate.mHyphenEdit;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetHyphenEdit(long nativePaint, int hyphen) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
- delegate.mHyphenEdit = hyphen;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nHasGlyph(long nativePaint, long nativeTypeface, int bidiFlags,
- String string) {
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return false;
- }
- if (string.length() == 0) {
- return false;
- }
- if (string.length() > 1) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_TEXT_RENDERING,
- "Paint.hasGlyph() is not supported for ligatures.", null, null);
- return false;
- }
- assert nativeTypeface == delegate.mNativeTypeface;
- Typeface_Delegate typeface_delegate = Typeface_Delegate.getDelegate(nativeTypeface);
-
- char c = string.charAt(0);
- for (Font font : typeface_delegate.getFonts(delegate.mFontVariant)) {
- if (font.canDisplay(c)) {
- return true;
- }
- }
- return false;
- }
-
-
- @LayoutlibDelegate
- /*package*/ static float nGetRunAdvance(long nativePaint, long nativeTypeface,
- @NonNull char[] text, int start, int end, int contextStart, int contextEnd,
- boolean isRtl, int offset) {
- int count = end - start;
- float[] advances = new float[count];
- int bidiFlags = isRtl ? Paint.BIDI_FORCE_RTL : Paint.BIDI_FORCE_LTR;
- nGetTextAdvances(nativePaint, nativeTypeface, text, start, count,
- contextStart, contextEnd - contextStart, bidiFlags, advances, 0);
- int startOffset = offset - start; // offset from start.
- float sum = 0;
- for (int i = 0; i < startOffset; i++) {
- sum += advances[i];
- }
- return sum;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetOffsetForAdvance(long nativePaint, long nativeTypeface,
- char[] text, int start, int end, int contextStart, int contextEnd, boolean isRtl,
- float advance) {
- int count = end - start;
- float[] advances = new float[count];
- int bidiFlags = isRtl ? Paint.BIDI_FORCE_RTL : Paint.BIDI_FORCE_LTR;
- nGetTextAdvances(nativePaint, nativeTypeface, text, start, count,
- contextStart, contextEnd - contextStart, bidiFlags, advances, 0);
- float sum = 0;
- int i;
- for (i = 0; i < count && sum < advance; i++) {
- sum += advances[i];
- }
- float distanceToI = sum - advance;
- float distanceToIMinus1 = advance - (sum - advances[i]);
- return distanceToI > distanceToIMinus1 ? i : i - 1;
- }
-
- // ---- Private delegate/helper methods ----
-
- /*package*/ Paint_Delegate() {
- reset();
- }
-
- private Paint_Delegate(Paint_Delegate paint) {
- set(paint);
- }
-
- private void set(Paint_Delegate paint) {
- mFlags = paint.mFlags;
- mColor = paint.mColor;
- mStyle = paint.mStyle;
- mCap = paint.mCap;
- mJoin = paint.mJoin;
- mTextAlign = paint.mTextAlign;
-
- boolean needsFontUpdate = false;
- if (mTypeface != paint.mTypeface || mNativeTypeface != paint.mNativeTypeface) {
- mTypeface = paint.mTypeface;
- mNativeTypeface = paint.mNativeTypeface;
- needsFontUpdate = true;
- }
-
- if (mTextSize != paint.mTextSize) {
- mTextSize = paint.mTextSize;
- needsFontUpdate = true;
- }
-
- if (mTextScaleX != paint.mTextScaleX) {
- mTextScaleX = paint.mTextScaleX;
- needsFontUpdate = true;
- }
-
- if (mTextSkewX != paint.mTextSkewX) {
- mTextSkewX = paint.mTextSkewX;
- needsFontUpdate = true;
- }
-
- mStrokeWidth = paint.mStrokeWidth;
- mStrokeMiter = paint.mStrokeMiter;
- mPorterDuffMode = paint.mPorterDuffMode;
- mColorFilter = paint.mColorFilter;
- mShader = paint.mShader;
- mPathEffect = paint.mPathEffect;
- mMaskFilter = paint.mMaskFilter;
- mHintingMode = paint.mHintingMode;
-
- if (needsFontUpdate) {
- updateFontObject();
- }
- }
-
- private void reset() {
- mFlags = Paint.HIDDEN_DEFAULT_PAINT_FLAGS;
- mColor = 0xFF000000;
- mStyle = Paint.Style.FILL.nativeInt;
- mCap = Paint.Cap.BUTT.nativeInt;
- mJoin = Paint.Join.MITER.nativeInt;
- mTextAlign = 0;
- mTypeface = Typeface_Delegate.getDelegate(Typeface.sDefaults[0].native_instance);
- mNativeTypeface = 0;
- mStrokeWidth = 1.f;
- mStrokeMiter = 4.f;
- mTextSize = 20.f;
- mTextScaleX = 1.f;
- mTextSkewX = 0.f;
- mPorterDuffMode = Xfermode.DEFAULT;
- mColorFilter = null;
- mShader = null;
- mPathEffect = null;
- mMaskFilter = null;
- updateFontObject();
- mHintingMode = Paint.HINTING_ON;
- }
-
- /**
- * Update the {@link Font} object from the typeface, text size and scaling
- */
- @SuppressWarnings("deprecation")
- private void updateFontObject() {
- if (mTypeface != null) {
- // Get the fonts from the TypeFace object.
- List fonts = mTypeface.getFonts(mFontVariant);
-
- if (fonts.isEmpty()) {
- mFonts = Collections.emptyList();
- return;
- }
-
- // create new font objects as well as FontMetrics, based on the current text size
- // and skew info.
- int nFonts = fonts.size();
- ArrayList infoList = new ArrayList(nFonts);
- //noinspection ForLoopReplaceableByForEach (avoid iterator instantiation)
- for (int i = 0; i < nFonts; i++) {
- Font font = fonts.get(i);
- if (font == null) {
- // If the font is null, add null to infoList. When rendering the text, if this
- // null is reached, a warning will be logged.
- infoList.add(null);
- continue;
- }
- FontInfo info = new FontInfo();
- info.mFont = font.deriveFont(mTextSize);
- if (mTextScaleX != 1.0 || mTextSkewX != 0) {
- // TODO: support skew
- info.mFont = info.mFont.deriveFont(new AffineTransform(
- mTextScaleX, mTextSkewX, 0, 1, 0, 0));
- }
- // The metrics here don't have anti-aliasing set.
- info.mMetrics = Toolkit.getDefaultToolkit().getFontMetrics(info.mFont);
-
- infoList.add(info);
- }
-
- mFonts = Collections.unmodifiableList(infoList);
- }
- }
-
- /*package*/ RectF measureText(char[] text, int index, int count, float[] advances,
- int advancesIndex, int bidiFlags) {
- return new BidiRenderer(null, this, text)
- .renderText(index, index + count, bidiFlags, advances, advancesIndex, false);
- }
-
- /*package*/ RectF measureText(char[] text, int index, int count, float[] advances,
- int advancesIndex, boolean isRtl) {
- return new BidiRenderer(null, this, text)
- .renderText(index, index + count, isRtl, advances, advancesIndex, false);
- }
-
- private float getFontMetrics(FontMetrics metrics) {
- if (mFonts.size() > 0) {
- java.awt.FontMetrics javaMetrics = mFonts.get(0).mMetrics;
- if (metrics != null) {
- // Android expects negative ascent so we invert the value from Java.
- metrics.top = - javaMetrics.getMaxAscent();
- metrics.ascent = - javaMetrics.getAscent();
- metrics.descent = javaMetrics.getDescent();
- metrics.bottom = javaMetrics.getMaxDescent();
- metrics.leading = javaMetrics.getLeading();
- }
-
- return javaMetrics.getHeight();
- }
-
- return 0;
- }
-
- private void setTextLocale(String locale) {
- mLocale = new Locale(locale);
- }
-
- private static void setFlag(long nativePaint, int flagMask, boolean flagValue) {
- // get the delegate from the native int.
- Paint_Delegate delegate = sManager.getDelegate(nativePaint);
- if (delegate == null) {
- return;
- }
-
- if (flagValue) {
- delegate.mFlags |= flagMask;
- } else {
- delegate.mFlags &= ~flagMask;
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java
deleted file mode 100644
index fd9ba62e2695d..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/PathDashPathEffect_Delegate.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.PathDashPathEffect
- *
- * Through the layoutlib_create tool, the original native methods of PathDashPathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original PathDashPathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public class PathDashPathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Path Dash Path Effects are not supported in Layout Preview mode.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(long native_path, float advance, float phase,
- int native_style) {
- PathDashPathEffect_Delegate newDelegate = new PathDashPathEffect_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java
deleted file mode 100644
index 000481ec7cc91..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/PathEffect_Delegate.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.PathEffect
- *
- * Through the layoutlib_create tool, the original native methods of PathEffect have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original PathEffect class.
- *
- * This also serve as a base class for all PathEffect delegate classes.
- *
- * @see DelegateManager
- *
- */
-public abstract class PathEffect_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(PathEffect_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- public static PathEffect_Delegate getDelegate(long nativeShader) {
- return sManager.getDelegate(nativeShader);
- }
-
- public abstract Stroke getStroke(Paint_Delegate paint);
- public abstract boolean isSupported();
- public abstract String getSupportMessage();
-
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nativeDestructor(long native_patheffect) {
- sManager.removeJavaReferenceFor(native_patheffect);
- }
-
- // ---- Private delegate/helper methods ----
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PathMeasure_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PathMeasure_Delegate.java
deleted file mode 100644
index 7f707c9aa01a8..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/PathMeasure_Delegate.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.layoutlib.bridge.util.CachedPathIteratorFactory;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import com.android.layoutlib.bridge.util.CachedPathIteratorFactory.CachedPathIterator;
-
-import java.awt.geom.PathIterator;
-
-/**
- * Delegate implementing the native methods of {@link android.graphics.PathMeasure}
- *
- * Through the layoutlib_create tool, the original native methods of PathMeasure have been
- * replaced by
- * calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between it
- * and the original PathMeasure class.
- *
- * @see DelegateManager
- */
-public final class PathMeasure_Delegate {
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(PathMeasure_Delegate.class);
-
- // ---- delegate data ----
- private CachedPathIteratorFactory mOriginalPathIterator;
-
- private long mNativePath;
-
-
- private PathMeasure_Delegate(long native_path, boolean forceClosed) {
- mNativePath = native_path;
- if (native_path != 0) {
- if (forceClosed) {
- // Copy the path and call close
- native_path = Path_Delegate.nInit(native_path);
- Path_Delegate.nClose(native_path);
- }
-
- Path_Delegate pathDelegate = Path_Delegate.getDelegate(native_path);
- mOriginalPathIterator = new CachedPathIteratorFactory(pathDelegate.getJavaShape()
- .getPathIterator(null));
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static long native_create(long native_path, boolean forceClosed) {
- return sManager.addNewDelegate(new PathMeasure_Delegate(native_path, forceClosed));
- }
-
- @LayoutlibDelegate
- /*package*/ static void native_destroy(long native_instance) {
- sManager.removeJavaReferenceFor(native_instance);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean native_getPosTan(long native_instance, float distance, float pos[],
- float tan[]) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "PathMeasure.getPostTan is not supported.", null, null);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean native_getMatrix(long native_instance, float distance, long
- native_matrix, int flags) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "PathMeasure.getMatrix is not supported.", null, null);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean native_nextContour(long native_instance) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "PathMeasure.nextContour is not supported.", null, null);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void native_setPath(long native_instance, long native_path, boolean
- forceClosed) {
- PathMeasure_Delegate pathMeasure = sManager.getDelegate(native_instance);
- assert pathMeasure != null;
-
- if (native_path != 0) {
- if (forceClosed) {
- // Copy the path and call close
- native_path = Path_Delegate.nInit(native_path);
- Path_Delegate.nClose(native_path);
- }
-
- Path_Delegate pathDelegate = Path_Delegate.getDelegate(native_path);
- pathMeasure.mOriginalPathIterator = new CachedPathIteratorFactory(pathDelegate.getJavaShape()
- .getPathIterator(null));
- }
-
- pathMeasure.mNativePath = native_path;
- }
-
- @LayoutlibDelegate
- /*package*/ static float native_getLength(long native_instance) {
- PathMeasure_Delegate pathMeasure = sManager.getDelegate(native_instance);
- assert pathMeasure != null;
-
- if (pathMeasure.mOriginalPathIterator == null) {
- return 0;
- }
-
- return pathMeasure.mOriginalPathIterator.iterator().getTotalLength();
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean native_isClosed(long native_instance) {
- PathMeasure_Delegate pathMeasure = sManager.getDelegate(native_instance);
- assert pathMeasure != null;
-
- Path_Delegate path = Path_Delegate.getDelegate(pathMeasure.mNativePath);
- if (path == null) {
- return false;
- }
-
- int type = 0;
- float segment[] = new float[6];
- for (PathIterator pi = path.getJavaShape().getPathIterator(null); !pi.isDone(); pi.next()) {
- type = pi.currentSegment(segment);
- }
-
- // A path is a closed path if the last element is SEG_CLOSE
- return type == PathIterator.SEG_CLOSE;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean native_getSegment(long native_instance, float startD, float stopD,
- long native_dst_path, boolean startWithMoveTo) {
- if (startD < 0) {
- startD = 0;
- }
-
- if (startD >= stopD) {
- return false;
- }
-
- PathMeasure_Delegate pathMeasure = sManager.getDelegate(native_instance);
- assert pathMeasure != null;
-
- CachedPathIterator iterator = pathMeasure.mOriginalPathIterator.iterator();
- float accLength = startD;
- boolean isZeroLength = true; // Whether the output has zero length or not
- float[] points = new float[6];
-
- iterator.jumpToSegment(accLength);
- while (!iterator.isDone() && (stopD - accLength > 0.1f)) {
- int type = iterator.currentSegment(points, stopD - accLength);
-
- if (accLength - iterator.getCurrentSegmentLength() <= stopD) {
- if (startWithMoveTo) {
- startWithMoveTo = false;
-
- // If this segment is a MOVETO, then we just use that one. If not, then we issue
- // a first moveto
- if (type != PathIterator.SEG_MOVETO) {
- float[] lastPoint = new float[2];
- iterator.getCurrentSegmentEnd(lastPoint);
- Path_Delegate.nMoveTo(native_dst_path, lastPoint[0], lastPoint[1]);
- }
- }
-
- isZeroLength = isZeroLength && iterator.getCurrentSegmentLength() > 0;
- switch (type) {
- case PathIterator.SEG_MOVETO:
- Path_Delegate.nMoveTo(native_dst_path, points[0], points[1]);
- break;
- case PathIterator.SEG_LINETO:
- Path_Delegate.nLineTo(native_dst_path, points[0], points[1]);
- break;
- case PathIterator.SEG_CLOSE:
- Path_Delegate.nClose(native_dst_path);
- break;
- case PathIterator.SEG_CUBICTO:
- Path_Delegate.nCubicTo(native_dst_path, points[0], points[1],
- points[2], points[3],
- points[4], points[5]);
- break;
- case PathIterator.SEG_QUADTO:
- Path_Delegate.nQuadTo(native_dst_path, points[0], points[1],
- points[2],
- points[3]);
- break;
- default:
- assert false;
- }
- }
-
- accLength += iterator.getCurrentSegmentLength();
- iterator.next();
- }
-
- return !isZeroLength;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
deleted file mode 100644
index 50b9165323197..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
+++ /dev/null
@@ -1,896 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.NonNull;
-import android.graphics.Path.Direction;
-import android.graphics.Path.FillType;
-
-import java.awt.Shape;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Arc2D;
-import java.awt.geom.Area;
-import java.awt.geom.Ellipse2D;
-import java.awt.geom.GeneralPath;
-import java.awt.geom.Path2D;
-import java.awt.geom.PathIterator;
-import java.awt.geom.Point2D;
-import java.awt.geom.Rectangle2D;
-import java.awt.geom.RoundRectangle2D;
-import java.util.ArrayList;
-
-/**
- * Delegate implementing the native methods of android.graphics.Path
- *
- * Through the layoutlib_create tool, the original native methods of Path have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Path class.
- *
- * @see DelegateManager
- *
- */
-public final class Path_Delegate {
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(Path_Delegate.class);
-
- private static final float EPSILON = 1e-4f;
-
- // ---- delegate data ----
- private FillType mFillType = FillType.WINDING;
- private Path2D mPath = new Path2D.Double();
-
- private float mLastX = 0;
- private float mLastY = 0;
-
- // true if the path contains does not contain a curve or line.
- private boolean mCachedIsEmpty = true;
-
- // ---- Public Helper methods ----
-
- public static Path_Delegate getDelegate(long nPath) {
- return sManager.getDelegate(nPath);
- }
-
- public Path2D getJavaShape() {
- return mPath;
- }
-
- public void setJavaShape(Shape shape) {
- reset();
- mPath.append(shape, false /*connect*/);
- }
-
- public void reset() {
- mPath.reset();
- mLastX = 0;
- mLastY = 0;
- }
-
- public void setPathIterator(PathIterator iterator) {
- reset();
- mPath.append(iterator, false /*connect*/);
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nInit() {
- // create the delegate
- Path_Delegate newDelegate = new Path_Delegate();
-
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nInit(long nPath) {
- // create the delegate
- Path_Delegate newDelegate = new Path_Delegate();
-
- // get the delegate to copy, which could be null if nPath is 0
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate != null) {
- newDelegate.set(pathDelegate);
- }
-
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nReset(long nPath) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.reset();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nRewind(long nPath) {
- // call out to reset since there's nothing to optimize in
- // terms of data structs.
- nReset(nPath);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSet(long native_dst, long nSrc) {
- Path_Delegate pathDstDelegate = sManager.getDelegate(native_dst);
- if (pathDstDelegate == null) {
- return;
- }
-
- Path_Delegate pathSrcDelegate = sManager.getDelegate(nSrc);
- if (pathSrcDelegate == null) {
- return;
- }
-
- pathDstDelegate.set(pathSrcDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsConvex(long nPath) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "Path.isConvex is not supported.", null, null);
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nGetFillType(long nPath) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return 0;
- }
-
- return pathDelegate.mFillType.nativeInt;
- }
-
- @LayoutlibDelegate
- public static void nSetFillType(long nPath, int ft) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.setFillType(Path.sFillTypeArray[ft]);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsEmpty(long nPath) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- return pathDelegate == null || pathDelegate.isEmpty();
-
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nIsRect(long nPath, RectF rect) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return false;
- }
-
- // create an Area that can test if the path is a rect
- Area area = new Area(pathDelegate.mPath);
- if (area.isRectangular()) {
- if (rect != null) {
- pathDelegate.fillBounds(rect);
- }
-
- return true;
- }
-
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nComputeBounds(long nPath, RectF bounds) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.fillBounds(bounds);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nIncReserve(long nPath, int extraPtCount) {
- // since we use a java2D path, there's no way to pre-allocate new points,
- // so we do nothing.
- }
-
- @LayoutlibDelegate
- /*package*/ static void nMoveTo(long nPath, float x, float y) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.moveTo(x, y);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nRMoveTo(long nPath, float dx, float dy) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.rMoveTo(dx, dy);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nLineTo(long nPath, float x, float y) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.lineTo(x, y);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nRLineTo(long nPath, float dx, float dy) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.rLineTo(dx, dy);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nQuadTo(long nPath, float x1, float y1, float x2, float y2) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.quadTo(x1, y1, x2, y2);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nRQuadTo(long nPath, float dx1, float dy1, float dx2, float dy2) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.rQuadTo(dx1, dy1, dx2, dy2);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nCubicTo(long nPath, float x1, float y1,
- float x2, float y2, float x3, float y3) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.cubicTo(x1, y1, x2, y2, x3, y3);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nRCubicTo(long nPath, float x1, float y1,
- float x2, float y2, float x3, float y3) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.rCubicTo(x1, y1, x2, y2, x3, y3);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nArcTo(long nPath, float left, float top, float right,
- float bottom,
- float startAngle, float sweepAngle, boolean forceMoveTo) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.arcTo(left, top, right, bottom, startAngle, sweepAngle, forceMoveTo);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nClose(long nPath) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.close();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddRect(long nPath,
- float left, float top, float right, float bottom, int dir) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.addRect(left, top, right, bottom, dir);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddOval(long nPath, float left, float top, float right,
- float bottom, int dir) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.mPath.append(new Ellipse2D.Float(
- left, top, right - left, bottom - top), false);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddCircle(long nPath, float x, float y, float radius, int dir) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- // because x/y is the center of the circle, need to offset this by the radius
- pathDelegate.mPath.append(new Ellipse2D.Float(
- x - radius, y - radius, radius * 2, radius * 2), false);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddArc(long nPath, float left, float top, float right,
- float bottom, float startAngle, float sweepAngle) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- // because x/y is the center of the circle, need to offset this by the radius
- pathDelegate.mPath.append(new Arc2D.Float(
- left, top, right - left, bottom - top,
- -startAngle, -sweepAngle, Arc2D.OPEN), false);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddRoundRect(long nPath, float left, float top, float right,
- float bottom, float rx, float ry, int dir) {
-
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.mPath.append(new RoundRectangle2D.Float(
- left, top, right - left, bottom - top, rx * 2, ry * 2), false);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddRoundRect(long nPath, float left, float top, float right,
- float bottom, float[] radii, int dir) {
-
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- float[] cornerDimensions = new float[radii.length];
- for (int i = 0; i < radii.length; i++) {
- cornerDimensions[i] = 2 * radii[i];
- }
- pathDelegate.mPath.append(new RoundRectangle(left, top, right - left, bottom - top,
- cornerDimensions), false);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddPath(long nPath, long src, float dx, float dy) {
- addPath(nPath, src, AffineTransform.getTranslateInstance(dx, dy));
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddPath(long nPath, long src) {
- addPath(nPath, src, null /*transform*/);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nAddPath(long nPath, long src, long matrix) {
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
- if (matrixDelegate == null) {
- return;
- }
-
- addPath(nPath, src, matrixDelegate.getAffineTransform());
- }
-
- @LayoutlibDelegate
- /*package*/ static void nOffset(long nPath, float dx, float dy) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.offset(dx, dy);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetLastPoint(long nPath, float dx, float dy) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- pathDelegate.mLastX = dx;
- pathDelegate.mLastY = dy;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nTransform(long nPath, long matrix,
- long dst_path) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return;
- }
-
- Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
- if (matrixDelegate == null) {
- return;
- }
-
- // this can be null if dst_path is 0
- Path_Delegate dstDelegate = sManager.getDelegate(dst_path);
-
- pathDelegate.transform(matrixDelegate, dstDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nTransform(long nPath, long matrix) {
- nTransform(nPath, matrix, 0);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nOp(long nPath1, long nPath2, int op, long result) {
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED, "Path.op() not supported", null);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nFinalize(long nPath) {
- sManager.removeJavaReferenceFor(nPath);
- }
-
- @LayoutlibDelegate
- /*package*/ static float[] nApproximate(long nPath, float error) {
- Path_Delegate pathDelegate = sManager.getDelegate(nPath);
- if (pathDelegate == null) {
- return null;
- }
- // Get a FlatteningIterator
- PathIterator iterator = pathDelegate.getJavaShape().getPathIterator(null, error);
-
- float segment[] = new float[6];
- float totalLength = 0;
- ArrayList points = new ArrayList();
- Point2D.Float previousPoint = null;
- while (!iterator.isDone()) {
- int type = iterator.currentSegment(segment);
- Point2D.Float currentPoint = new Point2D.Float(segment[0], segment[1]);
- // MoveTo shouldn't affect the length
- if (previousPoint != null && type != PathIterator.SEG_MOVETO) {
- totalLength += currentPoint.distance(previousPoint);
- }
- previousPoint = currentPoint;
- points.add(currentPoint);
- iterator.next();
- }
-
- int nPoints = points.size();
- float[] result = new float[nPoints * 3];
- previousPoint = null;
- for (int i = 0; i < nPoints; i++) {
- Point2D.Float point = points.get(i);
- float distance = previousPoint != null ? (float) previousPoint.distance(point) : .0f;
- result[i * 3] = distance / totalLength;
- result[i * 3 + 1] = point.x;
- result[i * 3 + 2] = point.y;
-
- totalLength += distance;
- previousPoint = point;
- }
-
- return result;
- }
-
- // ---- Private helper methods ----
-
- private void set(Path_Delegate delegate) {
- mPath.reset();
- setFillType(delegate.mFillType);
- mPath.append(delegate.mPath, false /*connect*/);
- }
-
- private void setFillType(FillType fillType) {
- mFillType = fillType;
- mPath.setWindingRule(getWindingRule(fillType));
- }
-
- /**
- * Returns the Java2D winding rules matching a given Android {@link FillType}.
- * @param type the android fill type
- * @return the matching java2d winding rule.
- */
- private static int getWindingRule(FillType type) {
- switch (type) {
- case WINDING:
- case INVERSE_WINDING:
- return GeneralPath.WIND_NON_ZERO;
- case EVEN_ODD:
- case INVERSE_EVEN_ODD:
- return GeneralPath.WIND_EVEN_ODD;
-
- default:
- assert false;
- return GeneralPath.WIND_NON_ZERO;
- }
- }
-
- @NonNull
- private static Direction getDirection(int direction) {
- for (Direction d : Direction.values()) {
- if (direction == d.nativeInt) {
- return d;
- }
- }
-
- assert false;
- return null;
- }
-
- public static void addPath(long destPath, long srcPath, AffineTransform transform) {
- Path_Delegate destPathDelegate = sManager.getDelegate(destPath);
- if (destPathDelegate == null) {
- return;
- }
-
- Path_Delegate srcPathDelegate = sManager.getDelegate(srcPath);
- if (srcPathDelegate == null) {
- return;
- }
-
- if (transform != null) {
- destPathDelegate.mPath.append(
- srcPathDelegate.mPath.getPathIterator(transform), false);
- } else {
- destPathDelegate.mPath.append(srcPathDelegate.mPath, false);
- }
- }
-
-
- /**
- * Returns whether the path already contains any points.
- * Note that this is different to
- * {@link #isEmpty} because if all elements are {@link PathIterator#SEG_MOVETO},
- * {@link #isEmpty} will return true while hasPoints will return false.
- */
- public boolean hasPoints() {
- return !mPath.getPathIterator(null).isDone();
- }
-
- /**
- * Returns whether the path is empty (contains no lines or curves).
- * @see Path#isEmpty
- */
- public boolean isEmpty() {
- if (!mCachedIsEmpty) {
- return false;
- }
-
- float[] coords = new float[6];
- mCachedIsEmpty = Boolean.TRUE;
- for (PathIterator it = mPath.getPathIterator(null); !it.isDone(); it.next()) {
- int type = it.currentSegment(coords);
- if (type != PathIterator.SEG_MOVETO) {
- // Once we know that the path is not empty, we do not need to check again unless
- // Path#reset is called.
- mCachedIsEmpty = false;
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Fills the given {@link RectF} with the path bounds.
- * @param bounds the RectF to be filled.
- */
- public void fillBounds(RectF bounds) {
- Rectangle2D rect = mPath.getBounds2D();
- bounds.left = (float)rect.getMinX();
- bounds.right = (float)rect.getMaxX();
- bounds.top = (float)rect.getMinY();
- bounds.bottom = (float)rect.getMaxY();
- }
-
- /**
- * Set the beginning of the next contour to the point (x,y).
- *
- * @param x The x-coordinate of the start of a new contour
- * @param y The y-coordinate of the start of a new contour
- */
- public void moveTo(float x, float y) {
- mPath.moveTo(mLastX = x, mLastY = y);
- }
-
- /**
- * Set the beginning of the next contour relative to the last point on the
- * previous contour. If there is no previous contour, this is treated the
- * same as moveTo().
- *
- * @param dx The amount to add to the x-coordinate of the end of the
- * previous contour, to specify the start of a new contour
- * @param dy The amount to add to the y-coordinate of the end of the
- * previous contour, to specify the start of a new contour
- */
- public void rMoveTo(float dx, float dy) {
- dx += mLastX;
- dy += mLastY;
- mPath.moveTo(mLastX = dx, mLastY = dy);
- }
-
- /**
- * Add a line from the last point to the specified point (x,y).
- * If no moveTo() call has been made for this contour, the first point is
- * automatically set to (0,0).
- *
- * @param x The x-coordinate of the end of a line
- * @param y The y-coordinate of the end of a line
- */
- public void lineTo(float x, float y) {
- if (!hasPoints()) {
- mPath.moveTo(mLastX = 0, mLastY = 0);
- }
- mPath.lineTo(mLastX = x, mLastY = y);
- }
-
- /**
- * Same as lineTo, but the coordinates are considered relative to the last
- * point on this contour. If there is no previous point, then a moveTo(0,0)
- * is inserted automatically.
- *
- * @param dx The amount to add to the x-coordinate of the previous point on
- * this contour, to specify a line
- * @param dy The amount to add to the y-coordinate of the previous point on
- * this contour, to specify a line
- */
- public void rLineTo(float dx, float dy) {
- if (!hasPoints()) {
- mPath.moveTo(mLastX = 0, mLastY = 0);
- }
-
- if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON) {
- // The delta is so small that this shouldn't generate a line
- return;
- }
-
- dx += mLastX;
- dy += mLastY;
- mPath.lineTo(mLastX = dx, mLastY = dy);
- }
-
- /**
- * Add a quadratic bezier from the last point, approaching control point
- * (x1,y1), and ending at (x2,y2). If no moveTo() call has been made for
- * this contour, the first point is automatically set to (0,0).
- *
- * @param x1 The x-coordinate of the control point on a quadratic curve
- * @param y1 The y-coordinate of the control point on a quadratic curve
- * @param x2 The x-coordinate of the end point on a quadratic curve
- * @param y2 The y-coordinate of the end point on a quadratic curve
- */
- public void quadTo(float x1, float y1, float x2, float y2) {
- mPath.quadTo(x1, y1, mLastX = x2, mLastY = y2);
- }
-
- /**
- * Same as quadTo, but the coordinates are considered relative to the last
- * point on this contour. If there is no previous point, then a moveTo(0,0)
- * is inserted automatically.
- *
- * @param dx1 The amount to add to the x-coordinate of the last point on
- * this contour, for the control point of a quadratic curve
- * @param dy1 The amount to add to the y-coordinate of the last point on
- * this contour, for the control point of a quadratic curve
- * @param dx2 The amount to add to the x-coordinate of the last point on
- * this contour, for the end point of a quadratic curve
- * @param dy2 The amount to add to the y-coordinate of the last point on
- * this contour, for the end point of a quadratic curve
- */
- public void rQuadTo(float dx1, float dy1, float dx2, float dy2) {
- if (!hasPoints()) {
- mPath.moveTo(mLastX = 0, mLastY = 0);
- }
- dx1 += mLastX;
- dy1 += mLastY;
- dx2 += mLastX;
- dy2 += mLastY;
- mPath.quadTo(dx1, dy1, mLastX = dx2, mLastY = dy2);
- }
-
- /**
- * Add a cubic bezier from the last point, approaching control points
- * (x1,y1) and (x2,y2), and ending at (x3,y3). If no moveTo() call has been
- * made for this contour, the first point is automatically set to (0,0).
- *
- * @param x1 The x-coordinate of the 1st control point on a cubic curve
- * @param y1 The y-coordinate of the 1st control point on a cubic curve
- * @param x2 The x-coordinate of the 2nd control point on a cubic curve
- * @param y2 The y-coordinate of the 2nd control point on a cubic curve
- * @param x3 The x-coordinate of the end point on a cubic curve
- * @param y3 The y-coordinate of the end point on a cubic curve
- */
- public void cubicTo(float x1, float y1, float x2, float y2,
- float x3, float y3) {
- if (!hasPoints()) {
- mPath.moveTo(0, 0);
- }
- mPath.curveTo(x1, y1, x2, y2, mLastX = x3, mLastY = y3);
- }
-
- /**
- * Same as cubicTo, but the coordinates are considered relative to the
- * current point on this contour. If there is no previous point, then a
- * moveTo(0,0) is inserted automatically.
- */
- public void rCubicTo(float dx1, float dy1, float dx2, float dy2,
- float dx3, float dy3) {
- if (!hasPoints()) {
- mPath.moveTo(mLastX = 0, mLastY = 0);
- }
- dx1 += mLastX;
- dy1 += mLastY;
- dx2 += mLastX;
- dy2 += mLastY;
- dx3 += mLastX;
- dy3 += mLastY;
- mPath.curveTo(dx1, dy1, dx2, dy2, mLastX = dx3, mLastY = dy3);
- }
-
- /**
- * 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 tread mod 360.
- *
- * @param left The left of oval defining shape and size of the arc
- * @param top The top of oval defining shape and size of the arc
- * @param right The right of oval defining shape and size of the arc
- * @param bottom The bottom of oval defining shape and size of the arc
- * @param startAngle Starting angle (in degrees) where the arc begins
- * @param sweepAngle Sweep angle (in degrees) measured clockwise, treated
- * mod 360.
- * @param forceMoveTo If true, always begin a new contour with the arc
- */
- public void arcTo(float left, float top, float right, float bottom, float startAngle,
- float sweepAngle,
- boolean forceMoveTo) {
- Arc2D arc = new Arc2D.Float(left, top, right - left, bottom - top, -startAngle,
- -sweepAngle, Arc2D.OPEN);
- mPath.append(arc, true /*connect*/);
-
- resetLastPointFromPath();
- }
-
- /**
- * Close the current contour. If the current point is not equal to the
- * first point of the contour, a line segment is automatically added.
- */
- public void close() {
- mPath.closePath();
- }
-
- private void resetLastPointFromPath() {
- Point2D last = mPath.getCurrentPoint();
- mLastX = (float) last.getX();
- mLastY = (float) last.getY();
- }
-
- /**
- * Add a closed rectangle contour to the path
- *
- * @param left The left side of a rectangle to add to the path
- * @param top The top of a rectangle to add to the path
- * @param right The right side of a rectangle to add to the path
- * @param bottom The bottom of a rectangle to add to the path
- * @param dir The direction to wind the rectangle's contour
- */
- public void addRect(float left, float top, float right, float bottom,
- int dir) {
- moveTo(left, top);
-
- Direction direction = getDirection(dir);
-
- switch (direction) {
- case CW:
- lineTo(right, top);
- lineTo(right, bottom);
- lineTo(left, bottom);
- break;
- case CCW:
- lineTo(left, bottom);
- lineTo(right, bottom);
- lineTo(right, top);
- break;
- }
-
- close();
-
- resetLastPointFromPath();
- }
-
- /**
- * Offset the path by (dx,dy), returning true on success
- *
- * @param dx The amount in the X direction to offset the entire path
- * @param dy The amount in the Y direction to offset the entire path
- */
- public void offset(float dx, float dy) {
- GeneralPath newPath = new GeneralPath();
-
- PathIterator iterator = mPath.getPathIterator(new AffineTransform(0, 0, dx, 0, 0, dy));
-
- newPath.append(iterator, false /*connect*/);
- mPath = newPath;
- }
-
- /**
- * Transform the points in this path by matrix, and write the answer
- * into dst. If dst is null, then the the original path is modified.
- *
- * @param matrix The matrix to apply to the path
- * @param dst The transformed path is written here. If dst is null,
- * then the the original path is modified
- */
- public void transform(Matrix_Delegate matrix, Path_Delegate dst) {
- if (matrix.hasPerspective()) {
- assert false;
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_AFFINE,
- "android.graphics.Path#transform() only " +
- "supports affine transformations.", null, null /*data*/);
- }
-
- GeneralPath newPath = new GeneralPath();
-
- PathIterator iterator = mPath.getPathIterator(matrix.getAffineTransform());
-
- newPath.append(iterator, false /*connect*/);
-
- if (dst != null) {
- dst.mPath = newPath;
- } else {
- mPath = newPath;
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java
deleted file mode 100644
index ff3f19f3f7429..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/PorterDuffColorFilter_Delegate.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.PorterDuff.Mode;
-
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-
-import static com.android.layoutlib.bridge.impl.PorterDuffUtility.getComposite;
-import static com.android.layoutlib.bridge.impl.PorterDuffUtility.getPorterDuffMode;
-
-/**
- * Delegate implementing the native methods of android.graphics.PorterDuffColorFilter
- *
- * Through the layoutlib_create tool, the original native methods of PorterDuffColorFilter have
- * been replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original PorterDuffColorFilter class.
- *
- * Because this extends {@link ColorFilter_Delegate}, there's no need to use a
- * {@link DelegateManager}, as all the Shader classes will be added to the manager
- * owned by {@link ColorFilter_Delegate}.
- *
- * @see ColorFilter_Delegate
- *
- */
-public class PorterDuffColorFilter_Delegate extends ColorFilter_Delegate {
-
- // ---- delegate data ----
-
- private final java.awt.Color mSrcColor;
- private final Mode mMode;
-
-
- // ---- Public Helper methods ----
-
- @Override
- public boolean isSupported() {
- return true;
- }
-
- @Override
- public String getSupportMessage() {
- return "PorterDuff Color Filter is not supported for mode: " + mMode.name() + ".";
- }
-
- @Override
- public void applyFilter(Graphics2D g, int width, int height) {
- g.setComposite(getComposite(mMode, 0xFF));
- g.setColor(mSrcColor);
- g.fillRect(0, 0, width, height);
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long native_CreatePorterDuffFilter(int srcColor, int porterDuffMode) {
- PorterDuffColorFilter_Delegate newDelegate =
- new PorterDuffColorFilter_Delegate(srcColor, porterDuffMode);
- return sManager.addNewDelegate(newDelegate);
- }
-
-
- // ---- Private delegate/helper methods ----
-
- private PorterDuffColorFilter_Delegate(int srcColor, int mode) {
- mSrcColor = new java.awt.Color(srcColor, true /* hasAlpha */);
- mMode = getCompatibleMode(getPorterDuffMode(mode));
- }
-
- // For filtering the colors, the src image should contain the "color" only for pixel values
- // which are not transparent in the target image. But, we are using a simple rectangular image
- // completely filled with color. Hence some Composite rules do not apply as intended. However,
- // in such cases, they can usually be mapped to some other mode, which produces an approximately
- // equivalent result.
- private Mode getCompatibleMode(Mode mode) {
- Mode m = mode;
- // Modes that are directly supported:
- // CLEAR, DST, SRC_IN, DST_IN, DST_OUT, SRC_ATOP, DARKEN, LIGHTEN, MULTIPLY, SCREEN,
- // ADD, OVERLAY
- switch (mode) {
- // Modes that can be mapped to one of the supported modes.
- case SRC:
- m = Mode.SRC_IN;
- break;
- case SRC_OVER:
- m = Mode.SRC_ATOP;
- break;
- case DST_OVER:
- m = Mode.DST;
- break;
- case SRC_OUT:
- m = Mode.CLEAR;
- break;
- case DST_ATOP:
- m = Mode.DST_IN;
- break;
- case XOR:
- m = Mode.DST_OUT;
- break;
- }
- return m;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
deleted file mode 100644
index b5ba46830a252..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Shader.TileMode;
-
-import java.awt.image.ColorModel;
-
-/**
- * Delegate implementing the native methods of android.graphics.RadialGradient
- *
- * Through the layoutlib_create tool, the original native methods of RadialGradient have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original RadialGradient class.
- *
- * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
- *
- * @see Shader_Delegate
- *
- */
-public class RadialGradient_Delegate extends Gradient_Delegate {
-
- // ---- delegate data ----
- private java.awt.Paint mJavaPaint;
-
- // ---- Public Helper methods ----
-
- @Override
- public java.awt.Paint getJavaPaint() {
- return mJavaPaint;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate1(long matrix, float x, float y, float radius,
- int colors[], float positions[], int tileMode) {
- RadialGradient_Delegate newDelegate = new RadialGradient_Delegate(matrix, x, y, radius,
- colors, positions, Shader_Delegate.getTileMode(tileMode));
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate2(long matrix, float x, float y, float radius,
- int color0, int color1, int tileMode) {
- return nativeCreate1(matrix, x, y, radius, new int[] { color0, color1 },
- null /*positions*/, tileMode);
- }
-
- // ---- Private delegate/helper methods ----
-
- /**
- * Create a shader that draws a radial gradient given the center and radius.
- *
- * @param nativeMatrix reference to the shader's native transformation matrix
- * @param x The x-coordinate of the center of the radius
- * @param y The y-coordinate of the center of the radius
- * @param radius Must be positive. The radius of the circle for this
- * gradient
- * @param colors The colors to be distributed between the center and edge of
- * the circle
- * @param positions May be NULL. 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.
- * @param tile The Shader tiling mode
- */
- private RadialGradient_Delegate(long nativeMatrix, float x, float y, float radius,
- int colors[], float positions[], TileMode tile) {
- super(nativeMatrix, colors, positions);
- mJavaPaint = new RadialGradientPaint(x, y, radius, mColors, mPositions, tile);
- }
-
- private class RadialGradientPaint extends GradientPaint {
-
- private final float mX;
- private final float mY;
- private final float mRadius;
-
- public RadialGradientPaint(float x, float y, float radius,
- int[] colors, float[] positions, TileMode mode) {
- super(colors, positions, mode);
- mX = x;
- mY = y;
- mRadius = radius;
- }
-
- @Override
- public java.awt.PaintContext createContext(
- java.awt.image.ColorModel colorModel,
- java.awt.Rectangle deviceBounds,
- java.awt.geom.Rectangle2D userBounds,
- java.awt.geom.AffineTransform xform,
- java.awt.RenderingHints hints) {
- precomputeGradientColors();
-
- java.awt.geom.AffineTransform canvasMatrix;
- try {
- canvasMatrix = xform.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in RadialGradient", e, null /*data*/);
- canvasMatrix = new java.awt.geom.AffineTransform();
- }
-
- java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
- try {
- localMatrix = localMatrix.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in RadialGradient", e, null /*data*/);
- localMatrix = new java.awt.geom.AffineTransform();
- }
-
- return new RadialGradientPaintContext(canvasMatrix, localMatrix, colorModel);
- }
-
- private class RadialGradientPaintContext implements java.awt.PaintContext {
-
- private final java.awt.geom.AffineTransform mCanvasMatrix;
- private final java.awt.geom.AffineTransform mLocalMatrix;
- private final java.awt.image.ColorModel mColorModel;
-
- public RadialGradientPaintContext(
- java.awt.geom.AffineTransform canvasMatrix,
- java.awt.geom.AffineTransform localMatrix,
- java.awt.image.ColorModel colorModel) {
- mCanvasMatrix = canvasMatrix;
- mLocalMatrix = localMatrix;
- mColorModel = colorModel.hasAlpha() ? colorModel : ColorModel.getRGBdefault();
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public java.awt.image.ColorModel getColorModel() {
- return mColorModel;
- }
-
- @Override
- public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
- java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
- mColorModel, mColorModel.createCompatibleWritableRaster(w, h),
- mColorModel.isAlphaPremultiplied(), null);
-
- int[] data = new int[w*h];
-
- // compute distance from each point to the center, and figure out the distance from
- // it.
- int index = 0;
- float[] pt1 = new float[2];
- float[] pt2 = new float[2];
- for (int iy = 0 ; iy < h ; iy++) {
- for (int ix = 0 ; ix < w ; ix++) {
- // handle the canvas transform
- pt1[0] = x + ix;
- pt1[1] = y + iy;
- mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
-
- // handle the local matrix
- pt1[0] = pt2[0] - mX;
- pt1[1] = pt2[1] - mY;
- mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
-
- float _x = pt2[0];
- float _y = pt2[1];
- float distance = (float) Math.hypot(_x, _y);
-
- data[index++] = getGradientColor(distance / mRadius);
- }
- }
-
- image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
- return image.getRaster();
- }
-
- }
- }
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
deleted file mode 100644
index edb7025b7cd73..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
+++ /dev/null
@@ -1,483 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.os.Parcel;
-
-import java.awt.Rectangle;
-import java.awt.Shape;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Area;
-import java.awt.geom.Rectangle2D;
-
-/**
- * Delegate implementing the native methods of android.graphics.Region
- *
- * Through the layoutlib_create tool, the original native methods of Region have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Region class.
- *
- * This also serve as a base class for all Region delegate classes.
- *
- * @see DelegateManager
- *
- */
-public class Region_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(Region_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
- private Area mArea = new Area();
-
- // ---- Public Helper methods ----
-
- public static Region_Delegate getDelegate(long nativeShader) {
- return sManager.getDelegate(nativeShader);
- }
-
- public Area getJavaArea() {
- return mArea;
- }
-
- /**
- * Combines two {@link Shape} into another one (actually an {@link Area}), according
- * to the given {@link Region.Op}.
- *
- * If the Op is not one that combines two shapes, then this return null
- *
- * @param shape1 the firt shape to combine which can be null if there's no original clip.
- * @param shape2 the 2nd shape to combine
- * @param regionOp the operande for the combine
- * @return a new area or null.
- */
- public static Area combineShapes(Shape shape1, Shape shape2, int regionOp) {
- if (regionOp == Region.Op.DIFFERENCE.nativeInt) {
- // if shape1 is null (empty), then the result is null.
- if (shape1 == null) {
- return null;
- }
-
- // result is always a new area.
- Area result = new Area(shape1);
- result.subtract(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
- return result;
-
- } else if (regionOp == Region.Op.INTERSECT.nativeInt) {
- // if shape1 is null, then the result is simply shape2.
- if (shape1 == null) {
- return new Area(shape2);
- }
-
- // result is always a new area.
- Area result = new Area(shape1);
- result.intersect(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
- return result;
-
- } else if (regionOp == Region.Op.UNION.nativeInt) {
- // if shape1 is null, then the result is simply shape2.
- if (shape1 == null) {
- return new Area(shape2);
- }
-
- // result is always a new area.
- Area result = new Area(shape1);
- result.add(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
- return result;
-
- } else if (regionOp == Region.Op.XOR.nativeInt) {
- // if shape1 is null, then the result is simply shape2
- if (shape1 == null) {
- return new Area(shape2);
- }
-
- // result is always a new area.
- Area result = new Area(shape1);
- result.exclusiveOr(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
- return result;
-
- } else if (regionOp == Region.Op.REVERSE_DIFFERENCE.nativeInt) {
- // result is always a new area.
- Area result = new Area(shape2);
-
- if (shape1 != null) {
- result.subtract(shape1 instanceof Area ? (Area) shape1 : new Area(shape1));
- }
-
- return result;
- }
-
- return null;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static boolean isEmpty(Region thisRegion) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return true;
- }
-
- return regionDelegate.mArea.isEmpty();
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean isRect(Region thisRegion) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return true;
- }
-
- return regionDelegate.mArea.isRectangular();
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean isComplex(Region thisRegion) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return true;
- }
-
- return regionDelegate.mArea.isSingular() == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean contains(Region thisRegion, int x, int y) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return false;
- }
-
- return regionDelegate.mArea.contains(x, y);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean quickContains(Region thisRegion,
- int left, int top, int right, int bottom) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return false;
- }
-
- return regionDelegate.mArea.isRectangular() &&
- regionDelegate.mArea.contains(left, top, right - left, bottom - top);
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean quickReject(Region thisRegion,
- int left, int top, int right, int bottom) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return false;
- }
-
- return regionDelegate.mArea.isEmpty() ||
- regionDelegate.mArea.intersects(left, top, right - left, bottom - top) == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean quickReject(Region thisRegion, Region rgn) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return false;
- }
-
- Region_Delegate targetRegionDelegate = sManager.getDelegate(rgn.mNativeRegion);
- if (targetRegionDelegate == null) {
- return false;
- }
-
- return regionDelegate.mArea.isEmpty() ||
- regionDelegate.mArea.getBounds().intersects(
- targetRegionDelegate.mArea.getBounds()) == false;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static void translate(Region thisRegion, int dx, int dy, Region dst) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return;
- }
-
- Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
- if (targetRegionDelegate == null) {
- return;
- }
-
- if (regionDelegate.mArea.isEmpty()) {
- targetRegionDelegate.mArea = new Area();
- } else {
- targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
- AffineTransform mtx = new AffineTransform();
- mtx.translate(dx, dy);
- targetRegionDelegate.mArea.transform(mtx);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static void scale(Region thisRegion, float scale, Region dst) {
- Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
- if (regionDelegate == null) {
- return;
- }
-
- Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
- if (targetRegionDelegate == null) {
- return;
- }
-
- if (regionDelegate.mArea.isEmpty()) {
- targetRegionDelegate.mArea = new Area();
- } else {
- targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
- AffineTransform mtx = new AffineTransform();
- mtx.scale(scale, scale);
- targetRegionDelegate.mArea.transform(mtx);
- }
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeConstructor() {
- Region_Delegate newDelegate = new Region_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeDestructor(long native_region) {
- sManager.removeJavaReferenceFor(native_region);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetRegion(long native_dst, long native_src) {
- Region_Delegate dstRegion = sManager.getDelegate(native_dst);
- if (dstRegion == null) {
- return;
- }
-
- Region_Delegate srcRegion = sManager.getDelegate(native_src);
- if (srcRegion == null) {
- return;
- }
-
- dstRegion.mArea.reset();
- dstRegion.mArea.add(srcRegion.mArea);
-
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeSetRect(long native_dst,
- int left, int top, int right, int bottom) {
- Region_Delegate dstRegion = sManager.getDelegate(native_dst);
- if (dstRegion == null) {
- return true;
- }
-
- dstRegion.mArea = new Area(new Rectangle2D.Float(left, top, right - left, bottom - top));
- return dstRegion.mArea.getBounds().isEmpty() == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeSetPath(long native_dst, long native_path, long native_clip) {
- Region_Delegate dstRegion = sManager.getDelegate(native_dst);
- if (dstRegion == null) {
- return true;
- }
-
- Path_Delegate path = Path_Delegate.getDelegate(native_path);
- if (path == null) {
- return true;
- }
-
- dstRegion.mArea = new Area(path.getJavaShape());
-
- Region_Delegate clip = sManager.getDelegate(native_clip);
- if (clip != null) {
- dstRegion.mArea.subtract(clip.getJavaArea());
- }
-
- return dstRegion.mArea.getBounds().isEmpty() == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeGetBounds(long native_region, Rect rect) {
- Region_Delegate region = sManager.getDelegate(native_region);
- if (region == null) {
- return true;
- }
-
- Rectangle bounds = region.mArea.getBounds();
- if (bounds.isEmpty()) {
- rect.left = rect.top = rect.right = rect.bottom = 0;
- return false;
- }
-
- rect.left = bounds.x;
- rect.top = bounds.y;
- rect.right = bounds.x + bounds.width;
- rect.bottom = bounds.y + bounds.height;
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeGetBoundaryPath(long native_region, long native_path) {
- Region_Delegate region = sManager.getDelegate(native_region);
- if (region == null) {
- return false;
- }
-
- Path_Delegate path = Path_Delegate.getDelegate(native_path);
- if (path == null) {
- return false;
- }
-
- if (region.mArea.isEmpty()) {
- path.reset();
- return false;
- }
-
- path.setPathIterator(region.mArea.getPathIterator(new AffineTransform()));
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeOp(long native_dst,
- int left, int top, int right, int bottom, int op) {
- Region_Delegate region = sManager.getDelegate(native_dst);
- if (region == null) {
- return false;
- }
-
- region.mArea = combineShapes(region.mArea,
- new Rectangle2D.Float(left, top, right - left, bottom - top), op);
-
- assert region.mArea != null;
- if (region.mArea != null) {
- region.mArea = new Area();
- }
-
- return region.mArea.getBounds().isEmpty() == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeOp(long native_dst, Rect rect, long native_region, int op) {
- Region_Delegate region = sManager.getDelegate(native_dst);
- if (region == null) {
- return false;
- }
-
- region.mArea = combineShapes(region.mArea,
- new Rectangle2D.Float(rect.left, rect.top, rect.width(), rect.height()), op);
-
- assert region.mArea != null;
- if (region.mArea != null) {
- region.mArea = new Area();
- }
-
- return region.mArea.getBounds().isEmpty() == false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeOp(long native_dst,
- long native_region1, long native_region2, int op) {
- Region_Delegate dstRegion = sManager.getDelegate(native_dst);
- if (dstRegion == null) {
- return true;
- }
-
- Region_Delegate region1 = sManager.getDelegate(native_region1);
- if (region1 == null) {
- return false;
- }
-
- Region_Delegate region2 = sManager.getDelegate(native_region2);
- if (region2 == null) {
- return false;
- }
-
- dstRegion.mArea = combineShapes(region1.mArea, region2.mArea, op);
-
- assert dstRegion.mArea != null;
- if (dstRegion.mArea != null) {
- dstRegion.mArea = new Area();
- }
-
- return dstRegion.mArea.getBounds().isEmpty() == false;
-
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreateFromParcel(Parcel p) {
- // This is only called by Region.CREATOR (Parcelable.Creator), which is only
- // used during aidl call so really this should not be called.
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "AIDL is not suppored, and therefore Regions cannot be created from parcels.",
- null /*data*/);
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeWriteToParcel(long native_region,
- Parcel p) {
- // This is only called when sending a region through aidl, so really this should not
- // be called.
- Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
- "AIDL is not suppored, and therefore Regions cannot be written to parcels.",
- null /*data*/);
- return false;
- }
-
- @LayoutlibDelegate
- /*package*/ static boolean nativeEquals(long native_r1, long native_r2) {
- Region_Delegate region1 = sManager.getDelegate(native_r1);
- if (region1 == null) {
- return false;
- }
-
- Region_Delegate region2 = sManager.getDelegate(native_r2);
- if (region2 == null) {
- return false;
- }
-
- return region1.mArea.equals(region2.mArea);
- }
-
- @LayoutlibDelegate
- /*package*/ static String nativeToString(long native_region) {
- Region_Delegate region = sManager.getDelegate(native_region);
- if (region == null) {
- return "not found";
- }
-
- return region.mArea.toString();
- }
-
- // ---- Private delegate/helper methods ----
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/RoundRectangle.java b/tools/layoutlib/bridge/src/android/graphics/RoundRectangle.java
deleted file mode 100644
index 736f03ec5a8c6..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/RoundRectangle.java
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import java.awt.geom.AffineTransform;
-import java.awt.geom.PathIterator;
-import java.awt.geom.Rectangle2D;
-import java.awt.geom.RectangularShape;
-import java.awt.geom.RoundRectangle2D;
-import java.util.EnumSet;
-import java.util.NoSuchElementException;
-
-/**
- * Defines a rectangle with rounded corners, where the sizes of the corners
- * are potentially different.
- */
-public class RoundRectangle extends RectangularShape {
- public double x;
- public double y;
- public double width;
- public double height;
- public double ulWidth;
- public double ulHeight;
- public double urWidth;
- public double urHeight;
- public double lrWidth;
- public double lrHeight;
- public double llWidth;
- public double llHeight;
-
- private enum Zone {
- CLOSE_OUTSIDE,
- CLOSE_INSIDE,
- MIDDLE,
- FAR_INSIDE,
- FAR_OUTSIDE
- }
-
- private final EnumSet close = EnumSet.of(Zone.CLOSE_OUTSIDE, Zone.CLOSE_INSIDE);
- private final EnumSet far = EnumSet.of(Zone.FAR_OUTSIDE, Zone.FAR_INSIDE);
-
- /**
- * @param cornerDimensions array of 8 floating-point number corresponding to the width and
- * the height of each corner in the following order: upper-left, upper-right, lower-right,
- * lower-left. It assumes for the size the same convention as {@link RoundRectangle2D}, that
- * is that the width and height of a corner correspond to the total width and height of the
- * ellipse that corner is a quarter of.
- */
- public RoundRectangle(float x, float y, float width, float height, float[] cornerDimensions) {
- assert cornerDimensions.length == 8 : "The array of corner dimensions must have eight " +
- "elements";
-
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
-
- float[] dimensions = cornerDimensions.clone();
- // If a value is negative, the corresponding corner is squared
- for (int i = 0; i < dimensions.length; i += 2) {
- if (dimensions[i] < 0 || dimensions[i + 1] < 0) {
- dimensions[i] = 0;
- dimensions[i + 1] = 0;
- }
- }
-
- double topCornerWidth = (dimensions[0] + dimensions[2]) / 2d;
- double bottomCornerWidth = (dimensions[4] + dimensions[6]) / 2d;
- double leftCornerHeight = (dimensions[1] + dimensions[7]) / 2d;
- double rightCornerHeight = (dimensions[3] + dimensions[5]) / 2d;
-
- // Rescale the corner dimensions if they are bigger than the rectangle
- double scale = Math.min(1.0, width / topCornerWidth);
- scale = Math.min(scale, width / bottomCornerWidth);
- scale = Math.min(scale, height / leftCornerHeight);
- scale = Math.min(scale, height / rightCornerHeight);
-
- this.ulWidth = dimensions[0] * scale;
- this.ulHeight = dimensions[1] * scale;
- this.urWidth = dimensions[2] * scale;
- this.urHeight = dimensions[3] * scale;
- this.lrWidth = dimensions[4] * scale;
- this.lrHeight = dimensions[5] * scale;
- this.llWidth = dimensions[6] * scale;
- this.llHeight = dimensions[7] * scale;
- }
-
- @Override
- public double getX() {
- return x;
- }
-
- @Override
- public double getY() {
- return y;
- }
-
- @Override
- public double getWidth() {
- return width;
- }
-
- @Override
- public double getHeight() {
- return height;
- }
-
- @Override
- public boolean isEmpty() {
- return (width <= 0d) || (height <= 0d);
- }
-
- @Override
- public void setFrame(double x, double y, double w, double h) {
- this.x = x;
- this.y = y;
- this.width = w;
- this.height = h;
- }
-
- @Override
- public Rectangle2D getBounds2D() {
- return new Rectangle2D.Double(x, y, width, height);
- }
-
- @Override
- public boolean contains(double x, double y) {
- if (isEmpty()) {
- return false;
- }
-
- double x0 = getX();
- double y0 = getY();
- double x1 = x0 + getWidth();
- double y1 = y0 + getHeight();
- // Check for trivial rejection - point is outside bounding rectangle
- if (x < x0 || y < y0 || x >= x1 || y >= y1) {
- return false;
- }
-
- double insideTopX0 = x0 + ulWidth / 2d;
- double insideLeftY0 = y0 + ulHeight / 2d;
- if (x < insideTopX0 && y < insideLeftY0) {
- // In the upper-left corner
- return isInsideCorner(x - insideTopX0, y - insideLeftY0, ulWidth / 2d, ulHeight / 2d);
- }
-
- double insideTopX1 = x1 - urWidth / 2d;
- double insideRightY0 = y0 + urHeight / 2d;
- if (x > insideTopX1 && y < insideRightY0) {
- // In the upper-right corner
- return isInsideCorner(x - insideTopX1, y - insideRightY0, urWidth / 2d, urHeight / 2d);
- }
-
- double insideBottomX1 = x1 - lrWidth / 2d;
- double insideRightY1 = y1 - lrHeight / 2d;
- if (x > insideBottomX1 && y > insideRightY1) {
- // In the lower-right corner
- return isInsideCorner(x - insideBottomX1, y - insideRightY1, lrWidth / 2d,
- lrHeight / 2d);
- }
-
- double insideBottomX0 = x0 + llWidth / 2d;
- double insideLeftY1 = y1 - llHeight / 2d;
- if (x < insideBottomX0 && y > insideLeftY1) {
- // In the lower-left corner
- return isInsideCorner(x - insideBottomX0, y - insideLeftY1, llWidth / 2d,
- llHeight / 2d);
- }
-
- // In the central part of the rectangle
- return true;
- }
-
- private boolean isInsideCorner(double x, double y, double width, double height) {
- double squareDist = height * height * x * x + width * width * y * y;
- return squareDist <= width * width * height * height;
- }
-
- private Zone classify(double coord, double side1, double arcSize1, double side2,
- double arcSize2) {
- if (coord < side1) {
- return Zone.CLOSE_OUTSIDE;
- } else if (coord < side1 + arcSize1) {
- return Zone.CLOSE_INSIDE;
- } else if (coord < side2 - arcSize2) {
- return Zone.MIDDLE;
- } else if (coord < side2) {
- return Zone.FAR_INSIDE;
- } else {
- return Zone.FAR_OUTSIDE;
- }
- }
-
- public boolean intersects(double x, double y, double w, double h) {
- if (isEmpty() || w <= 0 || h <= 0) {
- return false;
- }
- double x0 = getX();
- double y0 = getY();
- double x1 = x0 + getWidth();
- double y1 = y0 + getHeight();
- // Check for trivial rejection - bounding rectangles do not intersect
- if (x + w <= x0 || x >= x1 || y + h <= y0 || y >= y1) {
- return false;
- }
-
- double maxLeftCornerWidth = Math.max(ulWidth, llWidth) / 2d;
- double maxRightCornerWidth = Math.max(urWidth, lrWidth) / 2d;
- double maxUpperCornerHeight = Math.max(ulHeight, urHeight) / 2d;
- double maxLowerCornerHeight = Math.max(llHeight, lrHeight) / 2d;
- Zone x0class = classify(x, x0, maxLeftCornerWidth, x1, maxRightCornerWidth);
- Zone x1class = classify(x + w, x0, maxLeftCornerWidth, x1, maxRightCornerWidth);
- Zone y0class = classify(y, y0, maxUpperCornerHeight, y1, maxLowerCornerHeight);
- Zone y1class = classify(y + h, y0, maxUpperCornerHeight, y1, maxLowerCornerHeight);
-
- // Trivially accept if any point is inside inner rectangle
- if (x0class == Zone.MIDDLE || x1class == Zone.MIDDLE || y0class == Zone.MIDDLE || y1class == Zone.MIDDLE) {
- return true;
- }
- // Trivially accept if either edge spans inner rectangle
- if ((close.contains(x0class) && far.contains(x1class)) || (close.contains(y0class) &&
- far.contains(y1class))) {
- return true;
- }
-
- // Since neither edge spans the center, then one of the corners
- // must be in one of the rounded edges. We detect this case if
- // a [xy]0class is 3 or a [xy]1class is 1. One of those two cases
- // must be true for each direction.
- // We now find a "nearest point" to test for being inside a rounded
- // corner.
- if (x1class == Zone.CLOSE_INSIDE && y1class == Zone.CLOSE_INSIDE) {
- // Potentially in upper-left corner
- x = x + w - x0 - ulWidth / 2d;
- y = y + h - y0 - ulHeight / 2d;
- return x > 0 || y > 0 || isInsideCorner(x, y, ulWidth / 2d, ulHeight / 2d);
- }
- if (x1class == Zone.CLOSE_INSIDE) {
- // Potentially in lower-left corner
- x = x + w - x0 - llWidth / 2d;
- y = y - y1 + llHeight / 2d;
- return x > 0 || y < 0 || isInsideCorner(x, y, llWidth / 2d, llHeight / 2d);
- }
- if (y1class == Zone.CLOSE_INSIDE) {
- //Potentially in the upper-right corner
- x = x - x1 + urWidth / 2d;
- y = y + h - y0 - urHeight / 2d;
- return x < 0 || y > 0 || isInsideCorner(x, y, urWidth / 2d, urHeight / 2d);
- }
- // Potentially in the lower-right corner
- x = x - x1 + lrWidth / 2d;
- y = y - y1 + lrHeight / 2d;
- return x < 0 || y < 0 || isInsideCorner(x, y, lrWidth / 2d, lrHeight / 2d);
- }
-
- @Override
- public boolean contains(double x, double y, double w, double h) {
- if (isEmpty() || w <= 0 || h <= 0) {
- return false;
- }
- return (contains(x, y) &&
- contains(x + w, y) &&
- contains(x, y + h) &&
- contains(x + w, y + h));
- }
-
- @Override
- public PathIterator getPathIterator(final AffineTransform at) {
- return new PathIterator() {
- int index;
-
- // ArcIterator.btan(Math.PI/2)
- public static final double CtrlVal = 0.5522847498307933;
- private final double ncv = 1.0 - CtrlVal;
-
- // Coordinates of control points for Bezier curves approximating the straight lines
- // and corners of the rounded rectangle.
- private final double[][] ctrlpts = {
- {0.0, 0.0, 0.0, ulHeight},
- {0.0, 0.0, 1.0, -llHeight},
- {0.0, 0.0, 1.0, -llHeight * ncv, 0.0, ncv * llWidth, 1.0, 0.0, 0.0, llWidth,
- 1.0, 0.0},
- {1.0, -lrWidth, 1.0, 0.0},
- {1.0, -lrWidth * ncv, 1.0, 0.0, 1.0, 0.0, 1.0, -lrHeight * ncv, 1.0, 0.0, 1.0,
- -lrHeight},
- {1.0, 0.0, 0.0, urHeight},
- {1.0, 0.0, 0.0, ncv * urHeight, 1.0, -urWidth * ncv, 0.0, 0.0, 1.0, -urWidth,
- 0.0, 0.0},
- {0.0, ulWidth, 0.0, 0.0},
- {0.0, ncv * ulWidth, 0.0, 0.0, 0.0, 0.0, 0.0, ncv * ulHeight, 0.0, 0.0, 0.0,
- ulHeight},
- {}
- };
- private final int[] types = {
- SEG_MOVETO,
- SEG_LINETO, SEG_CUBICTO,
- SEG_LINETO, SEG_CUBICTO,
- SEG_LINETO, SEG_CUBICTO,
- SEG_LINETO, SEG_CUBICTO,
- SEG_CLOSE,
- };
-
- @Override
- public int getWindingRule() {
- return WIND_NON_ZERO;
- }
-
- @Override
- public boolean isDone() {
- return index >= ctrlpts.length;
- }
-
- @Override
- public void next() {
- index++;
- }
-
- @Override
- public int currentSegment(float[] coords) {
- if (isDone()) {
- throw new NoSuchElementException("roundrect iterator out of bounds");
- }
- int nc = 0;
- double ctrls[] = ctrlpts[index];
- for (int i = 0; i < ctrls.length; i += 4) {
- coords[nc++] = (float) (x + ctrls[i] * width + ctrls[i + 1] / 2d);
- coords[nc++] = (float) (y + ctrls[i + 2] * height + ctrls[i + 3] / 2d);
- }
- if (at != null) {
- at.transform(coords, 0, coords, 0, nc / 2);
- }
- return types[index];
- }
-
- @Override
- public int currentSegment(double[] coords) {
- if (isDone()) {
- throw new NoSuchElementException("roundrect iterator out of bounds");
- }
- int nc = 0;
- double ctrls[] = ctrlpts[index];
- for (int i = 0; i < ctrls.length; i += 4) {
- coords[nc++] = x + ctrls[i] * width + ctrls[i + 1] / 2d;
- coords[nc++] = y + ctrls[i + 2] * height + ctrls[i + 3] / 2d;
- }
- if (at != null) {
- at.transform(coords, 0, coords, 0, nc / 2);
- }
- return types[index];
- }
- };
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java
deleted file mode 100644
index 5b750899392c2..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Shader_Delegate.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Shader.TileMode;
-
-/**
- * Delegate implementing the native methods of android.graphics.Shader
- *
- * Through the layoutlib_create tool, the original native methods of Shader have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Shader class.
- *
- * This also serve as a base class for all Shader delegate classes.
- *
- * @see DelegateManager
- *
- */
-public abstract class Shader_Delegate {
-
- // ---- delegate manager ----
- protected static final DelegateManager sManager =
- new DelegateManager(Shader_Delegate.class);
-
- // ---- delegate helper data ----
-
- // ---- delegate data ----
- private Matrix_Delegate mLocalMatrix = null;
-
- // ---- Public Helper methods ----
-
- public static Shader_Delegate getDelegate(long nativeShader) {
- return sManager.getDelegate(nativeShader);
- }
-
- /**
- * Returns the {@link TileMode} matching the given int.
- * @param tileMode the tile mode int value
- * @return the TileMode enum.
- */
- public static TileMode getTileMode(int tileMode) {
- for (TileMode tm : TileMode.values()) {
- if (tm.nativeInt == tileMode) {
- return tm;
- }
- }
-
- assert false;
- return TileMode.CLAMP;
- }
-
- public abstract java.awt.Paint getJavaPaint();
- public abstract boolean isSupported();
- public abstract String getSupportMessage();
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static void nativeSafeUnref(long nativeInstance) {
- sManager.removeJavaReferenceFor(nativeInstance);
- }
-
- // ---- Private delegate/helper methods ----
-
- protected Shader_Delegate(long nativeMatrix) {
- mLocalMatrix = Matrix_Delegate.getDelegate(nativeMatrix);
- }
-
- protected java.awt.geom.AffineTransform getLocalMatrix() {
- if (mLocalMatrix != null) {
- return mLocalMatrix.getAffineTransform();
- }
-
- return new java.awt.geom.AffineTransform();
- }
-
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java
deleted file mode 100644
index 6d2e9b41cc194..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/SumPathEffect_Delegate.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import java.awt.Stroke;
-
-/**
- * Delegate implementing the native methods of android.graphics.SumPathEffect
- *
- * Through the layoutlib_create tool, the original native methods of SumPathEffect have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original SumPathEffect class.
- *
- * Because this extends {@link PathEffect_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link PathEffect_Delegate}.
- *
- * @see PathEffect_Delegate
- *
- */
-public class SumPathEffect_Delegate extends PathEffect_Delegate {
-
- // ---- delegate data ----
-
- // ---- Public Helper methods ----
-
- @Override
- public Stroke getStroke(Paint_Delegate paint) {
- // FIXME
- return null;
- }
-
- @Override
- public boolean isSupported() {
- return false;
- }
-
- @Override
- public String getSupportMessage() {
- return "Sum Path Effects are not supported in Layout Preview mode.";
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate(long first, long second) {
- SumPathEffect_Delegate newDelegate = new SumPathEffect_Delegate();
- return sManager.addNewDelegate(newDelegate);
- }
-
- // ---- Private delegate/helper methods ----
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java
deleted file mode 100644
index 30152bc6b0008..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/SweepGradient_Delegate.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.graphics.SweepGradient
- *
- * Through the layoutlib_create tool, the original native methods of SweepGradient have been
- * replaced by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original SweepGradient class.
- *
- * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
- * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
- *
- * @see Shader_Delegate
- *
- */
-public class SweepGradient_Delegate extends Gradient_Delegate {
-
- // ---- delegate data ----
- private java.awt.Paint mJavaPaint;
-
- // ---- Public Helper methods ----
-
- @Override
- public java.awt.Paint getJavaPaint() {
- return mJavaPaint;
- }
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate1(long matrix, float x, float y, int colors[], float
- positions[]) {
- SweepGradient_Delegate newDelegate = new SweepGradient_Delegate(matrix, x, y, colors,
- positions);
- return sManager.addNewDelegate(newDelegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreate2(long matrix, float x, float y, int color0, int color1) {
- return nativeCreate1(matrix, x, y, new int[] { color0, color1 },
- null /*positions*/);
- }
-
- // ---- Private delegate/helper methods ----
-
- /**
- * A subclass of Shader that draws a sweep gradient around a center point.
- *
- * @param nativeMatrix reference to the shader's native transformation matrix
- * @param cx The x-coordinate of the center
- * @param cy The y-coordinate of the center
- * @param colors The colors to be distributed between around the center.
- * There must be at least 2 colors in the array.
- * @param positions May be NULL. The relative position of
- * each corresponding color in the colors array, beginning
- * with 0 and ending with 1.0. If the values are not
- * monotonic, the drawing may produce unexpected results.
- * If positions is NULL, then the colors are automatically
- * spaced evenly.
- */
- private SweepGradient_Delegate(long nativeMatrix, float cx, float cy,
- int colors[], float positions[]) {
- super(nativeMatrix, colors, positions);
- mJavaPaint = new SweepGradientPaint(cx, cy, mColors, mPositions);
- }
-
- private class SweepGradientPaint extends GradientPaint {
-
- private final float mCx;
- private final float mCy;
-
- public SweepGradientPaint(float cx, float cy, int[] colors,
- float[] positions) {
- super(colors, positions, null /*tileMode*/);
- mCx = cx;
- mCy = cy;
- }
-
- @Override
- public java.awt.PaintContext createContext(
- java.awt.image.ColorModel colorModel,
- java.awt.Rectangle deviceBounds,
- java.awt.geom.Rectangle2D userBounds,
- java.awt.geom.AffineTransform xform,
- java.awt.RenderingHints hints) {
- precomputeGradientColors();
-
- java.awt.geom.AffineTransform canvasMatrix;
- try {
- canvasMatrix = xform.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in SweepGradient", e, null /*data*/);
- canvasMatrix = new java.awt.geom.AffineTransform();
- }
-
- java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
- try {
- localMatrix = localMatrix.createInverse();
- } catch (java.awt.geom.NoninvertibleTransformException e) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
- "Unable to inverse matrix in SweepGradient", e, null /*data*/);
- localMatrix = new java.awt.geom.AffineTransform();
- }
-
- return new SweepGradientPaintContext(canvasMatrix, localMatrix, colorModel);
- }
-
- private class SweepGradientPaintContext implements java.awt.PaintContext {
-
- private final java.awt.geom.AffineTransform mCanvasMatrix;
- private final java.awt.geom.AffineTransform mLocalMatrix;
- private final java.awt.image.ColorModel mColorModel;
-
- public SweepGradientPaintContext(
- java.awt.geom.AffineTransform canvasMatrix,
- java.awt.geom.AffineTransform localMatrix,
- java.awt.image.ColorModel colorModel) {
- mCanvasMatrix = canvasMatrix;
- mLocalMatrix = localMatrix;
- mColorModel = colorModel;
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public java.awt.image.ColorModel getColorModel() {
- return mColorModel;
- }
-
- @Override
- public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
- java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
- mColorModel, mColorModel.createCompatibleWritableRaster(w, h),
- mColorModel.isAlphaPremultiplied(), null);
-
- int[] data = new int[w*h];
-
- // compute angle from each point to the center, and figure out the distance from
- // it.
- int index = 0;
- float[] pt1 = new float[2];
- float[] pt2 = new float[2];
- for (int iy = 0 ; iy < h ; iy++) {
- for (int ix = 0 ; ix < w ; ix++) {
- // handle the canvas transform
- pt1[0] = x + ix;
- pt1[1] = y + iy;
- mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
-
- // handle the local matrix
- pt1[0] = pt2[0] - mCx;
- pt1[1] = pt2[1] - mCy;
- mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
-
- float dx = pt2[0];
- float dy = pt2[1];
-
- float angle;
- if (dx == 0) {
- angle = (float) (dy < 0 ? 3 * Math.PI / 2 : Math.PI / 2);
- } else if (dy == 0) {
- angle = (float) (dx < 0 ? Math.PI : 0);
- } else {
- angle = (float) Math.atan(dy / dx);
- if (dx > 0) {
- if (dy < 0) {
- angle += Math.PI * 2;
- }
- } else {
- angle += Math.PI;
- }
- }
-
- // convert to 0-1. value and get color
- data[index++] = getGradientColor((float) (angle / (2 * Math.PI)));
- }
- }
-
- image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
-
- return image.getRaster();
- }
-
- }
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface_Accessor.java b/tools/layoutlib/bridge/src/android/graphics/Typeface_Accessor.java
deleted file mode 100644
index ce669cba9c473..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Typeface_Accessor.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import android.annotation.NonNull;
-
-/**
- * Class allowing access to package-protected methods/fields.
- */
-public class Typeface_Accessor {
- public static boolean isSystemFont(@NonNull String fontName) {
- return Typeface.sSystemFontMap.containsKey(fontName);
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
deleted file mode 100644
index a04a32425fde5..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.NonNull;
-import android.graphics.FontFamily_Delegate.FontVariant;
-import android.graphics.fonts.FontVariationAxis;
-import android.text.FontConfig;
-
-import java.awt.Font;
-import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import static android.graphics.FontFamily_Delegate.getFontLocation;
-
-/**
- * Delegate implementing the native methods of android.graphics.Typeface
- *
- * Through the layoutlib_create tool, the original native methods of Typeface have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * This class behaves like the original native implementation, but in Java, keeping previously
- * native data into its own objects and mapping them to int that are sent back and forth between
- * it and the original Typeface class.
- *
- * @see DelegateManager
- *
- */
-public final class Typeface_Delegate {
-
- public static final String SYSTEM_FONTS = "/system/fonts/";
-
- // ---- delegate manager ----
- private static final DelegateManager sManager =
- new DelegateManager(Typeface_Delegate.class);
-
-
- // ---- delegate data ----
-
- @NonNull
- private final FontFamily_Delegate[] mFontFamilies; // the reference to FontFamily_Delegate.
- /** @see Font#getStyle() */
- private final int mStyle;
- private final int mWeight;
-
- private static long sDefaultTypeface;
-
-
- // ---- Public Helper methods ----
-
- public static Typeface_Delegate getDelegate(long nativeTypeface) {
- return sManager.getDelegate(nativeTypeface);
- }
-
- /**
- * Return a list of fonts that match the style and variant. The list is ordered according to
- * preference of fonts.
- *
- * The list may contain null when the font failed to load. If null is reached when trying to
- * render with this list of fonts, then a warning should be logged letting the user know that
- * some font failed to load.
- *
- * @param variant The variant preferred. Can only be {@link FontVariant#COMPACT} or
- * {@link FontVariant#ELEGANT}
- */
- @NonNull
- public List getFonts(FontVariant variant) {
- assert variant != FontVariant.NONE;
-
- // Calculate the required weight based on style and weight of this typeface.
- int weight = mWeight + 50 +
- ((mStyle & Font.BOLD) == 0 ? 0 : FontFamily_Delegate.BOLD_FONT_WEIGHT_DELTA);
- if (weight > 1000) {
- weight = 1000;
- } else if (weight < 100) {
- weight = 100;
- }
- final boolean isItalic = (mStyle & Font.ITALIC) != 0;
- List fonts = new ArrayList(mFontFamilies.length);
- for (int i = 0; i < mFontFamilies.length; i++) {
- FontFamily_Delegate ffd = mFontFamilies[i];
- if (ffd != null && ffd.isValid()) {
- Font font = ffd.getFont(weight, isItalic);
- if (font != null) {
- FontVariant ffdVariant = ffd.getVariant();
- if (ffdVariant == FontVariant.NONE) {
- fonts.add(font);
- continue;
- }
- // We cannot open each font and get locales supported, etc to match the fonts.
- // As a workaround, we hardcode certain assumptions like Elegant and Compact
- // always appear in pairs.
- assert i < mFontFamilies.length - 1;
- FontFamily_Delegate ffd2 = mFontFamilies[++i];
- assert ffd2 != null;
- FontVariant ffd2Variant = ffd2.getVariant();
- Font font2 = ffd2.getFont(weight, isItalic);
- assert ffd2Variant != FontVariant.NONE && ffd2Variant != ffdVariant
- && font2 != null;
- // Add the font with the matching variant to the list.
- if (variant == ffd.getVariant()) {
- fonts.add(font);
- } else {
- fonts.add(font2);
- }
- } else {
- // The FontFamily is valid but doesn't contain any matching font. This means
- // that the font failed to load. We add null to the list of fonts. Don't throw
- // the warning just yet. If this is a non-english font, we don't want to warn
- // users who are trying to render only english text.
- fonts.add(null);
- }
- }
- }
- return fonts;
- }
-
- /**
- * Clear the default typefaces when disposing bridge.
- */
- public static void resetDefaults() {
- // Sometimes this is called before the Bridge is initialized. In that case, we don't want to
- // initialize Typeface because the SDK fonts location hasn't been set.
- if (FontFamily_Delegate.getFontLocation() != null) {
- Typeface.sDefaults = null;
- }
- }
-
-
- // ---- native methods ----
-
- @LayoutlibDelegate
- /*package*/ static synchronized long nativeCreateFromTypeface(long native_instance, int style) {
- Typeface_Delegate delegate = sManager.getDelegate(native_instance);
- if (delegate == null) {
- delegate = sManager.getDelegate(sDefaultTypeface);
- }
- if (delegate == null) {
- return 0;
- }
-
- return sManager.addNewDelegate(new Typeface_Delegate(delegate.mFontFamilies, style,
- delegate.mWeight));
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreateFromTypefaceWithExactStyle(long native_instance,
- int weight, boolean italic) {
- Typeface_Delegate delegate = sManager.getDelegate(native_instance);
- if (delegate == null) {
- delegate = sManager.getDelegate(sDefaultTypeface);
- }
- if (delegate == null) {
- return 0;
- }
-
- int style = weight >= 600 ? (italic ? Typeface.BOLD_ITALIC : Typeface.BOLD) :
- (italic ? Typeface.ITALIC : Typeface.NORMAL);
- return sManager.addNewDelegate(new Typeface_Delegate(delegate.mFontFamilies, style, weight));
- }
-
- @LayoutlibDelegate
- /*package*/ static synchronized long nativeCreateFromTypefaceWithVariation(long native_instance,
- List axes) {
- long newInstance = nativeCreateFromTypeface(native_instance, 0);
-
- if (newInstance != 0) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED,
- "nativeCreateFromTypefaceWithVariation is not supported", null, null);
- }
- return newInstance;
- }
-
- @LayoutlibDelegate
- /*package*/ static synchronized int[] nativeGetSupportedAxes(long native_instance) {
- // nativeCreateFromTypefaceWithVariation is not supported so we do not keep the axes
- return null;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nativeCreateWeightAlias(long native_instance, int weight) {
- Typeface_Delegate delegate = sManager.getDelegate(native_instance);
- if (delegate == null) {
- delegate = sManager.getDelegate(sDefaultTypeface);
- }
- if (delegate == null) {
- return 0;
- }
- Typeface_Delegate weightAlias =
- new Typeface_Delegate(delegate.mFontFamilies, delegate.mStyle, weight);
- return sManager.addNewDelegate(weightAlias);
- }
-
- @LayoutlibDelegate
- /*package*/ static synchronized long nativeCreateFromArray(long[] familyArray, int weight,
- int italic) {
- FontFamily_Delegate[] fontFamilies = new FontFamily_Delegate[familyArray.length];
- for (int i = 0; i < familyArray.length; i++) {
- fontFamilies[i] = FontFamily_Delegate.getDelegate(familyArray[i]);
- }
- if (weight == Typeface.RESOLVE_BY_FONT_TABLE) {
- weight = 400;
- }
- if (italic == Typeface.RESOLVE_BY_FONT_TABLE) {
- italic = 0;
- }
- int style = weight >= 600 ? (italic == 1 ? Typeface.BOLD_ITALIC : Typeface.BOLD) :
- (italic == 1 ? Typeface.ITALIC : Typeface.NORMAL);
- Typeface_Delegate delegate = new Typeface_Delegate(fontFamilies, style, weight);
- return sManager.addNewDelegate(delegate);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeUnref(long native_instance) {
- sManager.removeJavaReferenceFor(native_instance);
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeGetStyle(long native_instance) {
- Typeface_Delegate delegate = sManager.getDelegate(native_instance);
- if (delegate == null) {
- return 0;
- }
-
- return delegate.mStyle;
- }
-
- @LayoutlibDelegate
- /*package*/ static void nativeSetDefault(long native_instance) {
- sDefaultTypeface = native_instance;
- }
-
- @LayoutlibDelegate
- /*package*/ static int nativeGetWeight(long native_instance) {
- Typeface_Delegate delegate = sManager.getDelegate(native_instance);
- if (delegate == null) {
- return 0;
- }
- return delegate.mWeight;
- }
-
- @LayoutlibDelegate
- /*package*/ static File getSystemFontConfigLocation() {
- return new File(getFontLocation());
- }
-
- @LayoutlibDelegate
- /*package*/ static FontFamily makeFamilyFromParsed(FontConfig.Family family,
- Map bufferForPath) {
- FontFamily fontFamily = new FontFamily(family.getLanguage(), family.getVariant());
- for (FontConfig.Font font : family.getFonts()) {
- String fullPathName = "/system/fonts/" + font.getFontName();
- FontFamily_Delegate.addFont(fontFamily.mBuilderPtr, fullPathName,
- font.getWeight(), font.isItalic());
- }
- fontFamily.freeze();
- return fontFamily;
- }
-
- // ---- Private delegate/helper methods ----
-
- public Typeface_Delegate(@NonNull FontFamily_Delegate[] fontFamilies, int style, int weight) {
- mFontFamilies = fontFamilies;
- mStyle = style;
- mWeight = weight;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_Delegate.java
deleted file mode 100644
index ad2c5647eef27..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_Delegate.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License") {}
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics.drawable;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.internal.view.animation.NativeInterpolatorFactoryHelper_Delegate;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.graphics.drawable.AnimatedVectorDrawable.VectorDrawableAnimatorRT;
-import android.graphics.drawable.VectorDrawable_Delegate.VFullPath_Delegate;
-import android.graphics.drawable.VectorDrawable_Delegate.VGroup_Delegate;
-import android.graphics.drawable.VectorDrawable_Delegate.VNativeObject;
-import android.graphics.drawable.VectorDrawable_Delegate.VPathRenderer_Delegate;
-
-import java.util.ArrayList;
-import java.util.function.Consumer;
-
-/**
- * Delegate used to provide new implementation of a select few methods of {@link
- * AnimatedVectorDrawable}
- *
- * Through the layoutlib_create tool, the original methods of AnimatedVectorDrawable have been
- * replaced by calls to methods of the same name in this delegate class.
- */
-@SuppressWarnings("unused")
-public class AnimatedVectorDrawable_Delegate {
- private static DelegateManager sAnimatorSets = new
- DelegateManager<>(AnimatorSetHolder.class);
- private static DelegateManager sHolders = new
- DelegateManager<>(PropertySetter.class);
-
-
- @LayoutlibDelegate
- /*package*/ static long nCreateAnimatorSet() {
- return sAnimatorSets.addNewDelegate(new AnimatorSetHolder());
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetVectorDrawableTarget(long animatorPtr, long vectorDrawablePtr) {
- // TODO: implement
- }
- @LayoutlibDelegate
- /*package*/ static void nAddAnimator(long setPtr, long propertyValuesHolder,
- long nativeInterpolator, long startDelay, long duration, int repeatCount,
- int repeatMode) {
- PropertySetter holder = sHolders.getDelegate(propertyValuesHolder);
- if (holder == null || holder.getValues() == null) {
- return;
- }
-
- ObjectAnimator animator = new ObjectAnimator();
- animator.setValues(holder.getValues());
- animator.setInterpolator(
- NativeInterpolatorFactoryHelper_Delegate.getDelegate(nativeInterpolator));
- animator.setStartDelay(startDelay);
- animator.setDuration(duration);
- animator.setRepeatCount(repeatCount);
- animator.setRepeatMode(repeatMode);
- animator.setTarget(holder);
- animator.setPropertyName(holder.getValues().getPropertyName());
-
- AnimatorSetHolder set = sAnimatorSets.getDelegate(setPtr);
- assert set != null;
- set.addAnimator(animator);
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreateGroupPropertyHolder(long nativePtr, int propertyId,
- float startValue, float endValue) {
- VGroup_Delegate group = VNativeObject.getDelegate(nativePtr);
- Consumer setter = group.getPropertySetter(propertyId);
-
- return sHolders.addNewDelegate(FloatPropertySetter.of(setter, startValue,
- endValue));
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreatePathDataPropertyHolder(long nativePtr, long startValuePtr,
- long endValuePtr) {
- Bridge.getLog().fidelityWarning(LayoutLog.TAG_UNSUPPORTED, "AnimatedVectorDrawable path " +
- "animations are not supported.", null, null);
- return 0;
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreatePathColorPropertyHolder(long nativePtr, int propertyId,
- int startValue, int endValue) {
- VFullPath_Delegate path = VNativeObject.getDelegate(nativePtr);
- Consumer setter = path.getIntPropertySetter(propertyId);
-
- return sHolders.addNewDelegate(IntPropertySetter.of(setter, startValue,
- endValue));
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreatePathPropertyHolder(long nativePtr, int propertyId,
- float startValue, float endValue) {
- VFullPath_Delegate path = VNativeObject.getDelegate(nativePtr);
- Consumer setter = path.getFloatPropertySetter(propertyId);
-
- return sHolders.addNewDelegate(FloatPropertySetter.of(setter, startValue,
- endValue));
- }
-
- @LayoutlibDelegate
- /*package*/ static long nCreateRootAlphaPropertyHolder(long nativePtr, float startValue,
- float endValue) {
- VPathRenderer_Delegate renderer = VNativeObject.getDelegate(nativePtr);
-
- return sHolders.addNewDelegate(FloatPropertySetter.of(renderer::setRootAlpha,
- startValue,
- endValue));
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetPropertyHolderData(long nativePtr, float[] data, int length) {
- PropertySetter setter = sHolders.getDelegate(nativePtr);
- assert setter != null;
-
- setter.setValues(data);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nSetPropertyHolderData(long nativePtr, int[] data, int length) {
- PropertySetter setter = sHolders.getDelegate(nativePtr);
- assert setter != null;
-
- setter.setValues(data);
- }
-
- @LayoutlibDelegate
- /*package*/ static void nStart(long animatorSetPtr, VectorDrawableAnimatorRT set, int id) {
- AnimatorSetHolder animatorSet = sAnimatorSets.getDelegate(animatorSetPtr);
- assert animatorSet != null;
-
- animatorSet.start();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nReverse(long animatorSetPtr, VectorDrawableAnimatorRT set, int id) {
- AnimatorSetHolder animatorSet = sAnimatorSets.getDelegate(animatorSetPtr);
- assert animatorSet != null;
-
- animatorSet.reverse();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nEnd(long animatorSetPtr) {
- AnimatorSetHolder animatorSet = sAnimatorSets.getDelegate(animatorSetPtr);
- assert animatorSet != null;
-
- animatorSet.end();
- }
-
- @LayoutlibDelegate
- /*package*/ static void nReset(long animatorSetPtr) {
- AnimatorSetHolder animatorSet = sAnimatorSets.getDelegate(animatorSetPtr);
- assert animatorSet != null;
-
- animatorSet.end();
- animatorSet.start();
- }
-
- private static class AnimatorSetHolder {
- private ArrayList mAnimators = new ArrayList<>();
- private AnimatorSet mAnimatorSet = null;
-
- private void addAnimator(@NonNull Animator animator) {
- mAnimators.add(animator);
- }
-
- private void ensureAnimatorSet() {
- if (mAnimatorSet == null) {
- mAnimatorSet = new AnimatorSet();
- mAnimatorSet.playTogether(mAnimators);
- }
- }
-
- private void start() {
- ensureAnimatorSet();
-
- mAnimatorSet.start();
- }
-
- private void end() {
- mAnimatorSet.end();
- }
-
- private void reset() {
- end();
- start();
- }
-
- private void reverse() {
- mAnimatorSet.reverse();
- }
- }
-
- /**
- * Class that allows setting a value and holds the range of values for the given property.
- *
- * @param the type of the property
- */
- private static class PropertySetter {
- final Consumer mValueSetter;
- private PropertyValuesHolder mValues;
-
- private PropertySetter(@NonNull Consumer valueSetter) {
- mValueSetter = valueSetter;
- }
-
- /**
- * Method to set an {@link Integer} value for this property. The default implementation of
- * this method doesn't do anything. This method is accessed via reflection by the
- * PropertyValuesHolder.
- */
- public void setIntValue(Integer value) {
- }
-
- /**
- * Method to set an {@link Integer} value for this property. The default implementation of
- * this method doesn't do anything. This method is accessed via reflection by the
- * PropertyValuesHolder.
- */
- public void setFloatValue(Float value) {
- }
-
- void setValues(float... values) {
- mValues = PropertyValuesHolder.ofFloat("floatValue", values);
- }
-
- @Nullable
- PropertyValuesHolder getValues() {
- return mValues;
- }
-
- void setValues(int... values) {
- mValues = PropertyValuesHolder.ofInt("intValue", values);
- }
- }
-
- private static class IntPropertySetter extends PropertySetter {
- private IntPropertySetter(Consumer valueSetter) {
- super(valueSetter);
- }
-
- private static PropertySetter of(Consumer valueSetter, int... values) {
- PropertySetter setter = new IntPropertySetter(valueSetter);
- setter.setValues(values);
-
- return setter;
- }
-
- public void setIntValue(Integer value) {
- mValueSetter.accept(value);
- }
- }
-
- private static class FloatPropertySetter extends PropertySetter {
- private FloatPropertySetter(Consumer valueSetter) {
- super(valueSetter);
- }
-
- private static PropertySetter of(Consumer valueSetter, float... values) {
- PropertySetter setter = new FloatPropertySetter(valueSetter);
- setter.setValues(values);
-
- return setter;
- }
-
- public void setFloatValue(Float value) {
- mValueSetter.accept(value);
- }
-
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_VectorDrawableAnimatorRT_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_VectorDrawableAnimatorRT_Delegate.java
deleted file mode 100644
index fc848d9af956b..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/drawable/AnimatedVectorDrawable_VectorDrawableAnimatorRT_Delegate.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics.drawable;
-
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Canvas;
-import android.graphics.drawable.AnimatedVectorDrawable.VectorDrawableAnimatorRT;
-
-public class AnimatedVectorDrawable_VectorDrawableAnimatorRT_Delegate {
- @LayoutlibDelegate
- /*package*/ static boolean useLastSeenTarget(VectorDrawableAnimatorRT thisDrawableAnimator) {
- return true;
- }
-
- @LayoutlibDelegate
- /*package*/ static void onDraw(VectorDrawableAnimatorRT thisDrawableAnimator, Canvas canvas) {
- // Do not attempt to record as we are not using a DisplayListCanvas
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/drawable/GradientDrawable_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/drawable/GradientDrawable_Delegate.java
deleted file mode 100644
index a3ad2aac7d3df..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/drawable/GradientDrawable_Delegate.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics.drawable;
-
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.graphics.Path;
-import android.graphics.drawable.GradientDrawable.GradientState;
-
-import java.lang.reflect.Field;
-
-/**
- * Delegate implementing the native methods of {@link GradientDrawable}
- *
- * Through the layoutlib_create tool, the original native methods of GradientDrawable have been
- * replaced by calls to methods of the same name in this delegate class.
- */
-public class GradientDrawable_Delegate {
-
- /**
- * The ring can be built either by drawing full circles, or by drawing arcs in case the
- * circle isn't complete. LayoutLib cannot handle drawing full circles (requires path
- * subtraction). So, if we need to draw full circles, we switch to drawing 99% circle.
- */
- @LayoutlibDelegate
- /*package*/ static Path buildRing(GradientDrawable thisDrawable, GradientState st) {
- boolean useLevel = st.mUseLevelForShape;
- int level = thisDrawable.getLevel();
- // 10000 is the max level. See android.graphics.drawable.Drawable#getLevel()
- float sweep = useLevel ? (360.0f * level / 10000.0f) : 360f;
- Field mLevel = null;
- if (sweep >= 360 || sweep <= -360) {
- st.mUseLevelForShape = true;
- // Use reflection to set the value of the field to prevent setting the drawable to
- // dirty again.
- try {
- mLevel = Drawable.class.getDeclaredField("mLevel");
- mLevel.setAccessible(true);
- mLevel.setInt(thisDrawable, 9999); // set to one less than max.
- } catch (NoSuchFieldException e) {
- // The field has been removed in a recent framework change. Fall back to old
- // buggy behaviour.
- } catch (IllegalAccessException e) {
- // We've already set the field to be accessible.
- assert false;
- }
- }
- Path path = thisDrawable.buildRing_Original(st);
- st.mUseLevelForShape = useLevel;
- if (mLevel != null) {
- try {
- mLevel.setInt(thisDrawable, level);
- } catch (IllegalAccessException e) {
- assert false;
- }
- }
- return path;
- }
-}
diff --git a/tools/layoutlib/bridge/src/android/graphics/drawable/VectorDrawable_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/drawable/VectorDrawable_Delegate.java
deleted file mode 100644
index 616784c10aaea..0000000000000
--- a/tools/layoutlib/bridge/src/android/graphics/drawable/VectorDrawable_Delegate.java
+++ /dev/null
@@ -1,1262 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics.drawable;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-import android.annotation.NonNull;
-import android.content.res.Resources;
-import android.content.res.Resources.Theme;
-import android.content.res.TypedArray;
-import android.graphics.BaseCanvas_Delegate;
-import android.graphics.Canvas_Delegate;
-import android.graphics.Color;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Paint.Cap;
-import android.graphics.Paint.Join;
-import android.graphics.Paint_Delegate;
-import android.graphics.Path;
-import android.graphics.PathMeasure;
-import android.graphics.Path_Delegate;
-import android.graphics.Rect;
-import android.graphics.Region.Op;
-import android.util.ArrayMap;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.util.MathUtils;
-import android.util.PathParser_Delegate;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-import java.util.ArrayList;
-import java.util.function.Consumer;
-
-import static android.graphics.Canvas.CLIP_SAVE_FLAG;
-import static android.graphics.Canvas.MATRIX_SAVE_FLAG;
-import static android.graphics.Paint.Cap.BUTT;
-import static android.graphics.Paint.Cap.ROUND;
-import static android.graphics.Paint.Cap.SQUARE;
-import static android.graphics.Paint.Join.BEVEL;
-import static android.graphics.Paint.Join.MITER;
-import static android.graphics.Paint.Style;
-
-/**
- * Delegate used to provide new implementation of a select few methods of {@link VectorDrawable}
- *