diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index a3cd7bfe..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,103 +0,0 @@ -# Java Gradle CircleCI 2.0 configuration file -# -# Check https://circleci.com/docs/2.0/language-java/ for more details -# -version: 2 - -general: - branches: - only: - #- circleci -jobs: - build: - docker: - # specify the version you desire here - #- image: circleci/openjdk:8-jdk - - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - - image: circleci/android:api-26-alpha - - working_directory: ~/repo - - environment: - # Customize the JVM maximum heap limit - JVM_OPTS: -Xmx3200m - TERM: dumb -# KEYSTORE: ${CIRCLE_WORKING_DIRECTORY}/sigining.keystore -# PUBLISHER_ACCT_JSON_FILE: ${CIRCLE_WORKING_DIRECTORY}/publisher_profile.json - - steps: - - checkout - - - run: echo 'export KEYSTORE=${HOME}/repo/sigining.keystore' >> $BASH_ENV - - run: echo 'export PUBLISHER_ACCT_JSON_FILE=${HOME}/repo/publisher_profile.json' >> $BASH_ENV - - # Download and cache dependencies - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - # Get private keys etc - - run: ./misc/download_keystore.sh - - run: ./misc/inject_circle_build_number.sh - - - run: ./gradlew dependencies - - - save_cache: - paths: - - ~/.m2 - key: v1-dependencies-{{ checksum "build.gradle" }} - - # run tests & code coc! - - run: ./gradlew testDebug jacocoTestReportDebug - - # build release - - run: ./gradlew assembleRelease - - # javadoc - - run: ./gradlew javadoc - - # trigger codecod.io - - run: bash <(curl -s https://codecov.io/bash) - - - store_artifacts: - path: androidplot-core/build/outputs/aar/ - destination: aar - - - store_artifacts: - path: demoapp/build/outputs/apk/ - destination: apk - - - store_artifacts: - path: androidplot-core/build/reports/jacoco/debug/ - destination: coverage_report - - - store_artifacts: - path: androidplot-core/build/reports/tests/ - destination: test_results - - - store_artifacts: - path: androidplot-core/build/docs/javadoc - destination: javadoc - - - store_test_results: - path: androidplot-core/build/test-results/ - - - deploy: - name: "Deploy to Bintray" - command: | - if [ "${CIRCLE_BRANCH}" == "master" ]; - then ./gradlew bintrayUpload; - fi - - - deploy: - name: "Deploy to Google Play" - command: | - if [ "${CIRCLE_BRANCH}" == "master" ]; - then - ./misc/download_google_publisher_json.sh; - ./gradlew publishApkRelease - fi \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..d38f337e --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,57 @@ +name: build androidplot +on: [push] +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Set Up JDK 17 + uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: '17' + + - name: Build and Test + run: ./gradlew testDebugUnitTest jacocoTestDebugUnitTestReport + + - name: Build Release + env: + ENCODED: ${{ secrets.DEMOAPP_KEYSTORE }} + KEYSTORE: keystore.jks + KEY_ALIAS: Key0 + KEYSTORE_PASSWORD: ${{ secrets.DEMOAPP_KEYSTORE_PASSWORD }} + KEY_PASSWORD: ${{ secrets.DEMOAPP_KEY_PASSWORD }} + run: | + echo $ENCODED | base64 -di > "${GITHUB_WORKSPACE}/demoapp/keystore.jks" + ./gradlew assembleRelease + +# TODO: get javadoc working again at some point +# - name: Javadoc +# run: ./gradlew javadoc + + - name: Code Coverage + run: bash <(curl -s https://codecov.io/bash) + + - uses: actions/upload-artifact@v3 + with: + name: Core Library + path: androidplot-core/build/outputs/aar/*.aar + retention-days: 30 + + - uses: actions/upload-artifact@v3 + if: github.ref_name == 'master' + with: + name: Demoapp APK + path: demoapp/build/outputs/apk/release/*.apk + retention-days: 30 + + - name: Stage for Maven Central + if: github.ref_name == 'master' + env: + OSSRH_ACTOR: ${{ secrets.OSSRH_ACTOR }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }} + SIGNING_PASSWORD: ${{ secrets.GPG_SIGNING_PASSWORD }} + run: ./gradlew publish \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md index 3fbf0a78..f49a4e16 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,13 +1,201 @@ - Copyright 2018 Androidplot.com + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ - 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 + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - http://www.apache.org/licenses/LICENSE-2.0 + 1. Definitions. - 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. \ No newline at end of file + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/README.md b/README.md index 7d7020d2..9617a26e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ -# ![image](docs/images/aplogo_small.png) Androidplot [![CircleCI](https://circleci.com/gh/halfhp/androidplot.svg?style=shield)](https://circleci.com/gh/halfhp/androidplot) [![codecov](https://codecov.io/gh/halfhp/androidplot/branch/master/graph/badge.svg)](https://codecov.io/gh/halfhp/androidplot) [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/androidplot.svg?style=social&label=Follow%20Us)](https://twitter.com/androidplot) +# ![image](docs/images/aplogo_small.png) Androidplot [![AndroidPlot](https://www.appbrain.com/stats/libraries/shield/androidplot.svg)](https://www.appbrain.com/stats/libraries/details/androidplot/androidplot) [![Codix](http://codix.io/gh/badge/halfhp/androidplot)](http://codix.io/gh/repo/halfhp/androidplot) [![codecov](https://codecov.io/gh/halfhp/androidplot/branch/master/graph/badge.svg)](https://codecov.io/gh/halfhp/androidplot) [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/androidplot.svg?style=social&label=Follow%20Us)](https://twitter.com/androidplot) -A library for creating dynamic and static charts in Android apps. It’s designed from the ground up for Android, -compatible with all versions of Android from 1.6 onward and is **used by over -[1,000 apps](http://www.appbrain.com/stats/libraries/details/androidplot/androidplot) on Google Play**. +A library for creating dynamic and static charts in Android apps. -[![Codix](http://codix.io/gh/badge/halfhp/androidplot)](http://codix.io/gh/repo/halfhp/androidplot) +Androidplot is compatible with all versions of Android from 1.6 onward, works equally with Kotlin and Java codebases +and is compatible with Jetpack compose. If you enjoy the lib, please [rate us on codix.io](http://codix.io/gh/repo/halfhp/androidplot)! @@ -43,7 +42,7 @@ Technical questions should be posted using the [androidplot tag](http://stackove # License Androidplot has been made available under the Apache 2.0 license: - Copyright 2018 Androidplot.com + Copyright 2021 Androidplot.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/androidplot-core/build.gradle b/androidplot-core/build.gradle index a814a4c1..b37b2b4a 100644 --- a/androidplot-core/build.gradle +++ b/androidplot-core/build.gradle @@ -14,11 +14,12 @@ * limitations under the License. */ -apply plugin: 'com.android.library' -apply plugin: 'com.github.dcendents.android-maven' -apply plugin: 'com.jfrog.bintray' -apply plugin: 'com.vanniktech.android.junit.jacoco' -apply plugin: 'com.github.kt3k.coveralls' +plugins { + id 'com.android.library' + id 'com.mxalbert.gradle.jacoco-android' + id 'maven-publish' + id 'signing' +} class AttrMarkdown extends DefaultTask { @@ -30,13 +31,14 @@ class AttrMarkdown extends DefaultTask { def input = project.file(inFile) def output = project.file(outFile) - if(output.exists()) { + if (output.exists()) { output.delete() } output.parentFile.mkdirs() - input.text.findAll(//) { match, g1 -> g1 - if(!g1.startsWith("NODOC")) { + input.text.findAll(//) { match, g1 -> + g1 + if (!g1.startsWith("NODOC")) { output.append(g1) output.append "\n\n" } @@ -52,27 +54,44 @@ class AttrMarkdown extends DefaultTask { * The generated doc will appear in / replace androidplot/docs/attrs.md */ task generateAttrsMarkdown(type: AttrMarkdown) { - inFile = { "src/main/res/values/attrs.xml"} + inFile = { "src/main/res/values/attrs.xml" } outFile = { "../docs/attrs.md" } } android { - compileSdkVersion theCompileSdkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + defaultConfig { - versionCode theVersionCode - versionName theVersionName + compileSdk theCompileSdkVersion minSdkVersion theMinSdkVersion targetSdkVersion theTargetSdkVersion testApplicationId "com.androidplot.test" } - /** - * TODO: enable and address lint issues. - */ - lintOptions { + testOptions { + unitTests.all { + jacoco { + includeNoLocationClasses = true + jacoco.excludes = ['jdk.internal.*'] + } + } + } + lint { abortOnError false } + namespace 'com.androidplot' + + publishing { + singleVariant("release") { + withSourcesJar() + withJavadocJar() + } + } } group = 'com.androidplot' @@ -83,99 +102,88 @@ def gitUrl = 'https://github.com/halfhp/androidplot.git' dependencies { - compile 'com.halfhp.fig:figlib:1.0.7' - compile 'com.android.support:support-annotations:27.0.2' - testCompile "org.mockito:mockito-core:1.10.19" - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile "org.robolectric:robolectric:3.1" - - // temp fix for: - // https://github.com/robolectric/robolectric/issues/1932 - testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1' -} - -task javadoc(type: Javadoc) { - source = android.sourceSets.main.java.srcDirs - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) - failOnError false - options { - links "http://docs.oracle.com/javase/7/docs/api/" - linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference" - } - exclude '**/BuildConfig.java' - exclude '**/R.java' -} + implementation 'com.halfhp.fig:figlib:1.0.11' + implementation 'androidx.annotation:annotation:1.8.2' -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir + testImplementation "org.mockito:mockito-core:5.7.0" + testImplementation group: 'junit', name: 'junit', version: '4.13.2' + testImplementation "org.robolectric:robolectric:4.7.3" } -task sourcesJar(type: Jar) { - classifier = 'sources' - from android.sourceSets.main.java.srcDirs -} +// TODO: get javadoc working again at some point +//task javadoc(type: Javadoc) { +// source = android.sourceSets.main.java.srcDirs +// classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) +// failOnError false +// options { +// links "http://docs.oracle.com/javase/7/docs/api/" +// linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference" +// } +// exclude '**/BuildConfig.java' +// exclude '**/R.java' +//} +// + + +// TODO: get javadoc working again at some point +//javadoc { +// options.overview = "src/main/java/overview.html" +//} + +afterEvaluate { + publishing { + repositories { + maven { + name = "MavenCentral" + url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" + credentials { + username = System.getenv("OSSRH_ACTOR") + password = System.getenv("OSSRH_TOKEN") + } + } + } -install { - repositories.mavenInstaller { - pom { - project { - packaging 'aar' - name 'Androidplot Core Library' - description = "Androidplot is a library for creating dynamic and static charts within your Android application." - url siteUrl - licenses { - license { - name 'The Apache Software License, Version 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.txt' + publications { + release(MavenPublication) { + from components.release + + // You can then customize attributes of the publication as shown below. + groupId = 'com.androidplot' + artifactId = 'androidplot-core' + version = theVersionName + + pom { + packaging 'aar' + name = 'Androidplot' + description = "Configure any object from XML." + url = gitUrl + licenses { + license { + name = 'The Apache Software License, Version 2.0' + url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' + } } - } - developers { - developer { - id 'halfhp' - name 'Nick Fellows' - email 'halfhp@gmail.com' + developers { + developer { + id = 'halfhp' + name = 'Nick Fellows' + email = 'halfhp@gmail.com' + } + } + scm { + connection = gitUrl + developerConnection = gitUrl + url = gitUrl } - } - scm { - connection gitUrl - developerConnection gitUrl - url siteUrl - } } } } } -bintray { - - // these environment vars must be set when deploying to bintray. - // note: BINTRAY_PASSWORD is actually the api key, but naming it 'password' - // tells the CI environment to obfuscate the value in public logs. - user = System.getenv('BINTRAY_USER') - key = System.getenv('BINTRAY_PASSWORD') - - - configurations = ['archives'] - pkg { - version { - name = theVersionName - } - repo = "androidplot" - name = "com.androidplot:androidplot-core" - issueTrackerUrl = "https://github.com/halfhp/androidplot/issues" - websiteUrl = siteUrl - vcsUrl = gitUrl - licenses = ["Apache-2.0"] - } -} - -javadoc { - options.overview = "src/main/java/overview.html" -} - -artifacts { - archives javadocJar - archives sourcesJar +signing { + def signingKey = System.getenv("SIGNING_KEY") + def signingPassword = System.getenv("SIGNING_PASSWORD") + useInMemoryPgpKeys(signingKey, signingPassword) + sign(publishing.publications) } diff --git a/androidplot-core/src/main/AndroidManifest.xml b/androidplot-core/src/main/AndroidManifest.xml index e83183d1..3043c930 100644 --- a/androidplot-core/src/main/AndroidManifest.xml +++ b/androidplot-core/src/main/AndroidManifest.xml @@ -16,5 +16,5 @@ - + \ No newline at end of file diff --git a/androidplot-core/src/main/java/com/androidplot/Plot.java b/androidplot-core/src/main/java/com/androidplot/Plot.java index 5e009635..63d2e831 100644 --- a/androidplot-core/src/main/java/com/androidplot/Plot.java +++ b/androidplot-core/src/main/java/com/androidplot/Plot.java @@ -1,1034 +1,1077 @@ -/* - * Copyright 2015 AndroidPlot.com - * - * 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 com.androidplot; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.PorterDuff; -import android.graphics.RectF; -import android.os.Build; -import android.os.Looper; -import android.support.annotation.Nullable; -import android.util.AttributeSet; -import android.util.Log; -import android.view.View; - -import com.androidplot.exception.PlotRenderException; -import com.androidplot.ui.Anchor; -import com.androidplot.ui.BoxModel; -import com.androidplot.ui.Formatter; -import com.androidplot.ui.HorizontalPositioning; -import com.androidplot.ui.LayoutManager; -import com.androidplot.ui.Resizable; -import com.androidplot.ui.SeriesBundle; -import com.androidplot.ui.SeriesRenderer; -import com.androidplot.ui.Size; -import com.androidplot.ui.SizeMode; -import com.androidplot.ui.TextOrientation; -import com.androidplot.ui.VerticalPositioning; -import com.androidplot.ui.widget.TextLabelWidget; -import com.androidplot.util.AttrUtils; -import com.androidplot.util.DisplayDimensions; -import com.androidplot.util.PixelUtils; -import com.halfhp.fig.Fig; -import com.halfhp.fig.FigException; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * Base class for all Plot implementations. - */ -public abstract class Plot, - RegistryType extends SeriesRegistry> - extends View implements Resizable { - private static final String TAG = Plot.class.getName(); - private static final String XML_ATTR_PREFIX = "androidplot"; - private static final String BASE_PACKAGE = "com.androidplot."; - - private static final int DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP = 10; - - public DisplayDimensions getDisplayDimensions() { - return displayDims; - } - - /** - * Used for caching renderer instances. Note that once a renderer is initialized it remains initialized - * for the life of the application; does not and should not be destroyed until the application exits. - */ - public HashMap, RendererType> getRenderers() { - return renderers; - } - - /** - * Associates lists series and getFormatter pairs with the class of the Renderer used to render them. - */ - public RegistryType getRegistry() { - return registry; - } - - public void setRegistry(RegistryType registry) { - this.registry = registry; - for(BundleType bundle : registry.getSeriesAndFormatterList()) { - attachSeries(bundle.getSeries(), bundle.getFormatter()); - } - } - - /** - * - * @return A new instance of RegistryType - */ - protected abstract RegistryType getRegistryInstance(); - - public TextLabelWidget getTitle() { - return title; - } - - public void setTitle(TextLabelWidget title) { - this.title = title; - } - - public void setTitle(String title) { - getTitle().setText(title); - } - - public enum BorderStyle { - ROUNDED, - SQUARE, - NONE - } - - /** - * The RenderMode used by a Plot to draw it's self onto the screen. The RenderMode can be set - * in two ways. - * - * In an xml layout: - * - * - * - * - * - * Programatically: - * - * - * XYPlot myPlot = new XYPlot(context "MyPlot", Plot.RenderMode.USE_MAIN_THREAD); - * - * - * A Plot's RenderMode cannot be changed after the plot has been initialized. - * @since 0.5.1 - */ - public enum RenderMode { - /** - * Use a second thread and an off-screen buffer to do drawing. This is the preferred method - * of drawing dynamic data and static data that consists of a large number of points. This mode - * provides more efficient CPU utilization at the cost of increased memory usage. As of - * version 0.5.1 this is the default RenderMode. - * - * XML value: use_background_thread - * @since 0.5.1 - */ - USE_BACKGROUND_THREAD, - - /** - * Do everything in the primary thread. This is the preferred method of drawing static charts - * and dynamic data that consists of a small number of points. This mode uses less memory at - * the cost of poor CPU utilization. - * - * XML value: use_main_thread - * @since 0.5.1 - */ - USE_MAIN_THREAD - } - private BoxModel boxModel = new BoxModel(); - - // no border by default: - private BorderStyle borderStyle = Plot.BorderStyle.NONE; - private float borderRadiusX = 15; - private float borderRadiusY = 15; - private Paint borderPaint; - private Paint backgroundPaint; - private LayoutManager layoutManager; - private TextLabelWidget title; - private DisplayDimensions displayDims = new DisplayDimensions(); - private RenderMode renderMode = RenderMode.USE_MAIN_THREAD; - private final BufferedCanvas pingPong = new BufferedCanvas(); - - // used to get rid of flickering when drawing offScreenBitmap to the visible Canvas. - private final Object renderSync = new Object(); - - private HashMap, RendererType> renderers; - - private RegistryType registry; - private final ArrayList listeners; - - private Thread renderThread; - private boolean keepRunning = false; - private boolean isIdle = true; - - { - listeners = new ArrayList<>(); - registry = getRegistryInstance(); - renderers = new HashMap<>(); - - borderPaint = new Paint(); - borderPaint.setColor(Color.rgb(150, 150, 150)); - borderPaint.setStyle(Paint.Style.STROKE); - borderPaint.setStrokeWidth(1.0f); - borderPaint.setAntiAlias(true); - backgroundPaint = new Paint(); - backgroundPaint.setColor(Color.DKGRAY); - backgroundPaint.setStyle(Paint.Style.FILL); - } - - - /** - * Any rendering that utilizes a buffer from this class should synchronize rendering on the instance of this class - * that is being used. - */ - private static class BufferedCanvas { - private volatile Bitmap bgBuffer; // all drawing is done on this buffer. - private volatile Bitmap fgBuffer; - private Canvas canvas = new Canvas(); - - /** - * Call this method once drawing on a Canvas retrieved by {@link #getCanvas()} to mark - * the buffer as fully rendered. Failure to call this method will result in nothing being drawn. - */ - public synchronized void swap() { - Bitmap tmp = bgBuffer; - bgBuffer = fgBuffer; - fgBuffer = tmp; - } - - public synchronized void resize(int h, int w) { - if (w <= 0 || h <= 0) { - bgBuffer = null; - fgBuffer = null; - } else { - bgBuffer = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444); - fgBuffer = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444); - } - } - - public void recycle() { - bgBuffer.recycle(); - bgBuffer = null; - - fgBuffer.recycle(); - fgBuffer = null; - System.gc(); - } - - /** - * Get a Canvas for drawing. Actual drawing should be synchronized on the instance - * of BufferedCanvas being used. - * @return The Canvas instance to draw onto. Returns null if drawing buffers have not - * been initialized a la {@link #resize(int, int)}. - */ - public synchronized Canvas getCanvas() { - if(bgBuffer != null) { - canvas.setBitmap(bgBuffer); - return canvas; - } else { - return null; - } - } - - /** - * @return The most recent fully rendered Bitmsp - */ - public Bitmap getBitmap() { - return fgBuffer; - } - } - - /** - * Convenience constructor - wraps {@link #Plot(android.content.Context, String, com.androidplot.Plot.RenderMode)}. - * RenderMode is set to {@link RenderMode#USE_BACKGROUND_THREAD}. - * @param context - * @param title The display title of this Plot. - */ - public Plot(Context context, String title) { - this(context, title, RenderMode.USE_MAIN_THREAD); - } - - /** - * Used for programmatic instantiation. - * @param context - * @param title The display title of this Plot. - */ - public Plot(Context context, String title, RenderMode mode) { - super(context); - this.renderMode = mode; - init(context, null, 0); - getTitle().setText(title); - } - - - /** - * Required by super-class. Extending class' implementations should add - * the following code immediately before exiting to ensure that loadAttrs - * is called only once by the derived class: - * - * if(getClass().equals(DerivedPlot.class) { - * loadAttrs(context, attrs); - * } - * - * - * See {@link com.androidplot.xy.XYPlot#XYPlot(android.content.Context, android.util.AttributeSet)} - * for an example. - * @param context - * @param attrs - */ - public Plot(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs, 0); - } - - /** - * Required by super-class. Extending class' implementations should add - * the following code immediately before exiting to ensure that loadAttrs - * is called only once by the derived class: - * - * if(getClass().equals(DerivedPlot.class) { - * loadAttrs(context, attrs); - * } - * - * - * See {@link com.androidplot.xy.XYPlot#XYPlot(android.content.Context, android.util.AttributeSet, int)} - * for an example. - * @param context - * @param attrs - * @param defStyle - */ - public Plot(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context, attrs, defStyle); - } - - /** - * Can be overridden by derived classes to control hardware acceleration state. - * Note that this setting is only used on Honeycomb and later environments. - * @return True if hardware acceleration is allowed, false otherwise. - * @since 0.5.1 - */ - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - protected boolean isHwAccelerationSupported() { - return false; - } - - /** - * Sets the render mode used by the Plot. - * WARNING: This method is not currently designed for general use outside of Configurator. - * Attempting to reassign the render mode at runtime will result in unexpected behavior. - * @param mode - */ - public void setRenderMode(RenderMode mode) { - this.renderMode = mode; - } - - /** - * Concrete implementations may do any final setup / initialization - * here. Immediately following this method's invocation, AndroidPlot assumes - * that the Plot instance is ready for final configuration via the Configurator. - */ - protected void onPreInit() { - // nothing to do by default - } - - /** - * Invoked immediately following configurator / styleable attr application. - */ - protected void onAfterConfig() { - // nothing to do by default - } - - protected final void init(Context context, AttributeSet attrs, int defStyle) { - PixelUtils.init(context); - layoutManager = new LayoutManager(); - title = new TextLabelWidget(layoutManager, new Size(25, - SizeMode.ABSOLUTE, 100, - SizeMode.ABSOLUTE), - TextOrientation.HORIZONTAL); - title.position(0, HorizontalPositioning.RELATIVE_TO_CENTER, 0, - VerticalPositioning.ABSOLUTE_FROM_TOP, Anchor.TOP_MIDDLE); - - // initialize attr defaults: - title.getLabelPaint().setTextSize( - PixelUtils.spToPix(DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP)); - - onPreInit(); - // make sure the title widget is always the topmost widget: - layoutManager.moveToTop(title); - if(context != null && attrs != null) { - loadAttrs(attrs, defStyle); - } - - onAfterConfig(); - - layoutManager.onPostInit(); - if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { - renderThread = new Thread(new Runnable() { - @Override - public void run() { - - keepRunning = true; - while (keepRunning) { - isIdle = false; - synchronized (pingPong) { - Canvas c = pingPong.getCanvas(); - renderOnCanvas(c); - pingPong.swap(); - } - synchronized (renderSync) { - postInvalidate(); - // prevent this thread from becoming an orphan - // after the view is destroyed - if (keepRunning) { - try { - renderSync.wait(); - } catch (InterruptedException e) { - keepRunning = false; - } - } - } - } - pingPong.recycle(); - } - }, "Androidplot renderThread"); - } - } - - /** - * If a styleable is available for the derived class, this method will be invoked with those attrs. - * The derived implementation is only responsible for setting derived class attributes, ie. it should - * not attempt to apply the Plot.title styleable attribute etc. Do not invoke recycle() on attrs. - * @param attrs Attrs for the derived class. - */ - protected abstract void processAttrs(TypedArray attrs); - - /** - * Apply base class attrs. - * @param attrs - */ - private void processBaseAttrs(TypedArray attrs) { - - // markup mode - boolean markupEnabled = attrs.getBoolean(R.styleable.Plot_markupEnabled, false); - setMarkupEnabled(markupEnabled); - - // renderMode - RenderMode renderMode = RenderMode.values() - [attrs.getInt(R.styleable.Plot_renderMode, getRenderMode().ordinal())]; - if(renderMode != getRenderMode()) { - setRenderMode(renderMode); - } - - // margins & padding - AttrUtils.configureBoxModelable(attrs, boxModel, R.styleable.Plot_marginTop, R.styleable.Plot_marginBottom, - R.styleable.Plot_marginLeft, R.styleable.Plot_marginRight, R.styleable.Plot_paddingTop, - R.styleable.Plot_paddingBottom, R.styleable.Plot_paddingLeft, R.styleable.Plot_paddingRight); - - // title - getTitle().setText(attrs.getString(R.styleable.Plot_title)); - getTitle().getLabelPaint().setTextSize( - attrs.getDimension(R.styleable.Plot_titleTextSize, - PixelUtils.spToPix(DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP))); - - getTitle().getLabelPaint().setColor(attrs.getColor( - R.styleable.Plot_titleTextColor, getTitle().getLabelPaint().getColor())); - - getBackgroundPaint().setColor( - attrs.getColor(R.styleable.Plot_backgroundColor, getBackgroundPaint().getColor())); - - AttrUtils.configureLinePaint(attrs, getBorderPaint(), - R.styleable.Plot_borderColor, R.styleable.Plot_borderThickness); - } - - /** - * Parse XML Attributes. Should only be called once and at the end of the base class constructor. - * The first-pass attempts to locate styleable attributes and apply those first. After that, - * configurator-style attributes are applied, overriding any styleable attrs that may have - * been previously applied. - * - * @param attrs - */ - private void loadAttrs(AttributeSet attrs, int defStyle) { - - if (attrs != null) { - - Field styleableFieldInR = null; - TypedArray typedAttrs = null; - - Class styleableClass = R.styleable.class; - String styleableName = getClass().getName().substring(BASE_PACKAGE.length()); - styleableName = styleableName.replace('.', '_'); - try { - /** - * Use reflection to safely run for the existence of styleable defs for Plot - * and it's derivatives. This safety run is necessary to avoid runtime exceptions - * in apps that don't include Androidplot as a .aar and won't have access to - * the resources defined in the core library. - */ - styleableFieldInR = styleableClass.getField(styleableName); - } catch (NoSuchFieldException e) { - Log.d(TAG, "Styleable definition not found for: " + styleableName); - } - if (styleableFieldInR != null) { - try { - int[] resIds = (int[]) styleableFieldInR.get(null); - typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0); - } catch (IllegalAccessException e) { - // nothing to do - } finally { - if (typedAttrs != null) { - // apply derived class' attrs: - processAttrs(typedAttrs); - typedAttrs.recycle(); - } - } - } - - try { - styleableFieldInR = styleableClass.getField(Plot.class.getSimpleName()); - if (styleableFieldInR != null) { - int[] resIds = (int[]) styleableFieldInR.get(null); - typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0); - } - } catch (IllegalAccessException e) { - // nothing to do - } catch (NoSuchFieldException e) { - Log.d(TAG, "Styleable definition not found for: " + Plot.class.getSimpleName()); - } finally { - if (typedAttrs != null) { - // apply base attrs: - processBaseAttrs(typedAttrs); - typedAttrs.recycle(); - } - } - - // apply "configurator" attrs: (overrides any previously applied styleable attrs) - // filter out androidplot prefixed attrs: - HashMap attrHash = new HashMap<>(); - for (int i = 0; i < attrs.getAttributeCount(); i++) { - String attrName = attrs.getAttributeName(i); - - // case insensitive run to see if this attr begins with our prefix: - if (attrName != null && attrName.toUpperCase().startsWith(XML_ATTR_PREFIX.toUpperCase())) { - attrHash.put(attrName.substring(XML_ATTR_PREFIX.length() + 1), attrs.getAttributeValue(i)); - } - } - try { - Fig.configure(getContext(), this, attrHash); - } catch (FigException e) { - throw new RuntimeException(e); - } - } - } - - public RenderMode getRenderMode() { - return renderMode; - } - - public synchronized boolean addListener(PlotListener listener) { - return !listeners.contains(listener) && listeners.add(listener); - } - - public synchronized boolean removeListener(PlotListener listener) { - return listeners.remove(listener); - } - - protected ArrayList getListeners() { - return listeners; - } - - protected void notifyListenersBeforeDraw(Canvas canvas) { - for (PlotListener listener : listeners) { - listener.onBeforeDraw(this, canvas); - } - } - - protected void notifyListenersAfterDraw(Canvas canvas) { - for (PlotListener listener : listeners) { - listener.onAfterDraw(this, canvas); - } - } - - /** - * Convenience method to add a multiple series at once using the same formatter. - * If a problem is encountered, the method immediately returns false and the plot - * will contain whatever series were added before the failure. - * @param formatter - * @param series - * @return True if all series were successfully added, false otherwise. - * @since 0.9.7 - */ - public synchronized boolean addSeries(FormatterType formatter, SeriesType... series) { - for(SeriesType s : series) { - if(!addSeries(s, formatter)) { - return false; - } - } - return true; - } - - /** - * Add a new Series to the Plot. - * @param series - * @param formatter - * @return True if the series was added or false if the series / formatter pair already exists in the registry. - */ - public synchronized boolean addSeries(SeriesType series, FormatterType formatter) { - final boolean result = getRegistry().add(series, formatter); - attachSeries(series, formatter); - return result; - } - - protected void attachSeries(SeriesType series, FormatterType formatter) { - - Class rendererClass = formatter.getRendererClass(); - - // initialize the Renderer if necessary: - if(!getRenderers().containsKey(rendererClass)) { - getRenderers().put(rendererClass, (RendererType) formatter.getRendererInstance(this)); - } - - // if this series implements PlotListener, add it as a listener: - if(series instanceof PlotListener) { - addListener((PlotListener)series); - } - } - - /** - * - * @param series - * @param rendererClass - * @return The {@link SeriesBundle} that matches the series and rendererClass params, or null if one is not found. - */ - protected SeriesBundle getSeries(SeriesType series, Class rendererClass) { - for(SeriesBundle thisPair : getSeries(series)) { - if(thisPair.getFormatter().getRendererClass() == rendererClass) { - return thisPair; - } - } - return null; - } - - /** - * - * @param series - * @return A List of {@link SeriesBundle} instances that reference series. - */ - protected List> getSeries(SeriesType series) { - return getRegistry().get(series); - } - - /** - * - * Remove a series for a specific Renderer only. Use {@link #removeSeries(Series)} to remove the series - * from the plot completely. - * @param series - * @param rendererClass - * @return True if anything was removed, false otherwise - */ - public synchronized boolean removeSeries(SeriesType series, Class rendererClass) { - - List removedItems = getRegistry().remove(series, rendererClass); - - // if series implements PlotListener and is not assigned to any other renderers remove it as a listener: - if (removedItems.size() == 1 && series instanceof PlotListener) { - removeListener((PlotListener) series); - return true; - } - return false; - } - - /** - * Remove all occurrences of series regardless of the associated Renderer. - * @param series - */ - public synchronized void removeSeries(SeriesType series) { - // if series implements PlotListener, remove it from listeners: - if (series instanceof PlotListener) { - removeListener((PlotListener) series); - } - - getRegistry().remove(series); - } - - /** - * Remove all series from the plot. - */ - public void clear() { - for(SeriesType series : getRegistry().getSeriesList()) { - if(series instanceof PlotListener) { - removeListener((PlotListener) series); - } - } - getRegistry().clear(); - } - - public boolean isEmpty() { - return getRegistry().isEmpty(); - } - - /** - * - * @param series - * @param rendererClass - * @return The Formatter instance corresponding to the specified series / renderer pair. - */ - public FormatterType getFormatter(SeriesType series, Class rendererClass) { - return getSeries(series, rendererClass).getFormatter(); - } - - public T getRenderer(Class rendererClass) { - return (T) getRenderers().get(rendererClass); - } - - public List getRendererList() { - return new ArrayList<>(getRenderers().values()); - } - - public void setMarkupEnabled(boolean enabled) { - this.layoutManager.setMarkupEnabled(enabled); - } - - /** - * Causes the plot to be redrawn. - * @since 0.5.1 - */ - public void redraw() { - - if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { - - // only enter synchronized block if the call is expected to block OR - // if the render thread is idle, so we know that we won't have to wait to - // obtain a lock. - if (isIdle) { - synchronized (renderSync) { - renderSync.notify(); - } - } - } else if(renderMode == RenderMode.USE_MAIN_THREAD) { - - // are we on the UI thread? - if (Looper.myLooper() == Looper.getMainLooper()) { - invalidate(); - } else { - postInvalidate(); - } - } else { - throw new IllegalArgumentException("Unsupported Render Mode: " + renderMode); - } - } - - @Override - public synchronized void layout(final DisplayDimensions dims) { - this.displayDims = dims; - layoutManager.layout(displayDims); - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - synchronized(renderSync) { - keepRunning = false; - renderSync.notify(); - } - } - - - @Override - protected synchronized void onSizeChanged (int w, int h, int oldw, int oldh) { - - // update pixel conversion values - PixelUtils.init(getContext()); - - // disable hardware acceleration if it's not explicitly supported - // by the current Plot implementation. this run only applies to - // honeycomb and later environments. - if (Build.VERSION.SDK_INT >= 11) { - if (!isHwAccelerationSupported() && isHardwareAccelerated()) { - setLayerType(View.LAYER_TYPE_SOFTWARE, null); - } - } - - // pingPong is only used in background rendering mode. - if(renderMode == RenderMode.USE_BACKGROUND_THREAD) { - pingPong.resize(h, w); - } - - RectF cRect = new RectF(0, 0, w, h); - RectF mRect = boxModel.getMarginatedRect(cRect); - RectF pRect = boxModel.getPaddedRect(mRect); - - layout(new DisplayDimensions(cRect, mRect, pRect)); - super.onSizeChanged(w, h, oldw, oldh); - if(renderThread != null && !renderThread.isAlive()) { - renderThread.start(); - } - } - - /** - * Called whenever the plot needs to be drawn via the Handler, which invokes invalidate(). - * Should never be called directly; use {@link #redraw()} instead. - * @param canvas - */ - @Override - protected void onDraw(Canvas canvas) { - if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { - synchronized(pingPong) { - Bitmap bmp = pingPong.getBitmap(); - if(bmp != null) { - canvas.drawBitmap(bmp, 0, 0, null); - } - } - } else if (renderMode == RenderMode.USE_MAIN_THREAD) { - renderOnCanvas(canvas); - } else { - throw new IllegalArgumentException("Unsupported Render Mode: " + renderMode); - } - } - - /** - * Renders the plot onto a canvas. Used by both main thread to draw directly - * onto the View's canvas as well as by background draw to render onto a - * Bitmap buffer. At the end of the day this is the main entry for a plot's - * "heavy lifting". - * @param canvas - */ - protected synchronized void renderOnCanvas(@Nullable Canvas canvas) { - if(canvas == null) { - return; - } - try { - // any series interested in synchronizing with plot should - // implement PlotListener.onBeforeDraw(...) and do a read lock from within its - // invocation. This is the entry point into that call: - notifyListenersBeforeDraw(canvas); - try { - // need to completely erase what was on the canvas before redrawing, otherwise - // some odd aliasing artifacts begin to build up around the edges of aa'd entities - // over time. - canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); - if (backgroundPaint != null) { - drawBackground(canvas, displayDims.marginatedRect); - } - - layoutManager.draw(canvas); - - if (getBorderPaint() != null) { - drawBorder(canvas, displayDims.marginatedRect); - } - } catch (PlotRenderException e) { - Log.e(TAG, "Exception while rendering Plot.", e); - } catch (Exception e) { - Log.e(TAG, "Exception while rendering Plot.", e); - } - - isIdle = true; - // any series interested in synchronizing with plot should - // implement PlotListener.onAfterDraw(...) and do a read unlock from within that - // invocation. This is the entry point for that invocation. - notifyListenersAfterDraw(canvas); - } finally { - } - } - - - /** - * Sets the visual style of the plot's border. - * @param style - * @param radiusX Sets the X radius for BorderStyle.ROUNDED. Use null for all other styles. - * @param radiusY Sets the Y radius for BorderStyle.ROUNDED. Use null for all other styles. - */ - public void setBorderStyle(BorderStyle style, Float radiusX, Float radiusY) { - if (style == Plot.BorderStyle.ROUNDED) { - if (radiusX == null || radiusY == null){ - throw new IllegalArgumentException("radiusX and radiusY cannot be null when using BorderStyle.ROUNDED"); - } - this.borderRadiusX = radiusX; - this.borderRadiusY = radiusY; - } - this.borderStyle = style; - } - - /** - * Draws the plot's outer border. - * @param canvas - * @throws PlotRenderException - */ - protected void drawBorder(Canvas canvas, RectF dims) { - drawRect(canvas, dims, borderPaint); - } - - protected void drawBackground(Canvas canvas, RectF dims) { - drawRect(canvas, dims, backgroundPaint); - } - - protected void drawRect(Canvas canvas, RectF dims, Paint paint) { - switch (borderStyle) { - case ROUNDED: - canvas.drawRoundRect(dims, borderRadiusX, borderRadiusY, paint); - break; - case SQUARE: - default: - canvas.drawRect(dims, paint); - break; - } - } - - public LayoutManager getLayoutManager() { - return layoutManager; - } - - public void setLayoutManager(LayoutManager layoutManager) { - this.layoutManager = layoutManager; - } - - public Paint getBackgroundPaint() { - return backgroundPaint; - } - - public void setBackgroundPaint(Paint backgroundPaint) { - this.backgroundPaint = backgroundPaint; - } - - /** - * Convenience method - wraps the individual setMarginXXX methods into a single method. - * @param left - * @param top - * @param right - * @param bottom - */ - public void setPlotMargins(float left, float top, float right, float bottom) { - setPlotMarginLeft(left); - setPlotMarginTop(top); - setPlotMarginRight(right); - setPlotMarginBottom(bottom); - } - - /** - * Convenience method - wraps the individual setPaddingXXX methods into a single method. - * @param left - * @param top - * @param right - * @param bottom - */ - public void setPlotPadding(float left, float top, float right, float bottom) { - setPlotPaddingLeft(left); - setPlotPaddingTop(top); - setPlotPaddingRight(right); - setPlotPaddingBottom(bottom); - } - - public float getPlotMarginTop() { - return boxModel.getMarginTop(); - } - - public void setPlotMarginTop(float plotMarginTop) { - boxModel.setMarginTop(plotMarginTop); - } - - public float getPlotMarginBottom() { - return boxModel.getMarginBottom(); - } - - public void setPlotMarginBottom(float plotMarginBottom) { - boxModel.setMarginBottom(plotMarginBottom); - } - - public float getPlotMarginLeft() { - return boxModel.getMarginLeft(); - } - - public void setPlotMarginLeft(float plotMarginLeft) { - boxModel.setMarginLeft(plotMarginLeft); - } - - public float getPlotMarginRight() { - return boxModel.getMarginRight(); - } - - public void setPlotMarginRight(float plotMarginRight) { - boxModel.setMarginRight(plotMarginRight); - } - - public float getPlotPaddingTop() { - return boxModel.getPaddingTop(); - } - - public void setPlotPaddingTop(float plotPaddingTop) { - boxModel.setPaddingTop(plotPaddingTop); - } - - public float getPlotPaddingBottom() { - return boxModel.getPaddingBottom(); - } - - public void setPlotPaddingBottom(float plotPaddingBottom) { - boxModel.setPaddingBottom(plotPaddingBottom); - } - - public float getPlotPaddingLeft() { - return boxModel.getPaddingLeft(); - } - - public void setPlotPaddingLeft(float plotPaddingLeft) { - boxModel.setPaddingLeft(plotPaddingLeft); - } - - public float getPlotPaddingRight() { - return boxModel.getPaddingRight(); - } - - public void setPlotPaddingRight(float plotPaddingRight) { - boxModel.setPaddingRight(plotPaddingRight); - } - - public Paint getBorderPaint() { - return borderPaint; - } - - /** - * Set's the paint used to draw the border. Note that this method - * copies borderPaint and set's the copy's Paint.Style attribute to - * Paint.Style.STROKE. - * @param borderPaint - */ - public void setBorderPaint(Paint borderPaint) { - if(borderPaint == null) { - this.borderPaint = null; - } else { - this.borderPaint = new Paint(borderPaint); - this.borderPaint.setStyle(Paint.Style.STROKE); - } - } -} +/* + * Copyright 2015 AndroidPlot.com + * + * 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 com.androidplot; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.RectF; +import android.os.Build; +import android.os.Looper; +import android.util.AttributeSet; +import android.util.Log; +import android.view.View; + +import androidx.annotation.Nullable; + +import com.androidplot.ui.Anchor; +import com.androidplot.ui.BoxModel; +import com.androidplot.ui.Formatter; +import com.androidplot.ui.HorizontalPositioning; +import com.androidplot.ui.LayoutManager; +import com.androidplot.ui.Resizable; +import com.androidplot.ui.SeriesBundle; +import com.androidplot.ui.SeriesRenderer; +import com.androidplot.ui.Size; +import com.androidplot.ui.SizeMode; +import com.androidplot.ui.TextOrientation; +import com.androidplot.ui.VerticalPositioning; +import com.androidplot.ui.widget.TextLabelWidget; +import com.androidplot.util.AttrUtils; +import com.androidplot.util.DisplayDimensions; +import com.androidplot.util.PixelUtils; +import com.halfhp.fig.Fig; +import com.halfhp.fig.FigException; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Base class for all Plot implementations. + */ +public abstract class Plot, + RegistryType extends SeriesRegistry> + extends View implements Resizable { + private static final String TAG = Plot.class.getName(); + private static final String XML_ATTR_PREFIX = "androidplot"; + private static final String BASE_PACKAGE = "com.androidplot."; + + private static final int DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP = 10; + + public DisplayDimensions getDisplayDimensions() { + return displayDims; + } + + /** + * Used for caching renderer instances. Note that once a renderer is initialized it remains initialized + * for the life of the application; does not and should not be destroyed until the application exits. + */ + public HashMap, RendererType> getRenderers() { + return renderers; + } + + /** + * Associates lists series and getFormatter pairs with the class of the Renderer used to render them. + */ + public RegistryType getRegistry() { + return registry; + } + + public void setRegistry(RegistryType registry) { + this.registry = registry; + for(BundleType bundle : registry.getSeriesAndFormatterList()) { + attachSeries(bundle.getSeries(), bundle.getFormatter()); + } + } + + /** + * + * @return A new instance of RegistryType + */ + protected abstract RegistryType getRegistryInstance(); + + public TextLabelWidget getTitle() { + return title; + } + + public void setTitle(TextLabelWidget title) { + this.title = title; + } + + public void setTitle(String title) { + getTitle().setText(title); + } + + public enum BorderStyle { + ROUNDED, + SQUARE, + NONE + } + + /** + * The RenderMode used by a Plot to draw it's self onto the screen. The RenderMode can be set + * in two ways. + * + * In an xml layout: + * + * + * + * + * + * Programatically: + * + * + * XYPlot myPlot = new XYPlot(context "MyPlot", Plot.RenderMode.USE_MAIN_THREAD); + * + * + * A Plot's RenderMode cannot be changed after the plot has been initialized. + * @since 0.5.1 + */ + public enum RenderMode { + /** + * Do everything in the primary thread. This is the preferred method of drawing static charts + * and dynamic data that consists of a small number of points. This mode uses less memory at + * the cost of poor CPU utilization. + * + * XML value: use_main_thread + * @since 0.5.1 + */ + USE_MAIN_THREAD, + + /** + * Use a second thread and an off-screen buffer to do drawing. This is the preferred method + * of drawing dynamic data and static data that consists of a large number of points. This mode + * provides more efficient CPU utilization at the cost of increased memory usage. As of + * version 0.5.1 this is the default RenderMode. + * + * XML value: use_background_thread + * @since 0.5.1 + */ + USE_BACKGROUND_THREAD + } + private BoxModel boxModel = new BoxModel(); + + // no border by default: + private BorderStyle borderStyle = Plot.BorderStyle.NONE; + private float borderRadiusX = 15; + private float borderRadiusY = 15; + private Paint borderPaint; + private Paint backgroundPaint; + private LayoutManager layoutManager; + private TextLabelWidget title; + private DisplayDimensions displayDims = new DisplayDimensions(); + private RenderMode renderMode = RenderMode.USE_MAIN_THREAD; + private final BufferedCanvas pingPong = new BufferedCanvas(); + + // used to get rid of flickering when drawing offScreenBitmap to the visible Canvas. + private final Object renderSync = new Object(); + + private HashMap, RendererType> renderers; + + private RegistryType registry; + private final ArrayList listeners; + + private Thread renderThread; + private boolean keepRunning = false; + private boolean isIdle = true; + + { + listeners = new ArrayList<>(); + registry = getRegistryInstance(); + renderers = new HashMap<>(); + + borderPaint = new Paint(); + borderPaint.setColor(Color.rgb(150, 150, 150)); + borderPaint.setStyle(Paint.Style.STROKE); + borderPaint.setStrokeWidth(1.0f); + borderPaint.setAntiAlias(true); + backgroundPaint = new Paint(); + backgroundPaint.setColor(Color.DKGRAY); + backgroundPaint.setStyle(Paint.Style.FILL); + } + + + /** + * Any rendering that utilizes a buffer from this class should synchronize rendering on the instance of this class + * that is being used. + */ + private static class BufferedCanvas { + private int lastHeight = 0; + private int lastWidth = 0; + private volatile Bitmap bgBuffer; // all drawing is done on this buffer. + private volatile Bitmap fgBuffer; + private Canvas canvas = new Canvas(); + + /** + * Call this method once drawing on a Canvas retrieved by {@link #getCanvas()} to mark + * the buffer as fully rendered. Failure to call this method will result in nothing being drawn. + */ + public synchronized void swap() { + Bitmap tmp = bgBuffer; + bgBuffer = fgBuffer; + fgBuffer = tmp; + } + + /** + * Used when rendering in background mode and a view is attached + * but not resized, so that rendering buffers will be reinitialized. + */ + public void resizeToLast() { + resize(lastHeight, lastWidth); + } + + public synchronized void resize(int h, int w) { + if (w <= 0 || h <= 0) { + bgBuffer = null; + fgBuffer = null; + } else { + lastHeight = h; + lastWidth = w; + try { + bgBuffer = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); + fgBuffer = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); + } catch(IllegalArgumentException e) { + throw new IllegalArgumentException("Illegal argument passed to Bitmap.createBitmap. width: " + w + " height: " + h); + } + } + } + + public void recycle() { + /** + * TODO: Issue #93 There have been rare reports of NPE's originating from here. + * Most likely there is something deeper that is amiss, but for now we'll simply + * do a null check before recycling. + */ + if(bgBuffer != null) { + bgBuffer.recycle(); + bgBuffer = null; + } + + if(fgBuffer != null) { + fgBuffer.recycle(); + fgBuffer = null; + } + + System.gc(); + } + + /** + * Get a Canvas for drawing. Actual drawing should be synchronized on the instance + * of BufferedCanvas being used. + * @return The Canvas instance to draw onto. Returns null if drawing buffers have not + * been initialized a la {@link #resize(int, int)}. + */ + public synchronized Canvas getCanvas() { + if(bgBuffer != null) { + canvas.setBitmap(bgBuffer); + return canvas; + } else { + return null; + } + } + + /** + * @return The most recent fully rendered Bitmsp + */ + public Bitmap getBitmap() { + return fgBuffer; + } + } + + /** + * Convenience constructor - wraps {@link #Plot(android.content.Context, String, com.androidplot.Plot.RenderMode)}. + * RenderMode is set to {@link RenderMode#USE_BACKGROUND_THREAD}. + * @param context + * @param title The display title of this Plot. + */ + public Plot(Context context, String title) { + this(context, title, RenderMode.USE_MAIN_THREAD); + } + + /** + * Used for programmatic instantiation. + * @param context + * @param title The display title of this Plot. + */ + public Plot(Context context, String title, RenderMode mode) { + super(context); + this.renderMode = mode; + init(context, null, 0); + getTitle().setText(title); + } + + + /** + * Required by super-class. Extending class' implementations should add + * the following code immediately before exiting to ensure that loadAttrs + * is called only once by the derived class: + * + * if(getClass().equals(DerivedPlot.class) { + * loadAttrs(context, attrs); + * } + * + * + * See {@link com.androidplot.xy.XYPlot#XYPlot(android.content.Context, android.util.AttributeSet)} + * for an example. + * @param context + * @param attrs + */ + public Plot(Context context, AttributeSet attrs) { + super(context, attrs); + init(context, attrs, 0); + } + + /** + * Required by super-class. Extending class' implementations should add + * the following code immediately before exiting to ensure that loadAttrs + * is called only once by the derived class: + * + * if(getClass().equals(DerivedPlot.class) { + * loadAttrs(context, attrs); + * } + * + * + * See {@link com.androidplot.xy.XYPlot#XYPlot(android.content.Context, android.util.AttributeSet, int)} + * for an example. + * @param context + * @param attrs + * @param defStyle + */ + public Plot(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(context, attrs, defStyle); + } + + /** + * Can be overridden by derived classes to control hardware acceleration state. + * Note that this setting is only used on Honeycomb and later environments. + * @return True if hardware acceleration is allowed, false otherwise. + * @since 0.5.1 + */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + protected boolean isHwAccelerationSupported() { + return false; + } + + /** + * Sets the render mode used by the Plot. + * WARNING: This method is not currently designed for general use outside of Configurator. + * Attempting to reassign the render mode at runtime will result in unexpected behavior. + * @param mode + */ + public void setRenderMode(RenderMode mode) { + this.renderMode = mode; + } + + /** + * Concrete implementations may do any final setup / initialization + * here. Immediately following this method's invocation, AndroidPlot assumes + * that the Plot instance is ready for final configuration via the Configurator. + */ + protected void onPreInit() { + // nothing to do by default + } + + /** + * Invoked immediately following configurator / styleable attr application. + */ + protected void onAfterConfig() { + // nothing to do by default + } + + protected final void init(Context context, AttributeSet attrs, int defStyle) { + PixelUtils.init(context); + layoutManager = new LayoutManager(); + title = new TextLabelWidget(layoutManager, new Size(25, + SizeMode.ABSOLUTE, 100, + SizeMode.ABSOLUTE), + TextOrientation.HORIZONTAL); + title.position(0, HorizontalPositioning.RELATIVE_TO_CENTER, 0, + VerticalPositioning.ABSOLUTE_FROM_TOP, Anchor.TOP_MIDDLE); + + // initialize attr defaults: + title.getLabelPaint().setTextSize( + PixelUtils.spToPix(DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP)); + + onPreInit(); + // make sure the title widget is always the topmost widget: + layoutManager.moveToTop(title); + if(context != null && attrs != null) { + loadAttrs(attrs, defStyle); + } + + onAfterConfig(); + + layoutManager.onPostInit(); + if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { + startBackgroundRendering(); + } + } + + protected void startBackgroundRendering() { + if(renderThread != null) { + return; + } + + renderThread = new Thread(() -> { + System.out.println("Thread started with id " + this.hashCode()); + + keepRunning = true; + while (keepRunning) { + isIdle = false; + synchronized (pingPong) { + Canvas c = pingPong.getCanvas(); + renderOnCanvas(c); + pingPong.swap(); + } + synchronized (renderSync) { + postInvalidate(); + // prevent this thread from becoming an orphan + // after the view is destroyed + if (keepRunning) { + try { + renderSync.wait(); + } catch (InterruptedException e) { + keepRunning = false; + } + } + } + } + System.out.println("Thread exited with id " + this.hashCode()); + renderThread = null; + pingPong.recycle(); + }, "Androidplot renderThread"); + } + + /** + * If a styleable is available for the derived class, this method will be invoked with those attrs. + * The derived implementation is only responsible for setting derived class attributes, ie. it should + * not attempt to apply the Plot.title styleable attribute etc. Do not invoke recycle() on attrs. + * @param attrs Attrs for the derived class. + */ + protected abstract void processAttrs(TypedArray attrs); + + /** + * Apply base class attrs. + * @param attrs + */ + private void processBaseAttrs(TypedArray attrs) { + + // markup mode + boolean markupEnabled = attrs.getBoolean(R.styleable.Plot_markupEnabled, false); + setMarkupEnabled(markupEnabled); + + // renderMode + RenderMode renderMode = RenderMode.values() + [attrs.getInt(R.styleable.Plot_renderMode, getRenderMode().ordinal())]; + if(renderMode != getRenderMode()) { + setRenderMode(renderMode); + } + + // margins & padding + AttrUtils.configureBoxModelable(attrs, boxModel, R.styleable.Plot_marginTop, R.styleable.Plot_marginBottom, + R.styleable.Plot_marginLeft, R.styleable.Plot_marginRight, R.styleable.Plot_paddingTop, + R.styleable.Plot_paddingBottom, R.styleable.Plot_paddingLeft, R.styleable.Plot_paddingRight); + + // title + getTitle().setText(attrs.getString(R.styleable.Plot_title)); + getTitle().getLabelPaint().setTextSize( + attrs.getDimension(R.styleable.Plot_titleTextSize, + PixelUtils.spToPix(DEFAULT_TITLE_WIDGET_TEXT_SIZE_SP))); + + getTitle().getLabelPaint().setColor(attrs.getColor( + R.styleable.Plot_titleTextColor, getTitle().getLabelPaint().getColor())); + + getBackgroundPaint().setColor( + attrs.getColor(R.styleable.Plot_backgroundColor, getBackgroundPaint().getColor())); + + AttrUtils.configureLinePaint(attrs, getBorderPaint(), + R.styleable.Plot_borderColor, R.styleable.Plot_borderThickness); + } + + /** + * Parse XML Attributes. Should only be called once and at the end of the base class constructor. + * The first-pass attempts to locate styleable attributes and apply those first. After that, + * configurator-style attributes are applied, overriding any styleable attrs that may have + * been previously applied. + * + * @param attrs + */ + private void loadAttrs(AttributeSet attrs, int defStyle) { + + if (attrs != null) { + + Field styleableFieldInR = null; + TypedArray typedAttrs = null; + + Class styleableClass = R.styleable.class; + String styleableName = getClass().getName().substring(BASE_PACKAGE.length()); + styleableName = styleableName.replace('.', '_'); + try { + /** + * Use reflection to safely run for the existence of styleable defs for Plot + * and it's derivatives. This safety run is necessary to avoid runtime exceptions + * in apps that don't include Androidplot as a .aar and won't have access to + * the resources defined in the core library. + */ + styleableFieldInR = styleableClass.getField(styleableName); + } catch (NoSuchFieldException e) { + Log.d(TAG, "Styleable definition not found for: " + styleableName); + } + if (styleableFieldInR != null) { + try { + int[] resIds = (int[]) styleableFieldInR.get(null); + typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0); + } catch (IllegalAccessException e) { + // nothing to do + } finally { + if (typedAttrs != null) { + // apply derived class' attrs: + processAttrs(typedAttrs); + typedAttrs.recycle(); + } + } + } + + try { + styleableFieldInR = styleableClass.getField(Plot.class.getSimpleName()); + if (styleableFieldInR != null) { + int[] resIds = (int[]) styleableFieldInR.get(null); + typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0); + } + } catch (IllegalAccessException e) { + // nothing to do + } catch (NoSuchFieldException e) { + Log.d(TAG, "Styleable definition not found for: " + Plot.class.getSimpleName()); + } finally { + if (typedAttrs != null) { + // apply base attrs: + processBaseAttrs(typedAttrs); + typedAttrs.recycle(); + } + } + + // apply "configurator" attrs: (overrides any previously applied styleable attrs) + // filter out androidplot prefixed attrs: + HashMap attrHash = new HashMap<>(); + for (int i = 0; i < attrs.getAttributeCount(); i++) { + String attrName = attrs.getAttributeName(i); + + // case insensitive run to see if this attr begins with our prefix: + if (attrName != null && attrName.toUpperCase().startsWith(XML_ATTR_PREFIX.toUpperCase())) { + attrHash.put(attrName.substring(XML_ATTR_PREFIX.length() + 1), attrs.getAttributeValue(i)); + } + } + try { + Fig.configure(getContext(), this, attrHash); + } catch (FigException e) { + throw new RuntimeException(e); + } + } + } + + public RenderMode getRenderMode() { + return renderMode; + } + + public synchronized boolean addListener(PlotListener listener) { + return !listeners.contains(listener) && listeners.add(listener); + } + + public synchronized boolean removeListener(PlotListener listener) { + return listeners.remove(listener); + } + + protected ArrayList getListeners() { + return listeners; + } + + protected void notifyListenersBeforeDraw(Canvas canvas) { + for (PlotListener listener : listeners) { + listener.onBeforeDraw(this, canvas); + } + } + + protected void notifyListenersAfterDraw(Canvas canvas) { + for (PlotListener listener : listeners) { + listener.onAfterDraw(this, canvas); + } + } + + /** + * Convenience method to add a multiple series at once using the same formatter. + * If a problem is encountered, the method immediately returns false and the plot + * will contain whatever series were added before the failure. + * @param formatter + * @param series + * @return True if all series were successfully added, false otherwise. + * @since 0.9.7 + */ + public synchronized boolean addSeries(FormatterType formatter, SeriesType... series) { + for(SeriesType s : series) { + if(!addSeries(s, formatter)) { + return false; + } + } + return true; + } + + /** + * Add a new Series to the Plot. + * @param series + * @param formatter + * @return True if the series was added or false if the series / formatter pair already exists in the registry. + */ + public synchronized boolean addSeries(SeriesType series, FormatterType formatter) { + final boolean result = getRegistry().add(series, formatter); + attachSeries(series, formatter); + return result; + } + + protected void attachSeries(SeriesType series, FormatterType formatter) { + + Class rendererClass = formatter.getRendererClass(); + + // initialize the Renderer if necessary: + if(!getRenderers().containsKey(rendererClass)) { + getRenderers().put(rendererClass, (RendererType) formatter.getRendererInstance(this)); + } + + // if this series implements PlotListener, add it as a listener: + if(series instanceof PlotListener) { + addListener((PlotListener)series); + } + } + + /** + * + * @param series + * @param rendererClass + * @return The {@link SeriesBundle} that matches the series and rendererClass params, or null if one is not found. + */ + protected SeriesBundle getSeries(SeriesType series, Class rendererClass) { + for(SeriesBundle thisPair : getSeries(series)) { + if(thisPair.getFormatter().getRendererClass() == rendererClass) { + return thisPair; + } + } + return null; + } + + /** + * + * @param series + * @return A List of {@link SeriesBundle} instances that reference series. + */ + protected List> getSeries(SeriesType series) { + return getRegistry().get(series); + } + + /** + * + * Remove a series for a specific Renderer only. Use {@link #removeSeries(Series)} to remove the series + * from the plot completely. + * @param series + * @param rendererClass + * @return True if anything was removed, false otherwise + */ + public synchronized boolean removeSeries(SeriesType series, Class rendererClass) { + + List removedItems = getRegistry().remove(series, rendererClass); + + // if series implements PlotListener and is not assigned to any other renderers remove it as a listener: + if (removedItems.size() == 1 && series instanceof PlotListener) { + removeListener((PlotListener) series); + return true; + } + return false; + } + + /** + * Remove all occurrences of series regardless of the associated Renderer. + * @param series + */ + public synchronized void removeSeries(SeriesType series) { + // if series implements PlotListener, remove it from listeners: + if (series instanceof PlotListener) { + removeListener((PlotListener) series); + } + + getRegistry().remove(series); + } + + /** + * Remove all series from the plot. + */ + public void clear() { + for(SeriesType series : getRegistry().getSeriesList()) { + if(series instanceof PlotListener) { + removeListener((PlotListener) series); + } + } + getRegistry().clear(); + } + + public boolean isEmpty() { + return getRegistry().isEmpty(); + } + + /** + * + * @param series + * @param rendererClass + * @return The Formatter instance corresponding to the specified series / renderer pair. + */ + public FormatterType getFormatter(SeriesType series, Class rendererClass) { + return getSeries(series, rendererClass).getFormatter(); + } + + public T getRenderer(Class rendererClass) { + return (T) getRenderers().get(rendererClass); + } + + public List getRendererList() { + return new ArrayList<>(getRenderers().values()); + } + + public void setMarkupEnabled(boolean enabled) { + this.layoutManager.setMarkupEnabled(enabled); + } + + /** + * Causes the plot to be redrawn. + * @since 0.5.1 + */ + public void redraw() { + + if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { + + // only enter synchronized block if the call is expected to block OR + // if the render thread is idle, so we know that we won't have to wait to + // obtain a lock. + if (renderThread != null && isIdle) { + synchronized (renderSync) { + renderSync.notify(); + } + } + + } else if(renderMode == RenderMode.USE_MAIN_THREAD) { + + // are we on the UI thread? + if (Looper.myLooper() == Looper.getMainLooper()) { + invalidate(); + } else { + postInvalidate(); + } + } else { + throw new IllegalArgumentException("Unsupported Render Mode: " + renderMode); + } + } + + @Override + public synchronized void layout(final DisplayDimensions dims) { + this.displayDims = dims; + layoutManager.layout(displayDims); + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + synchronized(renderSync) { + keepRunning = false; + renderSync.notify(); + } + } + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + + // necessary to support rendering in recyclerview etc. + if(renderMode == RenderMode.USE_BACKGROUND_THREAD && renderThread == null) { + pingPong.resizeToLast(); + startBackgroundRendering(); + renderThread.start(); + } + } + + @Override + protected synchronized void onSizeChanged (int w, int h, int oldw, int oldh) { + + // update pixel conversion values + PixelUtils.init(getContext()); + + // disable hardware acceleration if it's not explicitly supported + // by the current Plot implementation. this run only applies to + // honeycomb and later environments. + if (Build.VERSION.SDK_INT >= 11) { + if (!isHwAccelerationSupported() && isHardwareAccelerated()) { + setLayerType(View.LAYER_TYPE_SOFTWARE, null); + } + } + + // pingPong is only used in background rendering mode. + if(renderMode == RenderMode.USE_BACKGROUND_THREAD) { + pingPong.resize(h, w); + } + + RectF cRect = new RectF(0, 0, w, h); + RectF mRect = boxModel.getMarginatedRect(cRect); + RectF pRect = boxModel.getPaddedRect(mRect); + + layout(new DisplayDimensions(cRect, mRect, pRect)); + super.onSizeChanged(w, h, oldw, oldh); + if(renderThread != null && !renderThread.isAlive()) { + renderThread.start(); + } + } + + /** + * Called whenever the plot needs to be drawn via the Handler, which invokes invalidate(). + * Should never be called directly; use {@link #redraw()} instead. + * @param canvas + */ + @Override + protected void onDraw(Canvas canvas) { + if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { + synchronized(pingPong) { + Bitmap bmp = pingPong.getBitmap(); + if(bmp != null) { + canvas.drawBitmap(bmp, 0, 0, null); + } + } + } else if (renderMode == RenderMode.USE_MAIN_THREAD) { + renderOnCanvas(canvas); + } else { + throw new IllegalArgumentException("Unsupported Render Mode: " + renderMode); + } + } + + /** + * Renders the plot onto a canvas. Used by both main thread to draw directly + * onto the View's canvas as well as by background draw to render onto a + * Bitmap buffer. At the end of the day this is the main entry for a plot's + * "heavy lifting". + * @param canvas + */ + protected synchronized void renderOnCanvas(@Nullable Canvas canvas) { + if(canvas == null) { + return; + } + try { + // any series interested in synchronizing with plot should + // implement PlotListener.onBeforeDraw(...) and do a read lock from within its + // invocation. This is the entry point into that call: + notifyListenersBeforeDraw(canvas); + try { + // need to completely erase what was on the canvas before redrawing, otherwise + // some odd aliasing artifacts begin to build up around the edges of aa'd entities + // over time. + canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); + if (backgroundPaint != null) { + drawBackground(canvas, displayDims.marginatedRect); + } + + layoutManager.draw(canvas); + + if (getBorderPaint() != null) { + drawBorder(canvas, displayDims.marginatedRect); + } + } catch (Exception e) { + Log.e(TAG, "Exception while rendering Plot.", e); + } + + isIdle = true; + // any series interested in synchronizing with plot should + // implement PlotListener.onAfterDraw(...) and do a read unlock from within that + // invocation. This is the entry point for that invocation. + notifyListenersAfterDraw(canvas); + } finally { + } + } + + + /** + * Sets the visual style of the plot's border. + * @param style + * @param radiusX Sets the X radius for BorderStyle.ROUNDED. Use null for all other styles. + * @param radiusY Sets the Y radius for BorderStyle.ROUNDED. Use null for all other styles. + */ + public void setBorderStyle(BorderStyle style, Float radiusX, Float radiusY) { + if (style == Plot.BorderStyle.ROUNDED) { + if (radiusX == null || radiusY == null){ + throw new IllegalArgumentException("radiusX and radiusY cannot be null when using BorderStyle.ROUNDED"); + } + this.borderRadiusX = radiusX; + this.borderRadiusY = radiusY; + } + this.borderStyle = style; + } + + /** + * Draws the plot's outer border. + * @param canvas + */ + protected void drawBorder(Canvas canvas, RectF dims) { + drawRect(canvas, dims, borderPaint); + } + + protected void drawBackground(Canvas canvas, RectF dims) { + drawRect(canvas, dims, backgroundPaint); + } + + protected void drawRect(Canvas canvas, RectF dims, Paint paint) { + switch (borderStyle) { + case ROUNDED: + canvas.drawRoundRect(dims, borderRadiusX, borderRadiusY, paint); + break; + case SQUARE: + default: + canvas.drawRect(dims, paint); + break; + } + } + + public LayoutManager getLayoutManager() { + return layoutManager; + } + + public void setLayoutManager(LayoutManager layoutManager) { + this.layoutManager = layoutManager; + } + + public Paint getBackgroundPaint() { + return backgroundPaint; + } + + public void setBackgroundPaint(Paint backgroundPaint) { + this.backgroundPaint = backgroundPaint; + } + + /** + * Convenience method - wraps the individual setMarginXXX methods into a single method. + * @param left + * @param top + * @param right + * @param bottom + */ + public void setPlotMargins(float left, float top, float right, float bottom) { + setPlotMarginLeft(left); + setPlotMarginTop(top); + setPlotMarginRight(right); + setPlotMarginBottom(bottom); + } + + /** + * Convenience method - wraps the individual setPaddingXXX methods into a single method. + * @param left + * @param top + * @param right + * @param bottom + */ + public void setPlotPadding(float left, float top, float right, float bottom) { + setPlotPaddingLeft(left); + setPlotPaddingTop(top); + setPlotPaddingRight(right); + setPlotPaddingBottom(bottom); + } + + public float getPlotMarginTop() { + return boxModel.getMarginTop(); + } + + public void setPlotMarginTop(float plotMarginTop) { + boxModel.setMarginTop(plotMarginTop); + } + + public float getPlotMarginBottom() { + return boxModel.getMarginBottom(); + } + + public void setPlotMarginBottom(float plotMarginBottom) { + boxModel.setMarginBottom(plotMarginBottom); + } + + public float getPlotMarginLeft() { + return boxModel.getMarginLeft(); + } + + public void setPlotMarginLeft(float plotMarginLeft) { + boxModel.setMarginLeft(plotMarginLeft); + } + + public float getPlotMarginRight() { + return boxModel.getMarginRight(); + } + + public void setPlotMarginRight(float plotMarginRight) { + boxModel.setMarginRight(plotMarginRight); + } + + public float getPlotPaddingTop() { + return boxModel.getPaddingTop(); + } + + public void setPlotPaddingTop(float plotPaddingTop) { + boxModel.setPaddingTop(plotPaddingTop); + } + + public float getPlotPaddingBottom() { + return boxModel.getPaddingBottom(); + } + + public void setPlotPaddingBottom(float plotPaddingBottom) { + boxModel.setPaddingBottom(plotPaddingBottom); + } + + public float getPlotPaddingLeft() { + return boxModel.getPaddingLeft(); + } + + public void setPlotPaddingLeft(float plotPaddingLeft) { + boxModel.setPaddingLeft(plotPaddingLeft); + } + + public float getPlotPaddingRight() { + return boxModel.getPaddingRight(); + } + + public void setPlotPaddingRight(float plotPaddingRight) { + boxModel.setPaddingRight(plotPaddingRight); + } + + public Paint getBorderPaint() { + return borderPaint; + } + + /** + * Set's the paint used to draw the border. Note that this method + * copies borderPaint and set's the copy's Paint.Style attribute to + * Paint.Style.STROKE. + * @param borderPaint + */ + public void setBorderPaint(Paint borderPaint) { + if(borderPaint == null) { + this.borderPaint = null; + } else { + this.borderPaint = new Paint(borderPaint); + this.borderPaint.setStyle(Paint.Style.STROKE); + } + } +} diff --git a/androidplot-core/src/main/java/com/androidplot/exception/PlotRenderException.java b/androidplot-core/src/main/java/com/androidplot/exception/PlotRenderException.java deleted file mode 100644 index 62a6e6d9..00000000 --- a/androidplot-core/src/main/java/com/androidplot/exception/PlotRenderException.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2015 AndroidPlot.com - * - * 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 com.androidplot.exception; - -public class PlotRenderException extends Exception { - public PlotRenderException(String message) { - super(message); - } -} diff --git a/androidplot-core/src/main/java/com/androidplot/pie/PieLegendItem.java b/androidplot-core/src/main/java/com/androidplot/pie/PieLegendItem.java index 8b4e9913..669b188b 100644 --- a/androidplot-core/src/main/java/com/androidplot/pie/PieLegendItem.java +++ b/androidplot-core/src/main/java/com/androidplot/pie/PieLegendItem.java @@ -1,7 +1,7 @@ package com.androidplot.pie; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.ui.widget.LegendItem; diff --git a/androidplot-core/src/main/java/com/androidplot/pie/PieLegendWidget.java b/androidplot-core/src/main/java/com/androidplot/pie/PieLegendWidget.java index c59b7f0b..4d1ccd03 100644 --- a/androidplot-core/src/main/java/com/androidplot/pie/PieLegendWidget.java +++ b/androidplot-core/src/main/java/com/androidplot/pie/PieLegendWidget.java @@ -2,7 +2,7 @@ import android.graphics.Canvas; import android.graphics.RectF; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.ui.LayoutManager; import com.androidplot.ui.SeriesBundle; diff --git a/androidplot-core/src/main/java/com/androidplot/pie/PieRenderer.java b/androidplot-core/src/main/java/com/androidplot/pie/PieRenderer.java index dc83e620..db8921dc 100644 --- a/androidplot-core/src/main/java/com/androidplot/pie/PieRenderer.java +++ b/androidplot-core/src/main/java/com/androidplot/pie/PieRenderer.java @@ -18,7 +18,6 @@ import android.graphics.*; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.SeriesBundle; import com.androidplot.ui.SeriesRenderer; import com.androidplot.ui.RenderStack; @@ -58,7 +57,7 @@ public float getRadius(RectF rect) { @Override public void onRender(Canvas canvas, RectF plotArea, Segment series, SegmentFormatter formatter, - RenderStack stack) throws PlotRenderException { + RenderStack stack) { // This renderer renders all series in one shot, so exclude any remaining series // from causing subsequent invocations of onRender: @@ -170,7 +169,7 @@ protected void drawSegment(Canvas canvas, RectF bounds, Segment seg, SegmentForm canvas.drawLine(r1Inner.x, r1Inner.y, r1Outer.x, r1Outer.y, f.getRadialEdgePaint()); canvas.drawLine(r2Inner.x, r2Inner.y, r2Outer.x, r2Outer.y, f.getRadialEdgePaint()); } else { - canvas.save(Canvas.CLIP_SAVE_FLAG); + canvas.save(); Path chart = new Path(); chart.addCircle(cx, cy, outerRad, Path.Direction.CW); Path inside = new Path(); diff --git a/androidplot-core/src/main/java/com/androidplot/pie/PieWidget.java b/androidplot-core/src/main/java/com/androidplot/pie/PieWidget.java index 38c23b27..1b7b2a80 100644 --- a/androidplot-core/src/main/java/com/androidplot/pie/PieWidget.java +++ b/androidplot-core/src/main/java/com/androidplot/pie/PieWidget.java @@ -17,7 +17,6 @@ package com.androidplot.pie; import android.graphics.*; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.LayoutManager; import com.androidplot.ui.Size; import com.androidplot.ui.widget.Widget; @@ -38,7 +37,7 @@ public PieWidget(LayoutManager layoutManager, PieChart pieChart, Size metrics) { } @Override - protected void doOnDraw(Canvas canvas, RectF widgetRect) throws PlotRenderException { + protected void doOnDraw(Canvas canvas, RectF widgetRect) { renderStack.sync(); for(RenderStack.StackElement thisElement : renderStack.getElements()) { if(thisElement.isEnabled()) { diff --git a/androidplot-core/src/main/java/com/androidplot/ui/LayoutManager.java b/androidplot-core/src/main/java/com/androidplot/ui/LayoutManager.java index e4c5cce5..45f79a43 100644 --- a/androidplot-core/src/main/java/com/androidplot/ui/LayoutManager.java +++ b/androidplot-core/src/main/java/com/androidplot/ui/LayoutManager.java @@ -25,7 +25,6 @@ import android.view.MotionEvent; import android.view.View; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.widget.Widget; import com.androidplot.util.DisplayDimensions; import com.androidplot.util.LinkedLayerList; @@ -83,7 +82,7 @@ public void setMarkupEnabled(boolean enabled) { setDrawOutlineShadowsEnabled(enabled); } - public void draw(Canvas canvas) throws PlotRenderException { + public void draw(Canvas canvas) { if(isDrawMarginsEnabled()) { drawSpacing(canvas, displayDims.canvasRect, displayDims.marginatedRect, marginPaint); } @@ -92,7 +91,7 @@ public void draw(Canvas canvas) throws PlotRenderException { } for (Widget widget : elements()) { try { - canvas.save(Canvas.ALL_SAVE_FLAG); + canvas.save(); PositionMetrics metrics = widget.getPositionMetrics(); float elementWidth = widget.getWidthPix(displayDims.paddedRect.width()); float elementHeight = widget.getHeightPix(displayDims.paddedRect.height()); @@ -140,7 +139,7 @@ public void draw(Canvas canvas) throws PlotRenderException { private static void drawSpacing(Canvas canvas, RectF outer, RectF inner, Paint paint) { try { - canvas.save(Canvas.ALL_SAVE_FLAG); + canvas.save(); canvas.clipRect(inner, Region.Op.DIFFERENCE); canvas.drawRect(outer, paint); } finally { diff --git a/androidplot-core/src/main/java/com/androidplot/ui/PositionMetrics.java b/androidplot-core/src/main/java/com/androidplot/ui/PositionMetrics.java index 88efddcb..377e9e04 100644 --- a/androidplot-core/src/main/java/com/androidplot/ui/PositionMetrics.java +++ b/androidplot-core/src/main/java/com/androidplot/ui/PositionMetrics.java @@ -16,7 +16,7 @@ package com.androidplot.ui; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; public class PositionMetrics implements Comparable { diff --git a/androidplot-core/src/main/java/com/androidplot/ui/SeriesRenderer.java b/androidplot-core/src/main/java/com/androidplot/ui/SeriesRenderer.java index 882bdcfc..bfedeeb8 100644 --- a/androidplot-core/src/main/java/com/androidplot/ui/SeriesRenderer.java +++ b/androidplot-core/src/main/java/com/androidplot/ui/SeriesRenderer.java @@ -20,7 +20,6 @@ import android.graphics.RectF; import android.graphics.Region; import com.androidplot.Series; -import com.androidplot.exception.PlotRenderException; import com.androidplot.Plot; import java.util.ArrayList; @@ -52,10 +51,9 @@ public SeriesFormatterType getFormatter(SeriesType series) { * @param canvas * @param plotArea * @param sfPair The series / formatter pair to be rendered - * @throws PlotRenderException */ public void render(Canvas canvas, RectF plotArea, SeriesBundle sfPair, RenderStack stack) throws PlotRenderException { + SeriesFormatterType> sfPair, RenderStack stack) { onRender(canvas, plotArea, sfPair.getSeries(), sfPair.getFormatter(), stack); } @@ -67,10 +65,9 @@ public void render(Canvas canvas, RectF plotArea, SeriesBundle items = getLegendItems(); if(legendItemComparator != null) { Collections.sort(items, legendItemComparator); diff --git a/androidplot-core/src/main/java/com/androidplot/ui/widget/TextLabelWidget.java b/androidplot-core/src/main/java/com/androidplot/ui/widget/TextLabelWidget.java index 8c6e84cd..06bf54ff 100644 --- a/androidplot-core/src/main/java/com/androidplot/ui/widget/TextLabelWidget.java +++ b/androidplot-core/src/main/java/com/androidplot/ui/widget/TextLabelWidget.java @@ -101,7 +101,7 @@ public void doOnDraw(Canvas canvas, RectF widgetRect) { Anchor.CENTER); try { - canvas.save(Canvas.ALL_SAVE_FLAG); + canvas.save(); canvas.translate(start.x, start.y); switch (orientation) { case HORIZONTAL: diff --git a/androidplot-core/src/main/java/com/androidplot/ui/widget/Widget.java b/androidplot-core/src/main/java/com/androidplot/ui/widget/Widget.java index d66b85a8..6d21767b 100644 --- a/androidplot-core/src/main/java/com/androidplot/ui/widget/Widget.java +++ b/androidplot-core/src/main/java/com/androidplot/ui/widget/Widget.java @@ -17,10 +17,9 @@ package com.androidplot.ui.widget; import android.graphics.*; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; +import androidx.annotation.Nullable; +import androidx.annotation.NonNull; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.*; import com.androidplot.util.DisplayDimensions; import com.androidplot.ui.HorizontalPositioning; @@ -372,7 +371,7 @@ protected void onResize(@Nullable RectF oldRect, @NonNull RectF newRect) { // do nothing by default } - public void draw(Canvas canvas) throws PlotRenderException { + public void draw(Canvas canvas) { if (isVisible()) { if (backgroundPaint != null) { drawBackground(canvas, widgetDimensions.canvasRect); @@ -439,7 +438,7 @@ protected void drawBackground(Canvas canvas, RectF widgetRect) { * @param canvas The Canvas to draw onto * @param widgetRect the size and coordinates of this widget */ - protected abstract void doOnDraw(Canvas canvas, RectF widgetRect) throws PlotRenderException; + protected abstract void doOnDraw(Canvas canvas, RectF widgetRect); public Paint getBorderPaint() { return borderPaint; diff --git a/androidplot-core/src/main/java/com/androidplot/util/FastNumber.java b/androidplot-core/src/main/java/com/androidplot/util/FastNumber.java index 72e8a25d..4fa11d8a 100644 --- a/androidplot-core/src/main/java/com/androidplot/util/FastNumber.java +++ b/androidplot-core/src/main/java/com/androidplot/util/FastNumber.java @@ -1,7 +1,7 @@ package com.androidplot.util; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; /** * An extension of {@link Number} optimized for speed at the cost of memory. diff --git a/androidplot-core/src/main/java/com/androidplot/xy/AdvancedLineAndPointRenderer.java b/androidplot-core/src/main/java/com/androidplot/xy/AdvancedLineAndPointRenderer.java index ee3e7e24..11b9e8e8 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/AdvancedLineAndPointRenderer.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/AdvancedLineAndPointRenderer.java @@ -18,7 +18,6 @@ import android.content.*; import android.graphics.*; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.RenderStack; import com.androidplot.ui.SeriesRenderer; @@ -41,7 +40,7 @@ public AdvancedLineAndPointRenderer(XYPlot plot) { } @Override - protected void onRender(Canvas canvas, RectF plotArea, XYSeries series, Formatter formatter, RenderStack stack) throws PlotRenderException { + protected void onRender(Canvas canvas, RectF plotArea, XYSeries series, Formatter formatter, RenderStack stack) { PointF thisPoint; PointF lastPoint = null; for (int i = 0; i < series.size(); i++) { diff --git a/androidplot-core/src/main/java/com/androidplot/xy/BarRenderer.java b/androidplot-core/src/main/java/com/androidplot/xy/BarRenderer.java index bb8c4c7f..ced83885 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/BarRenderer.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/BarRenderer.java @@ -51,7 +51,13 @@ public class BarRenderer extends GroupRender public enum BarOrientation { /** - * Bars are drawn "overlapping" one another, with taller bars being drawn behind + * Bars are drawn overlapping one another, in the order their respective series + * was added to the plot. + */ + IN_ORDER, + + /** + * Bars are drawn overlapping one another, with taller bars being drawn behind * the shorter ones. */ OVERLAID, // bars are overlaid in descending y-val order (largest val in back) @@ -187,6 +193,7 @@ public void onRender(Canvas canvas, RectF plotArea, List -0.001 && scale < 0.001) { - return false; - } - return true; + return !Float.isInfinite(scale) + && !Float.isNaN(scale) + && (!(scale > -0.001) || !(scale < 0.001)); } protected void zoom(final MotionEvent motionEvent) { @@ -349,14 +405,14 @@ protected void zoom(final MotionEvent motionEvent) { Zoom.STRETCH_BOTH, Zoom.SCALE).contains(zoom)) { calculateZoom(newRect, scaleX, true); - plot.setDomainBoundaries(newRect.left, newRect.right, BoundaryMode.FIXED); + adjustDomainBoundary(newRect.left, newRect.right, BoundaryMode.FIXED); } if (EnumSet.of( Zoom.STRETCH_VERTICAL, Zoom.STRETCH_BOTH, Zoom.SCALE).contains(zoom)) { calculateZoom(newRect, scaleY, false); - plot.setRangeBoundaries(newRect.top, newRect.bottom, BoundaryMode.FIXED); + adjustRangeBoundary(newRect.top, newRect.bottom, BoundaryMode.FIXED); } plot.redraw(); } diff --git a/androidplot-core/src/main/java/com/androidplot/xy/ValueMarker.java b/androidplot-core/src/main/java/com/androidplot/xy/ValueMarker.java index 30e9aacd..de0436b2 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/ValueMarker.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/ValueMarker.java @@ -16,10 +16,14 @@ package com.androidplot.xy; +import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; +import android.graphics.RectF; + import com.androidplot.ui.PositionMetric; import com.androidplot.ui.TextOrientation; +import com.androidplot.util.FontUtils; /** * Encapsulates a single axis line marker drawn onto an XYPlot at a specified value. @@ -27,6 +31,8 @@ */ public abstract class ValueMarker { + private static final int MARKER_LABEL_SPACING = 2; + public String getText() { return text; } @@ -135,4 +141,37 @@ public PositionMetricType getTextPosition() { public void setTextPosition(PositionMetricType textPosition) { this.textPosition = textPosition; } + + /** + * Renders the text associated with user defined markers + * + * @param canvas + * @param text + * @param gridRect + * @param x + * @param y + */ + protected void drawMarkerText(Canvas canvas, String text, RectF gridRect, + float x, float y) { + if (getText() != null) { + x += MARKER_LABEL_SPACING; + y -= MARKER_LABEL_SPACING; + RectF textRect = new RectF(FontUtils.getStringDimensions(text, getTextPaint() + )); + textRect.offsetTo(x, y - textRect.height()); + + if (textRect.right > gridRect.right) { + textRect.offset(-(textRect.right - gridRect.right), 0); + } + + if (textRect.top < gridRect.top) { + textRect.offset(0, gridRect.top - textRect.top); + } + + canvas.drawText(text, textRect.left, textRect.bottom, getTextPaint() + ); + } + } + + public abstract void draw(Canvas canvas, XYPlot plot, RectF gridRect); } diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XValueMarker.java b/androidplot-core/src/main/java/com/androidplot/xy/XValueMarker.java index af02ca64..a4c12438 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XValueMarker.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XValueMarker.java @@ -16,7 +16,10 @@ package com.androidplot.xy; +import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.RectF; + import com.androidplot.ui.VerticalPositioning; import com.androidplot.ui.VerticalPosition; @@ -55,4 +58,19 @@ public XValueMarker(Number value, String text, VerticalPosition textPosition, Pa public XValueMarker(Number value, String text, VerticalPosition textPosition, int linePaint, int textPaint) { super(value, text, textPosition, linePaint, textPaint); } + + @Override + public void draw(Canvas canvas, XYPlot plot, RectF gridRect) { + if (getValue() != null) { + float xPix = (float) plot.getBounds().xRegion + .transform(getValue().doubleValue(), gridRect.left, gridRect.right, false); + canvas.drawLine(xPix, gridRect.top, xPix, gridRect.bottom, getLinePaint() + ); + float yPix = getTextPosition().getPixelValue(gridRect.height()); + yPix += gridRect.top; + if (getText() != null) { + drawMarkerText(canvas, getText(), gridRect, xPix, yPix); + } + } + } } diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XYConstraints.java b/androidplot-core/src/main/java/com/androidplot/xy/XYConstraints.java index 58338264..c4452d33 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XYConstraints.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XYConstraints.java @@ -16,8 +16,8 @@ package com.androidplot.xy; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; /** * Calculates the min/max constraints for an xy plane. diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XYGraphWidget.java b/androidplot-core/src/main/java/com/androidplot/xy/XYGraphWidget.java index 23506f64..8fa0571f 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XYGraphWidget.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XYGraphWidget.java @@ -22,12 +22,11 @@ import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.androidplot.R; import com.androidplot.Region; -import com.androidplot.exception.PlotRenderException; import com.androidplot.ui.Insets; import com.androidplot.ui.LayoutManager; import com.androidplot.ui.RenderStack; @@ -63,8 +62,6 @@ public class XYGraphWidget extends Widget { private static final float DEFAULT_LINE_LABEL_TEXT_SIZE_PX = PixelUtils.spToPix(15); - private static final int MARKER_LABEL_SPACING = TWO; - /** * Line interval per range label */ @@ -530,13 +527,19 @@ protected float seriesToScreenY(Number y) { @Override protected void onResize(@Nullable RectF oldRect, @NonNull RectF newRect) { - gridRect = RectFUtils.applyInsets(newRect, gridInsets); - labelRect = RectFUtils.applyInsets(newRect, lineLabelInsets); + recalculateSizes(newRect); + } + + protected void recalculateSizes(@Nullable RectF rect) { + if(rect == null) { + rect = getWidgetDimensions().paddedRect; + } + gridRect = RectFUtils.applyInsets(rect, gridInsets); + labelRect = RectFUtils.applyInsets(rect, lineLabelInsets); } @Override - protected void doOnDraw(Canvas canvas, RectF widgetRect) - throws PlotRenderException { + protected void doOnDraw(Canvas canvas, RectF widgetRect) { // don't draw if we have no space to draw into if (gridRect.height() > ZERO && gridRect.width() > ZERO) { @@ -561,7 +564,7 @@ protected void doOnDraw(Canvas canvas, RectF widgetRect) } protected void drawDomainLine(Canvas canvas, float xPix, Number xVal, - Paint linePaint, boolean isOrigin) { + Paint linePaint, boolean isOrigin, boolean shouldDrawLabel) { // lines if (linePaint != null) { @@ -571,12 +574,19 @@ protected void drawDomainLine(Canvas canvas, float xPix, Number xVal, } // labels - drawLineLabel(canvas, Edge.TOP, xVal, xPix, labelRect.top, isOrigin); - drawLineLabel(canvas, Edge.BOTTOM, xVal, xPix, labelRect.bottom, isOrigin); + if(shouldDrawLabel) { + if (isLineLabelEnabled(Edge.TOP)) { + drawLineLabel(canvas, Edge.TOP, xVal, xPix, labelRect.top, isOrigin); + } + + if (isLineLabelEnabled(Edge.BOTTOM)) { + drawLineLabel(canvas, Edge.BOTTOM, xVal, xPix, labelRect.bottom, isOrigin); + } + } } protected void drawRangeLine(Canvas canvas, float yPix, Number yVal, - Paint linePaint, boolean isOrigin) { + Paint linePaint, boolean isOrigin, boolean shouldDrawLabel) { // lines if (linePaint != null) { canvas.drawLine(gridRect.left - lineExtensionLeft, yPix, @@ -584,9 +594,15 @@ protected void drawRangeLine(Canvas canvas, float yPix, Number yVal, ); } - // labels - drawLineLabel(canvas, Edge.LEFT, yVal, labelRect.left, yPix, isOrigin); - drawLineLabel(canvas, Edge.RIGHT, yVal, labelRect.right, yPix, isOrigin); + if(shouldDrawLabel) { + // labels + if (isLineLabelEnabled(Edge.LEFT)) { + drawLineLabel(canvas, Edge.LEFT, yVal, labelRect.left, yPix, isOrigin); + } + if (isLineLabelEnabled(Edge.RIGHT)) { + drawLineLabel(canvas, Edge.RIGHT, yVal, labelRect.right, yPix, isOrigin); + } + } } protected void drawLineLabel(Canvas canvas, @@ -595,9 +611,7 @@ protected void drawLineLabel(Canvas canvas, float x, float y, boolean isOrigin) { - if (isLineLabelEnabled(edge)) { - getLineLabelRenderer(edge).drawLabel(canvas, getLineLabelStyle(edge), val, x, y, isOrigin); - } + getLineLabelRenderer(edge).drawLabel(canvas, getLineLabelStyle(edge), val, x, y, isOrigin); } /** @@ -643,7 +657,7 @@ protected void drawGrid(Canvas canvas) { } else { linePaint = domainSubGridLinePaint; } - drawDomainLine(canvas, (float) xPix, xVal, linePaint, isOrigin); + drawDomainLine(canvas, (float) xPix, xVal, linePaint, isOrigin, isMajorTick); } Number rangeOrigin = plot.getRangeOrigin(); @@ -681,79 +695,20 @@ protected void drawGrid(Canvas canvas) { } else { linePaint = rangeSubGridLinePaint; } - drawRangeLine(canvas, (float) yPix, yVal, linePaint, isOrigin); - } - } - - /** - * Renders the text associated with user defined markers - * - * @param canvas - * @param text - * @param marker - * @param x - * @param y - */ - private void drawMarkerText(Canvas canvas, String text, ValueMarker marker, - float x, float y) { - x += MARKER_LABEL_SPACING; - y -= MARKER_LABEL_SPACING; - RectF textRect = new RectF(FontUtils.getStringDimensions( - text, - marker.getTextPaint() - )); - textRect.offsetTo(x, y - textRect.height()); - - if (textRect.right > gridRect.right) { - textRect.offset(-(textRect.right - gridRect.right), ZERO); - } - - if (textRect.top < gridRect.top) { - textRect.offset(0, gridRect.top - textRect.top); + drawRangeLine(canvas, (float) yPix, yVal, linePaint, isOrigin, isMajorTick); } - - canvas.drawText(text, textRect.left, textRect.bottom, - marker.getTextPaint() - ); } protected void drawMarkers(Canvas canvas) { if (plot.getYValueMarkers() != null && plot.getYValueMarkers().size() > 0) { for (YValueMarker marker : plot.getYValueMarkers()) { - if (marker.getValue() != null) { - float yPix = (float) plot.getBounds().yRegion - .transform(marker.getValue() - .doubleValue(), gridRect.top, gridRect.bottom, true); - canvas.drawLine(gridRect.left, yPix, - gridRect.right, yPix, marker.getLinePaint() - ); - - float xPix = marker.getTextPosition().getPixelValue( - gridRect.width()); - xPix += gridRect.left; - - if (marker.getText() != null) { - drawMarkerText(canvas, marker.getText(), marker, xPix, yPix); - } - } + marker.draw(canvas, plot, gridRect); } } if (plot.getXValueMarkers() != null && plot.getXValueMarkers().size() > 0) { for (XValueMarker marker : plot.getXValueMarkers()) { - if (marker.getValue() != null) { - float xPix = (float) plot.getBounds().xRegion - .transform(marker.getValue() - .doubleValue(), gridRect.left, gridRect.right, false); - canvas.drawLine(xPix, gridRect.top, xPix, gridRect.bottom, - marker.getLinePaint() - ); - float yPix = marker.getTextPosition().getPixelValue(gridRect.height()); - yPix += gridRect.top; - if (marker.getText() != null) { - drawMarkerText(canvas, marker.getText(), marker, xPix, yPix); - } - } + marker.draw(canvas, plot, gridRect); } } } @@ -833,15 +788,14 @@ protected void drawGridBackground(Canvas canvas) { * Draws lines and points for each element in the series. * * @param canvas - * @throws PlotRenderException */ - protected void drawData(Canvas canvas) throws PlotRenderException { + protected void drawData(Canvas canvas) { if (drawGridOnTop) { drawGridBackground(canvas); } try { if (isGridClippingEnabled) { - canvas.save(Canvas.ALL_SAVE_FLAG); + canvas.save(); canvas.clipRect(gridRect, android.graphics.Region.Op.INTERSECT); } @@ -1149,6 +1103,7 @@ public Insets getGridInsets() { public void setGridInsets(Insets gridInsets) { this.gridInsets = gridInsets; + recalculateSizes(null); } /** @@ -1160,6 +1115,7 @@ public Insets getLineLabelInsets() { public void setLineLabelInsets(Insets lineLabelInsets) { this.lineLabelInsets = lineLabelInsets; + recalculateSizes(null); } public RectF getGridRect() { diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XYLegendItem.java b/androidplot-core/src/main/java/com/androidplot/xy/XYLegendItem.java index 1fd10ebd..51c67159 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XYLegendItem.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XYLegendItem.java @@ -1,6 +1,6 @@ package com.androidplot.xy; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.ui.widget.LegendItem; diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XYLegendWidget.java b/androidplot-core/src/main/java/com/androidplot/xy/XYLegendWidget.java index f08783cb..680fd4b2 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XYLegendWidget.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XYLegendWidget.java @@ -17,7 +17,7 @@ package com.androidplot.xy; import android.graphics.*; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.ui.LayoutManager; import com.androidplot.ui.SeriesBundle; diff --git a/androidplot-core/src/main/java/com/androidplot/xy/XYPlot.java b/androidplot-core/src/main/java/com/androidplot/xy/XYPlot.java index 67eaafa8..e519b5a0 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/XYPlot.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/XYPlot.java @@ -22,7 +22,7 @@ import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import android.util.AttributeSet; import com.androidplot.Plot; diff --git a/androidplot-core/src/main/java/com/androidplot/xy/YValueMarker.java b/androidplot-core/src/main/java/com/androidplot/xy/YValueMarker.java index f76dadd5..0e4aa435 100644 --- a/androidplot-core/src/main/java/com/androidplot/xy/YValueMarker.java +++ b/androidplot-core/src/main/java/com/androidplot/xy/YValueMarker.java @@ -16,7 +16,10 @@ package com.androidplot.xy; +import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.RectF; + import com.androidplot.ui.HorizontalPositioning; import com.androidplot.ui.HorizontalPosition; @@ -55,4 +58,21 @@ public YValueMarker(Number value, String text, HorizontalPosition textPosition, public YValueMarker(Number value, String text, HorizontalPosition textPosition, int linePaint, int textPaint) { super(value, text, textPosition, linePaint, textPaint); } + + @Override + public void draw(Canvas canvas, XYPlot plot, RectF gridRect) { + if (getValue() != null) { + float yPix = (float) plot.getBounds().yRegion + .transform(getValue() + .doubleValue(), gridRect.top, gridRect.bottom, true); + canvas.drawLine(gridRect.left, yPix, + gridRect.right, yPix, getLinePaint() + ); + + float xPix = getTextPosition().getPixelValue( + gridRect.width()); + xPix += gridRect.left; + drawMarkerText(canvas, getText(), gridRect, xPix, yPix); + } + } } diff --git a/androidplot-core/src/main/res/values/attrs.xml b/androidplot-core/src/main/res/values/attrs.xml index 535ccf18..5c714912 100644 --- a/androidplot-core/src/main/res/values/attrs.xml +++ b/androidplot-core/src/main/res/values/attrs.xml @@ -30,8 +30,8 @@ Supported Elements: - + diff --git a/androidplot-core/src/test/java/com/androidplot/PlotTest.java b/androidplot-core/src/test/java/com/androidplot/PlotTest.java index dc5e5e88..9e4753bf 100644 --- a/androidplot-core/src/test/java/com/androidplot/PlotTest.java +++ b/androidplot-core/src/test/java/com/androidplot/PlotTest.java @@ -20,11 +20,8 @@ import android.graphics.*; import android.util.*; -import com.androidplot.exception.PlotRenderException; import com.androidplot.test.*; import com.androidplot.ui.*; -import com.androidplot.xy.LineAndPointFormatter; -import com.androidplot.xy.SimpleXYSeries; import com.halfhp.fig.*; import org.junit.Test; import org.mockito.Mock; @@ -36,8 +33,8 @@ import static junit.framework.Assert.assertNotSame; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -47,8 +44,9 @@ public class PlotTest extends AndroidplotTest { SeriesRegistry mockSeriesRegistry; @Test - public void testInit_withoutAttrs() throws Exception { - Plot plot = mock(Plot.class); + public void testInit_withoutAttrs() { + //Plot plot = mock(Plot.class); + Plot plot = spy(new MockPlot("MockPlot")); plot.init(RuntimeEnvironment.application, null, 0); verify(plot, times(1)).onPreInit(); @@ -56,15 +54,17 @@ public void testInit_withoutAttrs() throws Exception { } @Test - public void testInit_withAttrs() throws Exception { - Plot plot = new MockPlot("MockPlot"); + public void testInit_withAttrs() { + Plot plot = spy(new MockPlot("MockPlot")); AttributeSet attrs = mock(AttributeSet.class); plot.init(RuntimeEnvironment.application, attrs, 0); - // TODO: verifications + + verify(plot, times(1)).onPreInit(); + verify(plot, times(1)).onAfterConfig(); } @Test - public void testAddSeries() throws Exception { + public void testAddSeries() { Plot plot = new MockPlot("MockPlot"); MockSeries m1 = new MockSeries(); @@ -97,7 +97,7 @@ public void testAddSeries() throws Exception { } @Test - public void testRemoveSeries() throws Exception { + public void testRemoveSeries() { Plot plot = new MockPlot("MockPlot"); @@ -157,7 +157,7 @@ public void testRemoveSeries() throws Exception { @Test - public void testGetFormatter() throws Exception { + public void testGetFormatter() { Plot plot = new MockPlot("MockPlot"); MockSeries m1 = new MockSeries(); @@ -185,7 +185,7 @@ public void testGetFormatter() throws Exception { } @Test - public void testGetRendererList() throws Exception { + public void testGetRendererList() { Plot plot = new MockPlot("MockPlot"); @@ -206,7 +206,7 @@ public void testGetRendererList() throws Exception { } @Test - public void testAddListener() throws Exception { + public void testAddListener() { Plot plot = new MockPlot("MockPlot"); ArrayList listeners = plot.getListeners(); @@ -232,7 +232,7 @@ public void testAddListener() throws Exception { } @Test - public void testRemoveListener() throws Exception { + public void testRemoveListener() { Plot plot = new MockPlot("MockPlot"); ArrayList listeners = plot.getListeners(); @@ -379,7 +379,7 @@ public MockRenderer1(Plot plot) { } @Override - public void onRender(Canvas canvas, RectF plotArea, Series series, Formatter formatter, RenderStack stack) throws PlotRenderException { + public void onRender(Canvas canvas, RectF plotArea, Series series, Formatter formatter, RenderStack stack) { } @@ -396,7 +396,7 @@ public MockRenderer2(Plot plot) { } @Override - public void onRender(Canvas canvas, RectF plotArea, Series series, Formatter formatter, RenderStack stack) throws PlotRenderException { + public void onRender(Canvas canvas, RectF plotArea, Series series, Formatter formatter, RenderStack stack) { } diff --git a/androidplot-core/src/test/java/com/androidplot/test/TestUtils.java b/androidplot-core/src/test/java/com/androidplot/test/TestUtils.java index ecb78333..1f8f1457 100644 --- a/androidplot-core/src/test/java/com/androidplot/test/TestUtils.java +++ b/androidplot-core/src/test/java/com/androidplot/test/TestUtils.java @@ -56,11 +56,11 @@ public static XYSeries generateXYSeriesWithNulls(String title, int size) { */ @SuppressLint("NewApi") public static MotionEvent newPointerDownEvent(int finger1x, int finger1y, int finger2x, int finger2y) { - MotionEvent me = MotionEvent.obtain(0, 0, 0, 0, 0, 0); + MotionEvent me = MotionEvent.obtain(0, 0, MotionEvent.ACTION_POINTER_DOWN, finger1x, finger1y, 0); ShadowMotionEvent sme = shadowOf(me); - sme.setAction(MotionEvent.ACTION_POINTER_DOWN); + //sme.setAction(MotionEvent.ACTION_POINTER_DOWN); sme.setPointerIds(0, 1); - sme.setLocation(finger1x, finger1y); + //sme.setLocation(finger1x, finger1y); sme.setPointer2(finger2x, finger2y); return me; } diff --git a/androidplot-core/src/test/java/com/androidplot/ui/widget/TextLabelWidgetTest.java b/androidplot-core/src/test/java/com/androidplot/ui/widget/TextLabelWidgetTest.java index 6ed81b7b..bdb48f92 100644 --- a/androidplot-core/src/test/java/com/androidplot/ui/widget/TextLabelWidgetTest.java +++ b/androidplot-core/src/test/java/com/androidplot/ui/widget/TextLabelWidgetTest.java @@ -14,9 +14,9 @@ import org.mockito.InOrder; import org.mockito.Mock; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyFloat; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; diff --git a/androidplot-core/src/test/java/com/androidplot/ui/widget/WidgetTest.java b/androidplot-core/src/test/java/com/androidplot/ui/widget/WidgetTest.java index db81d57c..cae6c056 100644 --- a/androidplot-core/src/test/java/com/androidplot/ui/widget/WidgetTest.java +++ b/androidplot-core/src/test/java/com/androidplot/ui/widget/WidgetTest.java @@ -2,9 +2,8 @@ import android.graphics.Canvas; import android.graphics.RectF; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; -import com.androidplot.exception.PlotRenderException; import com.androidplot.test.AndroidplotTest; import com.androidplot.ui.Anchor; import com.androidplot.ui.HorizontalPositioning; @@ -22,8 +21,10 @@ import org.mockito.Mockito; import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -88,14 +89,14 @@ public void position_withAnchor_updatesPositionWithNewAnchor() { } @Test - public void draw_sizeChanged_invokesOnResizeBeforeDoOnDraw() throws Exception { + public void draw_sizeChanged_invokesOnResizeBeforeDoOnDraw() { InOrder inOrder = Mockito.inOrder(widget); widget.draw(canvas); - inOrder.verify(widget).onResize(any(RectF.class), any(RectF.class)); + inOrder.verify(widget).onResize(isNull(), any(RectF.class)); inOrder.verify(widget).doOnDraw(eq(canvas), any(RectF.class)); - verify(widget).onResize(any(RectF.class), any(RectF.class)); + verify(widget).onResize(isNull(), any(RectF.class)); } static class TestWidget extends Widget { @@ -105,7 +106,7 @@ public TestWidget(@NonNull LayoutManager layoutManager, @NonNull Size size) { } @Override - protected void doOnDraw(Canvas canvas, RectF widgetRect) throws PlotRenderException { + protected void doOnDraw(Canvas canvas, RectF widgetRect) { // nothing to do } } diff --git a/androidplot-core/src/test/java/com/androidplot/util/PlotStatisticsTest.java b/androidplot-core/src/test/java/com/androidplot/util/PlotStatisticsTest.java index b063235a..4454c69c 100644 --- a/androidplot-core/src/test/java/com/androidplot/util/PlotStatisticsTest.java +++ b/androidplot-core/src/test/java/com/androidplot/util/PlotStatisticsTest.java @@ -27,9 +27,9 @@ import org.mockito.InjectMocks; import org.mockito.Mock; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyFloat; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; diff --git a/androidplot-core/src/test/java/com/androidplot/xy/AdvanceLineAndPointRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/AdvanceLineAndPointRendererTest.java index 647882c5..b1600828 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/AdvanceLineAndPointRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/AdvanceLineAndPointRendererTest.java @@ -24,7 +24,6 @@ import org.junit.*; import org.mockito.*; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** diff --git a/androidplot-core/src/test/java/com/androidplot/xy/BarRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/BarRendererTest.java index 2bb317b5..08cc1480 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/BarRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/BarRendererTest.java @@ -33,9 +33,9 @@ import java.util.List; import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyFloat; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -61,14 +61,14 @@ public class BarRendererTest extends AndroidplotTest { ArgumentCaptor rectCaptor; @Before - public void setUp() throws Exception { + public void setUp() { canvas = spy(new Canvas()); xyPlot = spy(new XYPlot(getContext(), "My Plot")); barFormatter = spy(new BarFormatter(Color.RED, Color.RED)); } @Test - public void testOnRender_handlesNullValues() throws Exception { + public void onRender_handlesNullValues() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", null, 5, null); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", null, 5, null); @@ -83,7 +83,7 @@ public void testOnRender_handlesNullValues() throws Exception { } @Test - public void testOnRender_stacked() throws Exception { + public void onRender_stacked() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 2, 5, 7); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 8, 5, 3); @@ -119,7 +119,7 @@ public void testOnRender_stacked() throws Exception { } @Test - public void testOnRender_sideBySide() throws Exception { + public void onRender_sideBySide() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 0, 5, 10); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 1, 7.5, 10); @@ -150,7 +150,35 @@ public void testOnRender_sideBySide() throws Exception { } @Test - public void testOnRender_overlaid() throws Exception { + public void onRender_inOrder_drawsFirstAddedSeriesFirst() { + XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 1, 5, 6); + XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 2, 4, 7); + + BarRenderer renderer = setupRendererForTesting(s1, s2); + renderer.setBarOrientation(BarRenderer.BarOrientation.IN_ORDER); + + xyPlot.setUserRangeOrigin(0); + xyPlot.calculateMinMaxVals(); + renderer.onRender(canvas, plotArea, s1, barFormatter, renderStack); + + verify(renderer, times(6)) + .drawBar(eq(canvas), barCaptor.capture(), rectCaptor.capture()); + + // list of all bars drawn, in the exact order they were drawn. + List bars = barCaptor.getAllValues(); + + assertEquals(bars.get(0).getY(), s1.getY(0)); + assertEquals(bars.get(1).getY(), s2.getY(0)); + + assertEquals(bars.get(2).getY(), s1.getY(1)); + assertEquals(bars.get(3).getY(), s2.getY(1)); + + assertEquals(bars.get(4).getY(), s1.getY(2)); + assertEquals(bars.get(5).getY(), s2.getY(2)); + } + + @Test + public void onRender_overlaid_drawsBarsWithExpectedHeight() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 0, 5, 10); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 1, 7.5, 10); @@ -183,10 +211,9 @@ public void testOnRender_overlaid() throws Exception { /** * Verify that positive values are drawn in order of highest yVal, while negative values are * drawn in order of lowest yVal. - * @throws Exception */ @Test - public void testOnRender_overlaid_drawsBarsInOrder() throws Exception { + public void onRender_overlaid_drawsSmallestBarsLast() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", -1, -2, 1, 2); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", -2, -1, 2, 1); @@ -211,7 +238,7 @@ public void testOnRender_overlaid_drawsBarsInOrder() throws Exception { } @Test - public void testFixedBarWidth() throws Exception { + public void onRender_fixedBarWidth_rendersAllBarsWithSameWidth() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 0, 5, 10); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 1, 7.5, 10); @@ -233,7 +260,7 @@ public void testFixedBarWidth() throws Exception { } @Test - public void testFixedGapWidth() throws Exception { + public void onRender_fixedGapWidth_rendersFixedGapBetweenAllBars() { XYSeries s1 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s1", 0, 5, 10); XYSeries s2 = new SimpleXYSeries(SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "s2", 1, 7.5, 10); diff --git a/androidplot-core/src/test/java/com/androidplot/xy/BubbleRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/BubbleRendererTest.java index cd0ff2b1..94a0be50 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/BubbleRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/BubbleRendererTest.java @@ -24,7 +24,6 @@ import org.junit.*; import org.mockito.*; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** diff --git a/androidplot-core/src/test/java/com/androidplot/xy/CandlestickRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/CandlestickRendererTest.java index a7fba775..8eda23b9 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/CandlestickRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/CandlestickRendererTest.java @@ -24,7 +24,6 @@ import org.junit.*; import org.mockito.*; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class CandlestickRendererTest extends AndroidplotTest { diff --git a/androidplot-core/src/test/java/com/androidplot/xy/FastLineAndPointRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/FastLineAndPointRendererTest.java index de81e70c..cf083d9e 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/FastLineAndPointRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/FastLineAndPointRendererTest.java @@ -24,8 +24,8 @@ import org.junit.runner.*; import org.mockito.*; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/androidplot-core/src/test/java/com/androidplot/xy/LTTBSamplerTest.java b/androidplot-core/src/test/java/com/androidplot/xy/LTTBSamplerTest.java index 3269082d..800992f9 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/LTTBSamplerTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/LTTBSamplerTest.java @@ -27,7 +27,6 @@ import java.util.*; import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class LTTBSamplerTest extends AndroidplotTest { diff --git a/androidplot-core/src/test/java/com/androidplot/xy/LineAndPointRendererTest.java b/androidplot-core/src/test/java/com/androidplot/xy/LineAndPointRendererTest.java index 9cb03cd1..44a7b22d 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/LineAndPointRendererTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/LineAndPointRendererTest.java @@ -26,7 +26,6 @@ import java.util.*; import static junit.framework.Assert.assertEquals; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; public class LineAndPointRendererTest extends AndroidplotTest { diff --git a/androidplot-core/src/test/java/com/androidplot/xy/XYGraphWidgetTest.java b/androidplot-core/src/test/java/com/androidplot/xy/XYGraphWidgetTest.java index 9f92afa8..a9182501 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/XYGraphWidgetTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/XYGraphWidgetTest.java @@ -28,11 +28,11 @@ import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; -import static junit.framework.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyFloat; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -67,7 +67,7 @@ public class XYGraphWidgetTest extends AndroidplotTest { @Before - public void setUp() throws Exception { + public void setUp() { size = spy(new Size(100, SizeMode.ABSOLUTE, 100, SizeMode.ABSOLUTE)); xyPlot = spy(new XYPlot(getContext(), "XYPlot")); when(xyPlot.getRegistry()).thenReturn(seriesRegistry); @@ -83,13 +83,8 @@ public void setUp() throws Exception { graphWidget.setLabelRect(new RectF(0, 0, 100, 100)); } - @After - public void tearDown() throws Exception { - - } - @Test - public void testProcessAttrs() throws Exception { + public void processAttrs_withDefaults_disablesGridClipping() { XYGraphWidget graphWidget = spy(new XYGraphWidget(layoutManager, xyPlot, size)); graphWidget.processAttrs(typedArray); @@ -97,7 +92,7 @@ public void testProcessAttrs() throws Exception { } @Test - public void testDoOnDraw_drawGridOnTopFalse() throws Exception { + public void doOnDraw_drawGridOnTopFalse_drawsGridAfterData() throws Exception { XYGraphWidget graphWidget = spy(new XYGraphWidget(layoutManager, xyPlot, size)); graphWidget.setDrawGridOnTop(false); doNothing().when(graphWidget).drawGrid(canvas); @@ -113,7 +108,7 @@ public void testDoOnDraw_drawGridOnTopFalse() throws Exception { } @Test - public void testDoOnDraw_drawGridOnTopTrue() throws Exception { + public void doOnDraw_drawGridOnTopTrue_drawsGridBeforeData() throws Exception { XYGraphWidget graphWidget = spy(new XYGraphWidget(layoutManager, xyPlot, size)); graphWidget.setDrawGridOnTop(true); doNothing().when(graphWidget).drawGrid(canvas); @@ -129,7 +124,7 @@ public void testDoOnDraw_drawGridOnTopTrue() throws Exception { } @Test - public void testDrawMarkers() throws Exception { + public void drawMarkers_drawsLineForEachMarker() { xyPlot.addMarker(new XValueMarker(1, "x")); xyPlot.addMarker(new YValueMarker(-1, "y")); @@ -140,42 +135,22 @@ public void testDrawMarkers() throws Exception { .drawLine(anyFloat(), anyFloat(), anyFloat(), anyFloat(), any(Paint.class)); } - protected void runDrawGridTest() { - doNothing().when(graphWidget). - drawDomainLine(any(Canvas.class), anyFloat(), any(Number.class), any(Paint.class), anyBoolean()); - - doNothing().when(graphWidget). - drawRangeLine(any(Canvas.class), anyFloat(), any(Number.class), any(Paint.class), anyBoolean()); - - xyPlot.setRangeBoundaries(0, 100, BoundaryMode.FIXED); - xyPlot.setDomainBoundaries(0, 100, BoundaryMode.FIXED); - - graphWidget.drawGrid(canvas); - - // expecting a 100x100 grid to be drawn: - verify(graphWidget, times(100)) - .drawDomainLine(eq(canvas), anyFloat(), anyFloat(), any(Paint.class), eq(false)); - - verify(graphWidget, times(100)) - .drawRangeLine(eq(canvas), anyFloat(), anyFloat(), any(Paint.class), eq(false)); - } - @Test - public void testDrawGrid_nullOrigin() throws Exception { + public void drawGrid_nullOrigin_drawsGrid() { when(xyPlot.getDomainOrigin()).thenReturn(null); when(xyPlot.getRangeOrigin()).thenReturn(null); runDrawGridTest(); } @Test - public void testDrawGrid_zeroOrigin() throws Exception { + public void drawGrid_zeroOrigin_drawsGrid() { when(xyPlot.getDomainOrigin()).thenReturn(0); when(xyPlot.getRangeOrigin()).thenReturn(0); runDrawGridTest(); } @Test - public void testDrawGrid_centeredOrigin() throws Exception { + public void drawGrid_centeredOrigin_drawsGrid() { // set origin to midpoint so we exercise // code to draw lines on both sides of the origin: @@ -185,7 +160,7 @@ public void testDrawGrid_centeredOrigin() throws Exception { } @Test - public void testDrawCursors_ifCursorPaintAndPositionAreSet() throws Exception { + public void drawCursors_withCursorPaintAndPosition_drawsCursorLines() { final Paint domainCursorPaint = new Paint(); graphWidget.setDomainCursorPaint(domainCursorPaint); @@ -201,7 +176,7 @@ public void testDrawCursors_ifCursorPaintAndPositionAreSet() throws Exception { } @Test - public void testDrawCursors_ifCursorPaintAndPositionAreNotSet() throws Exception { + public void testDrawCursors_noCursorPaintOrPosition_drawsNoCursorLines() { graphWidget.setDomainCursorPaint(null); graphWidget.setRangeCursorPaint(null); @@ -212,7 +187,7 @@ public void testDrawCursors_ifCursorPaintAndPositionAreNotSet() throws Exception } @Test - public void testDrawCursorLabel() throws Exception { + public void drawCursorLabel_drawsText() { graphWidget.setDomainCursorPosition(0f); graphWidget.setRangeCursorPosition(0f); XYGraphWidget.CursorLabelFormatter clf = mock(XYGraphWidget.CursorLabelFormatter.class); @@ -224,8 +199,7 @@ public void testDrawCursorLabel() throws Exception { } @Test - public void testSetLineLabelEdges() throws Exception { - + public void setLineLabelEdges_setsEdges() { graphWidget.setLineLabelEdges(XYGraphWidget.Edge.LEFT, XYGraphWidget.Edge.BOTTOM); assertTrue(graphWidget.isLineLabelEnabled(XYGraphWidget.Edge.LEFT)); assertTrue(graphWidget.isLineLabelEnabled(XYGraphWidget.Edge.BOTTOM)); @@ -238,7 +212,7 @@ public void testSetLineLabelEdges() throws Exception { } @Test - public void testSetLineLabelEdges_bitfield() throws Exception { + public void setLineLabelEdges_bitfield_setsEdges() { graphWidget.setLineLabelEdges( XYGraphWidget.Edge.TOP.getValue() | XYGraphWidget.Edge.RIGHT.getValue()); @@ -250,7 +224,7 @@ public void testSetLineLabelEdges_bitfield() throws Exception { } @Test - public void testScreenToSeries() throws Exception { + public void screenToSeries_returnsSeriesCoords() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); XYCoords coords = graphWidget.screenToSeries(new PointF(0, 0)); @@ -267,7 +241,7 @@ public void testScreenToSeries() throws Exception { } @Test - public void testSeriesToScreen() throws Exception { + public void seriesToScreen_returnsScreenPoint() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); PointF point = graphWidget.seriesToScreen(new XYCoords(-100, 100)); @@ -284,7 +258,7 @@ public void testSeriesToScreen() throws Exception { } @Test - public void testScreenToSeriesX() throws Exception { + public void screenToSeriesX_returnsSeriesValue() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); assertEquals(-100, graphWidget.screenToSeriesX(new PointF(0, 0)).intValue()); @@ -293,7 +267,7 @@ public void testScreenToSeriesX() throws Exception { } @Test - public void testScreenToSeriesY() throws Exception { + public void screenToSeriesY_returnsSeriesValue() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); assertEquals(100, graphWidget.screenToSeriesY(new PointF(0, 0)).intValue()); @@ -302,7 +276,7 @@ public void testScreenToSeriesY() throws Exception { } @Test - public void testSeriesToScreenX() throws Exception { + public void seriesToScreenX_returnsScreenValue() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); assertEquals(0f, graphWidget.seriesToScreenX(-100)); @@ -311,11 +285,45 @@ public void testSeriesToScreenX() throws Exception { } @Test - public void testSeriesToScreenY() throws Exception { + public void seriesToScreenY_returnsScreenValue() { when(xyPlot.getBounds()).thenReturn(new RectRegion(-100, 100, -100, 100)); assertEquals(100f, graphWidget.seriesToScreenY(100)); assertEquals(0f, graphWidget.seriesToScreenY(-100)); assertEquals(50f, graphWidget.seriesToScreenY(0)); } + + @Test + public void setGridInsets_updatesGridRect() { + graphWidget.setGridInsets(new com.androidplot.ui.Insets(0, 0, 0, 0)); + final RectF oldRect = graphWidget.getGridRect(); + + graphWidget.setGridInsets(new com.androidplot.ui.Insets(2, 2, 2, 2)); + final RectF newRect = graphWidget.getGridRect(); + + assertEquals(oldRect.left + 2, newRect.left); + assertEquals(oldRect.top + 2, newRect.top); + assertEquals(oldRect.right - 2, newRect.right); + assertEquals(oldRect.bottom -2, newRect.bottom); + } + + private void runDrawGridTest() { + doNothing().when(graphWidget). + drawDomainLine(any(Canvas.class), anyFloat(), any(Number.class), any(Paint.class), anyBoolean(), anyBoolean()); + + doNothing().when(graphWidget). + drawRangeLine(any(Canvas.class), anyFloat(), any(Number.class), any(Paint.class), anyBoolean(), anyBoolean()); + + xyPlot.setRangeBoundaries(0, 100, BoundaryMode.FIXED); + xyPlot.setDomainBoundaries(0, 100, BoundaryMode.FIXED); + + graphWidget.drawGrid(canvas); + + // expecting a 100x100 grid to be drawn: + verify(graphWidget, times(100)) + .drawDomainLine(eq(canvas), anyFloat(), anyDouble(), any(Paint.class), eq(false), anyBoolean()); + + verify(graphWidget, times(100)) + .drawRangeLine(eq(canvas), anyFloat(), anyDouble(), any(Paint.class), eq(false), anyBoolean()); + } } diff --git a/androidplot-core/src/test/java/com/androidplot/xy/XYLegendWidgetTest.java b/androidplot-core/src/test/java/com/androidplot/xy/XYLegendWidgetTest.java index b50f7237..778fb40a 100644 --- a/androidplot-core/src/test/java/com/androidplot/xy/XYLegendWidgetTest.java +++ b/androidplot-core/src/test/java/com/androidplot/xy/XYLegendWidgetTest.java @@ -32,11 +32,10 @@ import java.util.List; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/build.gradle b/build.gradle index d9bdfbfc..4b5e18de 100644 --- a/build.gradle +++ b/build.gradle @@ -14,35 +14,26 @@ * limitations under the License. */ -apply plugin: 'java' - -allprojects { - repositories { - jcenter() - } -} - ext { - theCompileSdkVersion = 26 - theTargetSdkVersion = 26 + theCompileSdkVersion = 34 + theTargetSdkVersion = 34 theMinSdkVersion = 5 - theVersionName = '1.5.5' - theVersionCode = 0 + theVersionName = '1.5.11' + theVersionCode = 227 + gitUrl = 'https://github.com/halfhp/androidplot.git' } buildscript { repositories { mavenCentral() - jcenter() + maven { url "https://plugins.gradle.org/m2/" } + maven { url 'https://s01.oss.sonatype.org/content/repositories/snapshots' } google() } dependencies { - classpath 'com.android.tools.build:gradle:3.0.1' - classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' - classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' - classpath 'com.vanniktech:gradle-android-junit-jacoco-plugin:0.6.0' - classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.6.3' + classpath 'com.android.tools.build:gradle:8.5.2' + classpath 'com.mxalbert.gradle:jacoco-android:0.2.0' } } @@ -52,7 +43,3 @@ allprojects { google() } } - -task wrapper(type: Wrapper) { - gradleVersion = '2.14.1' -} diff --git a/demoapp-wearable/build.gradle b/demoapp-wearable/build.gradle index b4afad27..666b353e 100644 --- a/demoapp-wearable/build.gradle +++ b/demoapp-wearable/build.gradle @@ -16,17 +16,14 @@ buildscript { repositories { - jcenter() + google() } dependencies { - classpath 'com.android.tools.build:gradle:3.0.1' + classpath 'com.android.tools.build:gradle:3.1.4' } } -apply plugin: 'com.android.application' -repositories { - jcenter() -} +apply plugin: 'com.android.application' android { compileSdkVersion theCompileSdkVersion @@ -41,9 +38,10 @@ android { } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_6 - targetCompatibility JavaVersion.VERSION_1_6 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } + buildTypes { release { minifyEnabled false @@ -54,6 +52,6 @@ android { dependencies { compile project(':androidplot-core') - compile 'com.google.android.support:wearable:1.3.0' + compile 'com.google.android.support:wearable:2.3.0' compile 'com.google.android.gms:play-services-wearable:8.3.0' } diff --git a/demoapp/build.gradle b/demoapp/build.gradle index c501ed33..2c2fbd52 100644 --- a/demoapp/build.gradle +++ b/demoapp/build.gradle @@ -14,35 +14,54 @@ * limitations under the License. */ -apply plugin: 'com.android.application' -apply plugin: 'com.github.triplet.play' - -dependencies { - compile project(':androidplot-core') - compile 'com.crittercism:crittercism-android-agent:5.4.0' - - debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1' - releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1' - testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1' -} - buildscript { - + ext.kotlin_version = '2.0.0' repositories { mavenCentral() } dependencies { - classpath 'com.github.triplet.gradle:play-publisher:1.1.5' + classpath 'com.github.triplet.gradle:play-publisher:3.6.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } +plugins { + id 'com.android.application' + id 'com.github.triplet.play' version '3.6.0' +} + +apply plugin: 'kotlin-android' + +dependencies { + implementation "androidx.core:core-ktx:1.13.1" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation project(':androidplot-core') + implementation 'androidx.recyclerview:recyclerview:1.3.2' + + debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.9.1' +} + +kotlin { + jvmToolchain(17) +} + android { + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + compileSdkVersion theCompileSdkVersion + buildFeatures { + viewBinding true + } + defaultConfig { versionCode theVersionCode versionName theVersionName - minSdkVersion 14 + minSdkVersion 19 targetSdkVersion theTargetSdkVersion applicationId "com.androidplot.demos" } @@ -66,18 +85,18 @@ android { debuggable true } } - - - /** - * TODO: uncomment this and address all the lint issues. - */ - lintOptions { + lint { abortOnError false } + namespace 'com.androidplot.demos' + } play { // see: https://github.com/Triple-T/gradle-play-publisher - jsonFile = file(System.getenv("PUBLISHER_ACCT_JSON_FILE") ?: "publisher.json") + serviceAccountCredentials.set(file(System.getenv("PUBLISHER_ACCT_JSON_FILE") ?: "publisher.json")) track = 'beta' } +repositories { + mavenCentral() +} diff --git a/demoapp/project.properties b/demoapp/project.properties index 29656f2d..90a2cb18 100644 --- a/demoapp/project.properties +++ b/demoapp/project.properties @@ -39,5 +39,3 @@ #proguard.config=${sdk.dir}\tools\proguard\proguard-android.txt:proguard-project.txt # using config with optimization enabled so that things like log statement removal will work: proguard.config=${sdk.dir}/tools/proguard/proguard-android-optimize.txt:proguard-project.txt -# Project target. -target=android-16 diff --git a/demoapp/src/main/AndroidManifest.xml b/demoapp/src/main/AndroidManifest.xml index 89f1428f..5b73a2b7 100644 --- a/demoapp/src/main/AndroidManifest.xml +++ b/demoapp/src/main/AndroidManifest.xml @@ -15,7 +15,7 @@ ~ limitations under the License. --> - + @@ -27,75 +27,88 @@ android:icon="@drawable/ic_launcher"> + android:label="@string/app_name" + android:exported="true"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:screenOrientation="landscape" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> + android:label="@string/app_name" + android:exported="false"> - + + @@ -111,7 +124,8 @@ + android:name="com.androidplot.demos.widget.DemoAppWidgetProvider" + android:exported="false"> diff --git a/demoapp/src/main/java/com/androidplot/demos/AnimatedXYPlotActivity.java b/demoapp/src/main/java/com/androidplot/demos/AnimatedXYPlotActivity.java index 75d9553b..43d3adc0 100644 --- a/demoapp/src/main/java/com/androidplot/demos/AnimatedXYPlotActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/AnimatedXYPlotActivity.java @@ -21,7 +21,7 @@ import android.app.Activity; import android.graphics.Color; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import android.view.animation.AccelerateDecelerateInterpolator; import com.androidplot.xy.BoundaryMode; diff --git a/demoapp/src/main/java/com/androidplot/demos/BarPlotExampleActivity.java b/demoapp/src/main/java/com/androidplot/demos/BarPlotExampleActivity.java index 8d8720d1..3cc2faa4 100644 --- a/demoapp/src/main/java/com/androidplot/demos/BarPlotExampleActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/BarPlotExampleActivity.java @@ -22,6 +22,7 @@ import java.text.ParsePosition; import java.util.Arrays; +import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Color; import android.graphics.Paint; @@ -86,6 +87,7 @@ private enum SeriesSize { private Pair selection; + @SuppressLint("ClickableViewAccessibility") @Override public void onCreate(Bundle savedInstanceState) { diff --git a/demoapp/src/main/java/com/androidplot/demos/CandlestickChartActivity.java b/demoapp/src/main/java/com/androidplot/demos/CandlestickChartActivity.java index 2c37580a..86ae1fbb 100644 --- a/demoapp/src/main/java/com/androidplot/demos/CandlestickChartActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/CandlestickChartActivity.java @@ -21,7 +21,7 @@ import android.graphics.DashPathEffect; import android.graphics.Paint; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.Region; import com.androidplot.util.PixelUtils; diff --git a/demoapp/src/main/java/com/androidplot/demos/DemoApplication.java b/demoapp/src/main/java/com/androidplot/demos/DemoApplication.java index 9c931a73..df3d6117 100644 --- a/demoapp/src/main/java/com/androidplot/demos/DemoApplication.java +++ b/demoapp/src/main/java/com/androidplot/demos/DemoApplication.java @@ -2,20 +2,10 @@ import android.app.*; -import com.squareup.leakcanary.*; - public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); - initLeakCanary(); - } - - protected void initLeakCanary() { - if (LeakCanary.isInAnalyzerProcess(this)) { - return; - } - LeakCanary.install(this); } } diff --git a/demoapp/src/main/java/com/androidplot/demos/DualScaleActivity.java b/demoapp/src/main/java/com/androidplot/demos/DualScaleActivity.java index d164710a..f0116121 100644 --- a/demoapp/src/main/java/com/androidplot/demos/DualScaleActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/DualScaleActivity.java @@ -20,7 +20,7 @@ import android.graphics.Color; import android.graphics.DashPathEffect; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.util.PixelUtils; import com.androidplot.xy.BoundaryMode; diff --git a/demoapp/src/main/java/com/androidplot/demos/DynamicXYPlotActivity.java b/demoapp/src/main/java/com/androidplot/demos/DynamicXYPlotActivity.java index f76dca01..f18b518b 100644 --- a/demoapp/src/main/java/com/androidplot/demos/DynamicXYPlotActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/DynamicXYPlotActivity.java @@ -138,8 +138,8 @@ public void notifyObservers() { private static final int MAX_AMP_SEED = 100; private static final int MIN_AMP_SEED = 10; private static final int AMP_STEP = 1; - public static final int SINE1 = 0; - public static final int SINE2 = 1; + static final int SINE1 = 0; + static final int SINE2 = 1; private static final int SAMPLE_SIZE = 31; private int phase = 0; private int sinAmp = 1; @@ -150,7 +150,7 @@ public void notifyObservers() { notifier = new MyObservable(); } - public void stopThread() { + void stopThread() { keepRunning = false; } @@ -181,18 +181,18 @@ public void run() { } } - public int getItemCount(int series) { + int getItemCount(int series) { return SAMPLE_SIZE; } - public Number getX(int series, int index) { + Number getX(int series, int index) { if (index >= SAMPLE_SIZE) { throw new IllegalArgumentException(); } return index; } - public Number getY(int series, int index) { + Number getY(int series, int index) { if (index >= SAMPLE_SIZE) { throw new IllegalArgumentException(); } @@ -208,7 +208,7 @@ public Number getY(int series, int index) { } } - public void addObserver(Observer observer) { + void addObserver(Observer observer) { notifier.addObserver(observer); } @@ -223,7 +223,7 @@ class SampleDynamicSeries implements XYSeries { private int seriesIndex; private String title; - public SampleDynamicSeries(SampleDynamicXYDatasource datasource, int seriesIndex, String title) { + SampleDynamicSeries(SampleDynamicXYDatasource datasource, int seriesIndex, String title) { this.datasource = datasource; this.seriesIndex = seriesIndex; this.title = title; diff --git a/demoapp/src/main/java/com/androidplot/demos/ECGExample.java b/demoapp/src/main/java/com/androidplot/demos/ECGExample.java index 31d71e87..2bd7dec5 100644 --- a/demoapp/src/main/java/com/androidplot/demos/ECGExample.java +++ b/demoapp/src/main/java/com/androidplot/demos/ECGExample.java @@ -82,7 +82,7 @@ public static class MyFadeFormatter extends AdvancedLineAndPointRenderer.Formatt private int trailSize; - public MyFadeFormatter(int trailSize) { + MyFadeFormatter(int trailSize) { this.trailSize = trailSize; } @@ -125,7 +125,7 @@ public static class ECGModel implements XYSeries { * @param size Sample size contained within this model * @param updateFreqHz Frequency at which new samples are added to the model */ - public ECGModel(int size, int updateFreqHz) { + ECGModel(int size, int updateFreqHz) { data = new Number[size]; for(int i = 0; i < data.length; i++) { data[i] = 0; @@ -176,7 +176,7 @@ public void run() { }); } - public void start(final WeakReference rendererRef) { + void start(final WeakReference rendererRef) { this.rendererRef = rendererRef; keepRunning = true; thread.start(); diff --git a/demoapp/src/main/java/com/androidplot/demos/ListViewActivity.java b/demoapp/src/main/java/com/androidplot/demos/ListViewActivity.java index 9d640053..290b7802 100644 --- a/demoapp/src/main/java/com/androidplot/demos/ListViewActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/ListViewActivity.java @@ -20,7 +20,7 @@ import android.content.Context; import android.graphics.Color; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -78,10 +78,10 @@ protected void generateData() { double bp = Math.random(); LineAndPointFormatter lpf = new LineAndPointFormatter( - Color.rgb(new Double(rl * 255).intValue(), - new Double(gl * 255).intValue(), new Double(bl * 255).intValue()), - Color.rgb(new Double(rp * 255).intValue(), - new Double(gp * 255).intValue(), new Double(bp * 255).intValue()), + Color.rgb(Double.valueOf(rl * 255).intValue(), + Double.valueOf(gl * 255).intValue(), Double.valueOf(bl * 255).intValue()), + Color.rgb(Double.valueOf(rp * 255).intValue(), + Double.valueOf(gp * 255).intValue(), Double.valueOf(bp * 255).intValue()), null, null); // for fun, configure interpolation on the formatter: diff --git a/demoapp/src/main/java/com/androidplot/demos/MainActivity.java b/demoapp/src/main/java/com/androidplot/demos/MainActivity.java deleted file mode 100644 index 86dadb68..00000000 --- a/demoapp/src/main/java/com/androidplot/demos/MainActivity.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2015 AndroidPlot.com - * - * 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 com.androidplot.demos; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import com.crittercism.app.Crittercism; - -public class MainActivity extends Activity { - - private static final String TAG = MainActivity.class.getName(); - - // DO *NOT* CHANGE THIS LINE! (CI-MATCH-POPULATE) - private static final String CRITTERCISM_APP_ID = null; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - if (CRITTERCISM_APP_ID != null) { - Log.d(TAG, "Crittercism initialized."); - Crittercism.initialize(getApplicationContext(), CRITTERCISM_APP_ID); - } - - setContentView(R.layout.main); - - Button startAnimatedXYPlotExButton = (Button) findViewById(R.id.animatedXYPlotExButton); - startAnimatedXYPlotExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, AnimatedXYPlotActivity.class)); - } - }); - - Button startScatterPlotExButton = (Button) findViewById(R.id.startScatterExButton); - startScatterPlotExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, ScatterPlotActivity.class)); - } - }); - - Button startSimplePieExButton = (Button) findViewById(R.id.startSimplePieExButton); - startSimplePieExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, SimplePieChartActivity.class)); - } - }); - - Button startDynamicXYExButton = (Button) findViewById(R.id.startDynamicXYExButton); - startDynamicXYExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, DynamicXYPlotActivity.class)); - } - }); - - Button startCandlestickExButton = (Button) findViewById(R.id.startCandlestickExButton); - startCandlestickExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, CandlestickChartActivity.class)); - } - }); - - Button startSimpleXYExButton = (Button) findViewById(R.id.startSimpleXYExButton); - startSimpleXYExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, SimpleXYPlotActivity.class)); - } - }); - - Button startBarPlotExButton = (Button) findViewById(R.id.startBarPlotExButton); - startBarPlotExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, BarPlotExampleActivity.class)); - } - }); - - Button startOrSensorExButton = (Button) findViewById(R.id.startOrSensorExButton); - startOrSensorExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, OrientationSensorExampleActivity.class)); - } - }); - - Button startDualScaleExButton = (Button) findViewById(R.id.startDualScaleExButton); - startDualScaleExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, DualScaleActivity.class)); - } - }); - - Button startTimeSeriesExButon = (Button) findViewById(R.id.startTimeSeriesExButton); - startTimeSeriesExButon.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, TimeSeriesActivity.class)); - } - }); - - Button startStepChartExButton = (Button) findViewById(R.id.startStepChartExButton); - startStepChartExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, StepChartExampleActivity.class)); - } - }); - - Button startScrollZoomExButton = (Button) findViewById(R.id.startScrollZoomButton); - startScrollZoomExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, TouchZoomExampleActivity.class)); - } - }); - - Button startXyRegionExampleButton = (Button) findViewById(R.id.startXyRegionExampleButton); - startXyRegionExampleButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, XYRegionExampleActivity.class)); - } - }); - - - Button listViewExButton = (Button) findViewById(R.id.startXyListViewExButton); - listViewExButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, ListViewActivity.class)); - } - }); - - Button startXYPlotWithBgImgExampleButton = (Button) findViewById(R.id.startXYPlotWithBgImgExample); - startXYPlotWithBgImgExampleButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, XYPlotWithBgImgActivity.class)); - } - }); - - // ECG - Button startECGExampleButton = (Button) findViewById(R.id.startECGExample); - startECGExampleButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, ECGExample.class)); - } - }); - - // f(x) plot - Button fxPlotExampleButton = (Button) findViewById(R.id.fxPlotExample); - fxPlotExampleButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, FXPlotExampleActivity.class)); - } - }); - - // bubble chart - Button bubbleChartButton = (Button) findViewById(R.id.bubbleChartExample); - bubbleChartButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MainActivity.this, BubbleChartActivity.class)); - } - }); - } -} diff --git a/demoapp/src/main/java/com/androidplot/demos/MainActivity.kt b/demoapp/src/main/java/com/androidplot/demos/MainActivity.kt new file mode 100644 index 00000000..6632af40 --- /dev/null +++ b/demoapp/src/main/java/com/androidplot/demos/MainActivity.kt @@ -0,0 +1,109 @@ +/* + * Copyright 2021 AndroidPlot.com + * + * 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 com.androidplot.demos + +import android.app.Activity +import android.os.Bundle +import android.content.Intent +import com.androidplot.demos.databinding.MainBinding + +class MainActivity : Activity() { + + private lateinit var binding: MainBinding + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = MainBinding.inflate(layoutInflater) + + binding.animatedXYPlotExButton.setOnClickListener { + startActivity(Intent(this, AnimatedXYPlotActivity::class.java)) + } + + binding.startScatterExButton.setOnClickListener { + startActivity(Intent(this, ScatterPlotActivity::class.java)) + } + + binding.startSimplePieExButton.setOnClickListener { + startActivity(Intent(this, SimplePieChartActivity::class.java)) + } + + binding.startDynamicXYExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, DynamicXYPlotActivity::class.java)) + } + + binding.startCandlestickExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, CandlestickChartActivity::class.java)) + } + + binding.startSimpleXYExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, SimpleXYPlotActivity::class.java)) + } + + binding.startBarPlotExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, BarPlotExampleActivity::class.java)) + } + + binding.startOrSensorExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, OrientationSensorExampleActivity::class.java)) + } + + binding.startDualScaleExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, DualScaleActivity::class.java)) + } + + binding.startTimeSeriesExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, TimeSeriesActivity::class.java)) + } + + binding.startStepChartExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, StepChartExampleActivity::class.java)) + } + + binding.startScrollZoomButton.setOnClickListener { + startActivity(Intent(this@MainActivity, TouchZoomExampleActivity::class.java)) + } + + binding.startXyRegionExampleButton.setOnClickListener { + startActivity(Intent(this@MainActivity, XYRegionExampleActivity::class.java)) + } + + binding.startXyListViewExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, ListViewActivity::class.java)) + } + + binding.startXyRecyclerViewExButton.setOnClickListener { + startActivity(Intent(this@MainActivity, RecyclerViewActivity::class.java)) + } + + binding.startXYPlotWithBgImgExample.setOnClickListener { + startActivity(Intent(this@MainActivity, XYPlotWithBgImgActivity::class.java)) + } + + binding.startECGExample.setOnClickListener { + startActivity(Intent(this@MainActivity, ECGExample::class.java)) + } + + binding.fxPlotExample.setOnClickListener { + startActivity(Intent(this@MainActivity, FXPlotExampleActivity::class.java)) + } + + binding.bubbleChartExample.setOnClickListener { + startActivity(Intent(this@MainActivity, BubbleChartActivity::class.java)) + } + + setContentView(binding.root) + } +} \ No newline at end of file diff --git a/demoapp/src/main/java/com/androidplot/demos/RecyclerViewActivity.kt b/demoapp/src/main/java/com/androidplot/demos/RecyclerViewActivity.kt new file mode 100644 index 00000000..194ee6e0 --- /dev/null +++ b/demoapp/src/main/java/com/androidplot/demos/RecyclerViewActivity.kt @@ -0,0 +1,130 @@ +/* + * Copyright 2021 AndroidPlot.com + * + * 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 com.androidplot.demos + +import android.app.Activity +import android.graphics.Color +import com.androidplot.ui.SeriesBundle +import android.os.Bundle +import android.view.ViewGroup +import android.view.LayoutInflater +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.androidplot.demos.databinding.RecyclerviewExampleBinding +import com.androidplot.demos.databinding.RecyclerviewExampleItemBinding +import com.androidplot.util.PixelUtils +import com.androidplot.xy.* +import java.util.* + +class RecyclerViewActivity : Activity() { + private lateinit var binding: RecyclerviewExampleBinding + + companion object { + private const val NUM_PLOTS = 10 + private const val NUM_POINTS_PER_SERIES = 10 + private const val NUM_SERIES_PER_PLOT = 5 + } + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + PixelUtils.init(this) + + binding = RecyclerviewExampleBinding.inflate(layoutInflater) + setContentView(binding.root) + + binding.recyclerView.setHasFixedSize(true) + binding.recyclerView.layoutManager = LinearLayoutManager(this) + binding.recyclerView.adapter = MyRecyclerViewAdapter() + } + + class MyRecyclerViewHolder( + private val binding: RecyclerviewExampleItemBinding + ) : RecyclerView.ViewHolder(binding.root) { + fun bind(data: List>, title: String) { + val plot = binding.plot + plot.clear() + plot.title.text = title + data.map { plot.addSeries(it.series, it.formatter) } + plot.redraw() + } + } + + class MyRecyclerViewAdapter : RecyclerView.Adapter() { + private val seriesData = generateData() + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewHolder { + val itemBinding = RecyclerviewExampleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) + return MyRecyclerViewHolder(itemBinding) + } + + override fun onBindViewHolder(holder: MyRecyclerViewHolder, position: Int) { + holder.bind(seriesData[position], "Series $position") + } + + override fun getItemCount() = seriesData.size + + private fun generateData(): List>> { + val theData = mutableListOf>>() + fun generateBundle(seriesLabel: String): SeriesBundle { + val generator = Random() + val nums = ArrayList() + for (j in 0 until NUM_POINTS_PER_SERIES) { + nums.add(generator.nextFloat()) + } + + val formatter = LineAndPointFormatter( + Color.rgb( + java.lang.Double.valueOf(Math.random() * 255).toInt(), + java.lang.Double.valueOf(Math.random() * 255).toInt(), + java.lang.Double.valueOf(Math.random() * 255).toInt() + ), + Color.rgb( + java.lang.Double.valueOf(Math.random() * 255).toInt(), + java.lang.Double.valueOf(Math.random() * 255).toInt(), + java.lang.Double.valueOf(Math.random() * 255).toInt() + ), + null, null + ) + + // for fun, configure interpolation on the formatter: + formatter.interpolationParams = CatmullRomInterpolator.Params( + 20, + CatmullRomInterpolator.Type.Centripetal + ) + + return SeriesBundle( + SimpleXYSeries( + nums, + SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, + seriesLabel + ), + formatter + ) + } + + for (i in 0 until NUM_PLOTS) { + val seriesList: MutableList> = + ArrayList(NUM_SERIES_PER_PLOT) + + for (k in 0 until NUM_SERIES_PER_PLOT) { + seriesList.add(generateBundle("S$k")) + } + theData.add(seriesList) + } + return theData + } + } +} \ No newline at end of file diff --git a/demoapp/src/main/java/com/androidplot/demos/SimplePieChartActivity.java b/demoapp/src/main/java/com/androidplot/demos/SimplePieChartActivity.java index 9484176f..cf419083 100644 --- a/demoapp/src/main/java/com/androidplot/demos/SimplePieChartActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/SimplePieChartActivity.java @@ -18,6 +18,7 @@ import android.animation.Animator; import android.animation.ValueAnimator; +import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.*; import android.os.Bundle; @@ -52,6 +53,7 @@ public class SimplePieChartActivity extends Activity private Segment s3; private Segment s4; + @SuppressLint("ClickableViewAccessibility") @Override public void onCreate(Bundle savedInstanceState) { diff --git a/demoapp/src/main/java/com/androidplot/demos/SimpleXYPlotActivity.java b/demoapp/src/main/java/com/androidplot/demos/SimpleXYPlotActivity.java index b673f512..db3a5a28 100644 --- a/demoapp/src/main/java/com/androidplot/demos/SimpleXYPlotActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/SimpleXYPlotActivity.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 AndroidPlot.com + * Copyright 2018 AndroidPlot.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,8 @@ import android.app.Activity; import android.graphics.DashPathEffect; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; -import com.androidplot.ui.Size; -import com.androidplot.ui.SizeMode; import com.androidplot.util.PixelUtils; import com.androidplot.xy.CatmullRomInterpolator; import com.androidplot.xy.LineAndPointFormatter; @@ -50,7 +48,7 @@ public void onCreate(Bundle savedInstanceState) setContentView(R.layout.simple_xy_plot_example); // initialize our XYPlot reference: - plot = (XYPlot) findViewById(R.id.plot); + plot = findViewById(R.id.plot); // create a couple arrays of y-values to plot: final Number[] domainLabels = {1, 2, 3, 6, 7, 8, 9, 10, 13, 14}; diff --git a/demoapp/src/main/java/com/androidplot/demos/StepChartExampleActivity.java b/demoapp/src/main/java/com/androidplot/demos/StepChartExampleActivity.java index 79b8272f..4b1fdc35 100644 --- a/demoapp/src/main/java/com/androidplot/demos/StepChartExampleActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/StepChartExampleActivity.java @@ -23,7 +23,7 @@ import android.graphics.Paint; import android.graphics.Shader; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.util.PixelUtils; import com.androidplot.xy.SimpleXYSeries; diff --git a/demoapp/src/main/java/com/androidplot/demos/TimeSeriesActivity.java b/demoapp/src/main/java/com/androidplot/demos/TimeSeriesActivity.java index c5811bfc..12930bd7 100644 --- a/demoapp/src/main/java/com/androidplot/demos/TimeSeriesActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/TimeSeriesActivity.java @@ -16,12 +16,13 @@ package com.androidplot.demos; +import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.os.Bundle; -import android.support.annotation.NonNull; +import androidx.annotation.NonNull; import com.androidplot.util.PixelUtils; import com.androidplot.xy.BoundaryMode; @@ -102,6 +103,7 @@ public void onCreate(Bundle savedInstanceState) { // create a simple date format that draws on the year portion of our timestamp. // see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html // for a full description of SimpleDateFormat. + @SuppressLint("SimpleDateFormat") private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM yyyy"); @Override diff --git a/demoapp/src/main/java/com/androidplot/demos/TouchZoomExampleActivity.java b/demoapp/src/main/java/com/androidplot/demos/TouchZoomExampleActivity.java index c4105cde..dfae19d9 100644 --- a/demoapp/src/main/java/com/androidplot/demos/TouchZoomExampleActivity.java +++ b/demoapp/src/main/java/com/androidplot/demos/TouchZoomExampleActivity.java @@ -152,6 +152,7 @@ public void onNothingSelected(AdapterView parent) { } }); + zoomSpinner.setAdapter( new ArrayAdapter<>(this, R.layout.spinner_item, PanZoom.Zoom.values())); zoomSpinner.setSelection(panZoom.getZoom().ordinal()); @@ -167,5 +168,19 @@ public void onNothingSelected(AdapterView parent) { } }); } + + // (optional) save the current pan/zoom state + @Override + public void onSaveInstanceState(Bundle bundle) { + bundle.putSerializable("pan-zoom-state", panZoom.getState()); + } + + // (optional) restore the previously saved pan/zoom state + @Override + public void onRestoreInstanceState(Bundle bundle) { + PanZoom.State state = (PanZoom.State) bundle.getSerializable("pan-zoom-state"); + panZoom.setState(state); + plot.redraw(); + } } diff --git a/demoapp/src/main/res/layout/main.xml b/demoapp/src/main/res/layout/main.xml index 590087de..3a2d873f 100644 --- a/demoapp/src/main/res/layout/main.xml +++ b/demoapp/src/main/res/layout/main.xml @@ -118,6 +118,13 @@ android:text="ListView of XYPlots" android:enabled="true"/> +