├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── strings.xml
│ │ │ ├── values-land
│ │ │ │ └── dimens.xml
│ │ │ ├── values-w1240dp
│ │ │ │ └── dimens.xml
│ │ │ ├── values-w600dp
│ │ │ │ └── dimens.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── values-v29
│ │ │ │ └── themes.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── layout
│ │ │ │ ├── content_main.xml
│ │ │ │ ├── activity_main.xml
│ │ │ │ ├── fragment_first.xml
│ │ │ │ ├── fragment_second.xml
│ │ │ │ ├── main_fragment.xml
│ │ │ │ └── trace_list_fragment.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── navigation
│ │ │ │ └── nav_graph.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── cn
│ │ │ │ └── alvince
│ │ │ │ └── droidprism
│ │ │ │ └── sample
│ │ │ │ ├── trace
│ │ │ │ ├── SampleTrace.kt
│ │ │ │ └── SampleInvisibleTrace.kt
│ │ │ │ ├── log
│ │ │ │ └── CustomPrismLogcatSink.kt
│ │ │ │ ├── FirstFragment.kt
│ │ │ │ ├── SecondFragment.kt
│ │ │ │ ├── MainFragment.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── list
│ │ │ │ └── TraceListFragment.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── cn
│ │ │ └── alvince
│ │ │ └── droidprism
│ │ │ └── sample
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── cn
│ │ └── alvince
│ │ └── droidprism
│ │ └── sample
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── lib-prism-core
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── res
│ │ │ └── values
│ │ │ │ └── ids.xml
│ │ └── java
│ │ │ └── cn
│ │ │ └── alvince
│ │ │ └── droidprism
│ │ │ ├── internal
│ │ │ ├── Log.kt
│ │ │ ├── TraceEmitter.kt
│ │ │ ├── TraceShooter.kt
│ │ │ ├── lifecycle
│ │ │ │ └── Lifecycle.kt
│ │ │ ├── Utils.kt
│ │ │ └── Instrumentation.kt
│ │ │ ├── IPrismSink.kt
│ │ │ ├── log
│ │ │ ├── page
│ │ │ │ ├── ILogPage.kt
│ │ │ │ ├── ILogPageEntry.kt
│ │ │ │ ├── IPageName.kt
│ │ │ │ ├── IPageDurationCalc.kt
│ │ │ │ └── LogPageManager.kt
│ │ │ ├── ActionType.kt
│ │ │ ├── impl
│ │ │ │ ├── LogPageEntryDelegate.kt
│ │ │ │ └── LogPageDelegate.kt
│ │ │ ├── TraceSpot.kt
│ │ │ ├── ITraceable.kt
│ │ │ └── ExposureStateHelper.kt
│ │ │ ├── util
│ │ │ └── Functions.kt
│ │ │ ├── EZPrism.kt
│ │ │ ├── app
│ │ │ ├── Fragment.kt
│ │ │ └── Activity.kt
│ │ │ └── operator
│ │ │ ├── ViewExposureController.kt
│ │ │ └── ViewTraceHelper.kt
│ └── test
│ │ └── java
│ │ └── cn
│ │ └── alvince
│ │ └── droidprism
│ │ └── ExampleUnitTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── pub
│ └── publish_config.gradle
├── .gitignore
├── .editorconfig
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/lib-prism-core/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/lib-prism-core/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "EZPrism"
2 | include ':app'
3 | include ':lib-prism-core'
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/values-w1240dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 200dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvince/EZPrism/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/res/values/ids.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 19 16:42:39 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/Log.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.internal
2 |
3 | import cn.alvince.droidprism.log.page.PageNameOf
4 |
5 | internal val PAGE_BACKGROUND = PageNameOf("Background")
6 |
7 | internal val PAGE_UNDEFINED = PageNameOf("Undefined")
8 |
9 | internal val PAGE_EMPTY = PageNameOf("None")
10 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/IPrismSink.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism
2 |
3 | import androidx.annotation.MainThread
4 | import cn.alvince.droidprism.log.ActionType
5 | import org.json.JSONObject
6 |
7 | interface IPrismSink {
8 |
9 | /**
10 | * Called on main thread, sink trace event
11 | */
12 | @MainThread
13 | fun sink(type: ActionType, logData: JSONObject)
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 4
8 | end_of_line = lf
9 | insert_final_newline = true
10 | trim_trailing_whitespace = true
11 |
12 | [*.kt]
13 | max_line_length = 160
14 | wildcard_import_limit = 99
15 |
16 | [*.gradle]
17 | max_line_length = 160
18 |
19 | [*.json]
20 | indent_size = 2
21 |
22 | [*.md]
23 | trim_trailing_whitespace = false
24 |
--------------------------------------------------------------------------------
/app/src/test/java/cn/alvince/droidprism/sample/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/lib-prism-core/src/test/java/cn/alvince/droidprism/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/values-v29/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/TraceEmitter.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.internal
2 |
3 | import androidx.annotation.MainThread
4 | import cn.alvince.droidprism.log.ActionType
5 | import cn.alvince.droidprism.log.ITraceable
6 |
7 | class TraceEmitter {
8 |
9 | @MainThread
10 | fun emitAction(actionType: ActionType, trace: ITraceable) {
11 | logDIfDebug { "emit trace: [${actionType.logType()}] $trace" }
12 | TraceShooter.sendWithCommonFields(actionType, actionType.traceToJson(trace))
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/page/ILogPage.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.page
2 |
3 | import cn.alvince.droidprism.log.ExposureStateHelper
4 |
5 | interface ILogPage {
6 |
7 | fun interface OnPageShowStatusChangeListener {
8 | fun onPageShowStatusChanged(show: Boolean)
9 | }
10 |
11 | val exposureStateHelper: ExposureStateHelper
12 |
13 | fun onPageShowingChanged(show: Boolean)
14 |
15 | fun pageName(): IPageName
16 |
17 | fun addOnPageShowStatusChangedListener(listener: OnPageShowStatusChangeListener)
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/page/ILogPageEntry.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.page
2 |
3 | import cn.alvince.zanpakuto.core.serialization.JSONCreator
4 | import org.json.JSONObject
5 |
6 | /**
7 | * [ILogPage] entry that traceable powered by [LogPageManager]
8 | *
9 | * Create by bytedance on 2022/9/24
10 | *
11 | * @author zhangyang.alvince@bytedance.com
12 | */
13 | interface ILogPageEntry : ILogPage {
14 |
15 | val content: JSONObject
16 |
17 | var className: String
18 |
19 | fun setPageName(pageName: IPageName)
20 |
21 | fun setPageContent(content: JSONObject)
22 |
23 | fun setPageContent(content: JSONCreator.() -> Unit)
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/trace/SampleTrace.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample.trace
2 |
3 | import cn.alvince.droidprism.log.ActionType
4 | import cn.alvince.droidprism.log.ITraceable
5 | import cn.alvince.zanpakuto.core.serialization.json
6 | import org.json.JSONObject
7 |
8 | /**
9 | * Sample custom trace model
10 | *
11 | * Create by bytedance on 2022/9/11
12 | *
13 | * @author zhangyang.alvince@bytedance.com
14 | */
15 | open class SampleTrace(val name: String) : ITraceable {
16 |
17 | override fun toActionJson(actionType: ActionType): JSONObject = json {
18 | "event_id" to name
19 | }
20 |
21 | override fun toString(): String {
22 | return "SampleTrace(name='$name')"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/TraceShooter.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.internal
2 |
3 | import cn.alvince.droidprism.log.ActionType
4 | import cn.alvince.droidprism.log.page.ILogPageEntry
5 | import org.json.JSONObject
6 |
7 | internal object TraceShooter {
8 |
9 | fun pageEntry(pageEntry: ILogPageEntry) {
10 | // Instrumentation.traverseSink { it.sink(ActionType.PAGE_ENTER, ) }
11 | }
12 |
13 | fun pageExit(pageEntry: ILogPageEntry) {
14 | Instrumentation.traverseSink { it.sink(ActionType.PAGE_EXIT, pageEntry.content) }
15 | }
16 |
17 | fun sendWithCommonFields(type: ActionType, logData: JSONObject) {
18 | Instrumentation.traverseSink { it.sink(type, logData) }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/page/IPageName.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.page
2 |
3 | import cn.alvince.zanpakuto.core.text.orDefault
4 |
5 | /**
6 | * Log page name indicator
7 | */
8 | interface IPageName {
9 | val id: String
10 |
11 | val displayName: String get() = id
12 | }
13 |
14 | /**
15 | * Simple [IPageName] impl
16 | */
17 | class SimplePageName(pageId: String, display: String? = null) : IPageName {
18 | override val id: String = pageId
19 |
20 | override val displayName: String = display.orDefault(pageId)
21 | }
22 |
23 | @Suppress("FunctionName") // Create IPageName via function
24 | fun PageNameOf(pageId: String, displayName: String? = null): IPageName = SimplePageName(pageId, displayName)
25 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/cn/alvince/droidprism/sample/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("cn.alvince.droidprism.sample", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/lib-prism-core/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/log/CustomPrismLogcatSink.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample.log
2 |
3 | import android.util.Log
4 | import cn.alvince.droidprism.EZPrism
5 | import cn.alvince.droidprism.IPrismSink
6 | import cn.alvince.droidprism.log.ActionType
7 | import org.json.JSONObject
8 |
9 | class CustomPrismLogcatSink : IPrismSink {
10 |
11 | override fun sink(type: ActionType, logData: JSONObject) {
12 | Log.d("EZPrism", "——> [custom sink] ${type.typeName} - $logData")
13 | }
14 |
15 | companion object {
16 | private var prepared = false
17 |
18 | fun prepare() {
19 | if (prepared) {
20 | return
21 | }
22 | EZPrism.devMode(true)
23 | .useRawPage()
24 | .addPrinter(CustomPrismLogcatSink())
25 | prepared = true
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/util/Functions.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.util
2 |
3 | import android.view.View
4 | import cn.alvince.droidprism.log.ExposureStateHelper
5 | import cn.alvince.droidprism.log.page.ILogPage
6 | import cn.alvince.droidprism.log.ITraceable
7 | import cn.alvince.droidprism.operator.ViewTraceHelper
8 |
9 | fun View.traceExpose(page: ILogPage, trace: ITraceable?) {
10 | getTraceHelper().apply {
11 | this.trace = trace
12 | this.exposureStateHelper = page.exposureStateHelper
13 | }
14 | }
15 |
16 | fun View.exposeWith(exposureStateHelper: ExposureStateHelper, trace: ITraceable?) {
17 | getTraceHelper().apply {
18 | this.trace = trace
19 | this.exposureStateHelper = exposureStateHelper
20 | }
21 | }
22 |
23 | fun View.getTraceHelper(): ViewTraceHelper {
24 | return ViewTraceHelper.from(this) ?: ViewTraceHelper.create().also { it.attachToView(this) }
25 | }
26 |
--------------------------------------------------------------------------------
/gradle/pub/publish_config.gradle:
--------------------------------------------------------------------------------
1 | project.extensions.create('mvn', MvnConfig)
2 |
3 | class MvnConfig {
4 | String artifact = ''
5 | String group = 'cn.alvince.droidprism'
6 | String version = ''
7 | String name = ''
8 | String description = ''
9 | String packaging = 'aar'
10 |
11 | void setArtifact(String artifact) {
12 | this.artifact = artifact
13 | }
14 |
15 | void setGroup(String group) {
16 | this.group = group
17 | }
18 |
19 | void setVersion(String version) {
20 | this.version = version
21 | }
22 |
23 | void setName(String name) {
24 | this.name = name
25 | }
26 |
27 | void setDescription(String description) {
28 | this.description = description
29 | }
30 |
31 | void setPackaging(String packaging) {
32 | this.packaging = packaging
33 | }
34 |
35 | String getName() {
36 | return name.isEmpty() ? artifact : name
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/trace/SampleInvisibleTrace.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample.trace
2 |
3 | import cn.alvince.droidprism.log.ActionType
4 | import cn.alvince.droidprism.log.ITraceWhenInvisibleWithDuration
5 | import cn.alvince.droidprism.log.SimpleDuration
6 | import cn.alvince.zanpakuto.core.serialization.json
7 | import org.json.JSONObject
8 |
9 | /**
10 | * Sample custom trace model that track when invisible only, with exposure duration report
11 | *
12 | * Create by bytedance on 2022/9/11
13 | *
14 | * @author zhangyang.alvince@bytedance.com
15 | */
16 | class SampleInvisibleTrace(name: String) : SampleTrace(name), ITraceWhenInvisibleWithDuration by SimpleDuration() {
17 |
18 | override fun toActionJson(actionType: ActionType): JSONObject = json {
19 | "event_id" to name
20 | if (actionType == ActionType.EXPOSE) {
21 | "duration" to duration.inSeconds
22 | }
23 | }
24 |
25 | override fun toString(): String {
26 | return "SampleInvisibleTrace(name='$name', duration='$duration')"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/page/IPageDurationCalc.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.page
2 |
3 | import cn.alvince.zanpakuto.core.time.Duration
4 | import cn.alvince.zanpakuto.core.time.Timestamp
5 |
6 | /**
7 | * Create by bytedance on 2022/10/1
8 | *
9 | * @author zhangyang.alvince@bytedance.com
10 | */
11 | interface IPageDurationCalc {
12 | val showDuration: Duration
13 |
14 | fun setUserVisible(isVisibleToUser: Boolean)
15 | }
16 |
17 | class EZPageDurationCalc : IPageDurationCalc {
18 |
19 | override val showDuration get() = _showDuration
20 |
21 | private var isUserVisible = false
22 | private var lastVisibleTime = Timestamp.ZERO
23 | private var _showDuration = Duration.ZERO
24 |
25 | override fun setUserVisible(isVisibleToUser: Boolean) {
26 | if (isVisibleToUser == isUserVisible) {
27 | return
28 | }
29 | isUserVisible = isVisibleToUser
30 | if (isVisibleToUser) {
31 | lastVisibleTime = Timestamp.now()
32 | _showDuration = Duration.ZERO
33 | return
34 | }
35 | _showDuration = Timestamp.now() - lastVisibleTime
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/ActionType.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log
2 |
3 | import org.json.JSONObject
4 |
5 | /**
6 | * Trace action type enumerate
7 | *
8 | * Created by alvince on 2022/5/23
9 | *
10 | * @author alvince.zy@gmail.com
11 | */
12 | enum class ActionType(val typeName: String) {
13 |
14 | PAGE_ENTER("page_enter") {
15 | override fun traceToJson(trace: ITraceable): JSONObject = error("Unsupported, only indicate enter the log page")
16 | },
17 |
18 | PAGE_EXIT("page_exit") {
19 | override fun traceToJson(trace: ITraceable): JSONObject = error("Unsupported, indicate exit log page only")
20 | },
21 |
22 | /**
23 | * For click event
24 | */
25 | CLICK("click"),
26 |
27 | /**
28 | * For content exposing
29 | */
30 | EXPOSE("view") {
31 | override fun logType(): String = "Expose"
32 |
33 | override fun traceToJson(trace: ITraceable): JSONObject = trace.toExposeJson()
34 | },
35 |
36 | ;
37 |
38 | internal open fun logType(): String = "ActionEvent"
39 |
40 | internal open fun traceToJson(trace: ITraceable): JSONObject = trace.toActionJson(this)
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
16 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/lifecycle/Lifecycle.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.internal.lifecycle
2 |
3 | import androidx.annotation.RestrictTo
4 | import androidx.lifecycle.Lifecycle
5 | import androidx.lifecycle.LifecycleEventObserver
6 | import androidx.lifecycle.LifecycleOwner
7 | import java.lang.ref.WeakReference
8 |
9 | @RestrictTo(RestrictTo.Scope.LIBRARY)
10 | internal class LifecycleObserver(owner: LifecycleOwner, val onStateChange: (source: LifecycleOwner, event: Lifecycle.Event) -> Unit): LifecycleEventObserver {
11 |
12 | private val target: LifecycleOwner? get() = _source.get()
13 |
14 | private val _source = WeakReference(owner)
15 |
16 | override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
17 | onStateChange(source, event)
18 | if (event == Lifecycle.Event.ON_DESTROY) {
19 | source.lifecycle.removeObserver(this)
20 | }
21 | }
22 |
23 | fun attach() {
24 | target?.lifecycle?.addObserver(this)
25 | }
26 | }
27 |
28 | fun LifecycleOwner.observeWith(onStateChange: (source: LifecycleOwner, event: Lifecycle.Event) -> Unit) {
29 | LifecycleObserver(this, onStateChange).attach()
30 | }
31 |
--------------------------------------------------------------------------------
/lib-prism-core/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | version "0.0.2"
7 |
8 | apply from: '../gradle/pub/publish_config.gradle'
9 |
10 | mvn {
11 | name 'easy prism log'
12 | description 'easy prism log component'
13 | artifact 'ezprism'
14 | }
15 |
16 | android {
17 | compileSdkVersion 32
18 |
19 | defaultConfig {
20 | minSdkVersion 19
21 | targetSdkVersion 32
22 |
23 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
24 | consumerProguardFiles "consumer-rules.pro"
25 | }
26 |
27 | buildTypes {
28 | release {
29 | minifyEnabled false
30 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
31 | }
32 | }
33 | compileOptions {
34 | sourceCompatibility JavaVersion.VERSION_1_8
35 | targetCompatibility JavaVersion.VERSION_1_8
36 | }
37 | kotlinOptions {
38 | jvmTarget = '1.8'
39 | }
40 | }
41 |
42 | dependencies {
43 | implementation 'cn.alvince.zanpakuto:core:1.0.1'
44 | implementation "androidx.collection:collection-ktx:1.1.0"
45 | implementation 'androidx.core:core-ktx:1.6.0'
46 | implementation 'androidx.appcompat:appcompat:1.3.1'
47 | testImplementation 'junit:junit:4.13.2'
48 | }
49 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 |
25 | kotlin.version=1.6.0
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/impl/LogPageEntryDelegate.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.impl
2 |
3 | import cn.alvince.droidprism.internal.plus
4 | import cn.alvince.droidprism.log.page.EZPageDurationCalc
5 | import cn.alvince.droidprism.log.page.ILogPageEntry
6 | import cn.alvince.droidprism.log.page.IPageDurationCalc
7 | import cn.alvince.droidprism.log.page.IPageName
8 | import cn.alvince.zanpakuto.core.serialization.JSONCreator
9 | import org.json.JSONObject
10 |
11 | /**
12 | * [ILogPageEntry] implementation for delegate page base behaviors
13 | *
14 | * Create by bytedance on 2022/9/24
15 | *
16 | * @author zhangyang.alvince@bytedance.com
17 | */
18 | class LogPageEntryDelegate() : LogPageDelegate(""), ILogPageEntry, IPageDurationCalc by EZPageDurationCalc() {
19 |
20 | override val content: JSONObject get() = pageContentData
21 |
22 | override var className: String = ""
23 |
24 | private val pageContentData = JSONObject()
25 |
26 |
27 | constructor(id: IPageName) : this() {
28 | pageId = id
29 | }
30 |
31 | override fun setPageName(pageName: IPageName) {
32 | pageId = pageName
33 | }
34 |
35 | override fun setPageContent(content: JSONObject) {
36 | pageContentData + content
37 | }
38 |
39 | override fun setPageContent(content: JSONCreator.() -> Unit) {
40 | JSONObject()
41 | .also { JSONCreator(it).apply(content) }
42 | .also {
43 | pageContentData + it
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/TraceSpot.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log
2 |
3 | import cn.alvince.zanpakuto.core.serialization.json
4 | import org.json.JSONObject
5 |
6 | data class TraceSpot internal constructor(
7 | val traceAction: String,
8 | val primaryType: String,
9 | val primaryId: String,
10 | val extend: Map? = null,
11 | val exposeId: String? = null,
12 | var serialNo: Int = 0, // prevent hash collision for instances with the same data
13 | ) : ITraceable {
14 |
15 | override fun toActionJson(actionType: ActionType): JSONObject = json {
16 | "event_id" to eventId(actionType)
17 | "action_primary_id" indeed primaryId
18 | "action_primary_type" indeed primaryType
19 | "action_extend" indeed extend?.takeUnless { it.isEmpty() }?.toString()
20 | "expose_id" indeed exposeId
21 | }
22 |
23 | override fun toExposeJson(): JSONObject = json {
24 | "event_id" to eventId(ActionType.EXPOSE)
25 | "expose_primary_id" indeed primaryId
26 | "expose_primary_type" indeed primaryType
27 | "expose_extend" indeed extend?.takeUnless { it.isEmpty() }?.toString()
28 | "expose_id" indeed exposeId
29 | }
30 |
31 | private fun eventId(actionType: ActionType): String = "${traceAction}_${actionType.typeName}"
32 |
33 | companion object {
34 | fun of(action: String) = TraceSpot(action, "", "")
35 |
36 | fun of(action: String, primaryType: String, primaryId: String) = TraceSpot(action, primaryType, primaryId)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/FirstFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.fragment.app.Fragment
8 | import androidx.navigation.fragment.findNavController
9 | import cn.alvince.droidprism.app.asLogPage
10 | import cn.alvince.droidprism.sample.databinding.FragmentFirstBinding
11 | import cn.alvince.droidprism.sample.trace.SampleTrace
12 | import cn.alvince.droidprism.util.traceExpose
13 |
14 | /**
15 | * A simple [Fragment] subclass as the default destination in the navigation.
16 | */
17 | class FirstFragment : Fragment() {
18 |
19 | private var _binding: FragmentFirstBinding? = null
20 |
21 | // This property is only valid between onCreateView and
22 | // onDestroyView.
23 | private val binding get() = _binding!!
24 |
25 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
26 | _binding = FragmentFirstBinding.inflate(inflater, container, false)
27 | return binding.root
28 | }
29 |
30 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
31 | super.onViewCreated(view, savedInstanceState)
32 |
33 | binding.buttonFirst.setOnClickListener {
34 | findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
35 | }
36 |
37 | binding.buttonFirst.traceExpose(asLogPage(), SampleTrace("first_button"))
38 | }
39 |
40 | override fun onDestroyView() {
41 | super.onDestroyView()
42 | _binding = null
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/EZPrism.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism
2 |
3 | import cn.alvince.droidprism.internal.Instrumentation
4 | import cn.alvince.zanpakuto.core.time.Duration
5 | import java.util.concurrent.TimeUnit
6 |
7 | /**
8 | * EZPrism access entrance
9 | *
10 | * Created by alvince on 2022/5/23
11 | *
12 | * @author alvince.zy@gmail.com
13 | * @see [EZPrism](https://github.com/alvince/EZPrism)
14 | */
15 | object EZPrism {
16 |
17 | /**
18 | * Enable or disable developer mode (for print logs), `false` default
19 | */
20 | fun devMode(enable: Boolean): EZPrism = this.apply { Instrumentation.devMode = enable }
21 |
22 | fun useRawPage(): EZPrism = this.apply { Instrumentation.useRawPage = true }
23 |
24 | /**
25 | * Add trace
26 | */
27 | fun addPrinter(sink: IPrismSink): EZPrism = this.apply { Instrumentation.addSink(sink) }
28 |
29 | /**
30 | * Set custom time threshold in milliseconds for view expose detect
31 | */
32 | fun setExposeTimeThreshold(timeInMillis: Long): EZPrism = this.apply {
33 | require(timeInMillis > 0) { "A threshold greater than 0 ms should be set." }
34 | Instrumentation.setCustomExposeTimeThreshold(Duration.of(timeInMillis, TimeUnit.MILLISECONDS))
35 | }
36 |
37 | /**
38 | * Set custom time threshold in milliseconds for exposure data frequency
39 | */
40 | fun setExposeFrequencyThreshold(timeInMillis: Long): EZPrism = this.apply {
41 | require(timeInMillis > 0) { "A threshold greater than 0 ms should be set." }
42 | Instrumentation.setCustomExposeFrequencyThreshold(Duration.of(timeInMillis, TimeUnit.MILLISECONDS))
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_first.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
23 |
24 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/Utils.kt:
--------------------------------------------------------------------------------
1 | @file:JvmName("InternalUtils")
2 |
3 | package cn.alvince.droidprism.internal
4 |
5 | import android.os.Handler
6 | import android.os.Looper
7 | import android.util.Log
8 | import androidx.collection.SparseArrayCompat
9 | import org.json.JSONObject
10 |
11 | internal val mainHandler = Handler(Looper.getMainLooper())
12 |
13 | internal const val LOG_TAG = "EZPrism"
14 |
15 | internal inline fun logDIfDebug(lazyMessage: () -> String) {
16 | if (Instrumentation.devMode) {
17 | Log.d(LOG_TAG, lazyMessage())
18 | }
19 | }
20 |
21 | internal inline fun logVIfDebug(lazyMessage: () -> String) {
22 | if (Instrumentation.devMode) {
23 | Log.v(LOG_TAG, lazyMessage())
24 | }
25 | }
26 |
27 | internal fun SparseArrayCompat.getOrPut(key: Int, supplier: () -> T): T {
28 | return get(key) ?: supplier().also { put(key, it) }
29 | }
30 |
31 | internal fun checkMainThread() {
32 | if (Thread.currentThread() != Looper.getMainLooper().thread) {
33 | error("Non called from main-thread.")
34 | }
35 | }
36 |
37 | internal fun runOnMain(block: () -> Unit) {
38 | if (Looper.getMainLooper().thread === Thread.currentThread()) {
39 | block()
40 | } else {
41 | mainHandler.post(block)
42 | }
43 | }
44 |
45 | internal fun postOnMain(delayed: Long = 0L, block: () -> Unit) {
46 | if (delayed > 0L) {
47 | mainHandler.postDelayed(block, delayed)
48 | return
49 | }
50 | mainHandler.post(block)
51 | }
52 |
53 | internal operator fun JSONObject.plus(another: JSONObject): JSONObject = this
54 | .apply {
55 | another.keys().forEach { k -> putOpt(k, another.get(k)) }
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/SecondFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.fragment.app.Fragment
8 | import androidx.navigation.fragment.findNavController
9 | import cn.alvince.droidprism.app.asLogPage
10 | import cn.alvince.droidprism.sample.databinding.FragmentSecondBinding
11 | import cn.alvince.droidprism.sample.trace.SampleTrace
12 | import cn.alvince.droidprism.util.traceExpose
13 |
14 | /**
15 | * A simple [Fragment] subclass as the second destination in the navigation.
16 | */
17 | class SecondFragment : Fragment() {
18 |
19 | private var _binding: FragmentSecondBinding? = null
20 |
21 | // This property is only valid between onCreateView and
22 | // onDestroyView.
23 | private val binding get() = _binding!!
24 |
25 | override fun onCreateView(
26 | inflater: LayoutInflater, container: ViewGroup?,
27 | savedInstanceState: Bundle?
28 | ): View? {
29 |
30 | _binding = FragmentSecondBinding.inflate(inflater, container, false)
31 | return binding.root
32 |
33 | }
34 |
35 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
36 | super.onViewCreated(view, savedInstanceState)
37 |
38 | binding.buttonSecond.setOnClickListener {
39 | findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
40 | }
41 |
42 | binding.buttonSecond.traceExpose(asLogPage(), SampleTrace("second_button"))
43 | }
44 |
45 | override fun onDestroyView() {
46 | super.onDestroyView()
47 | _binding = null
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_second.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
23 |
24 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | def localMode = true
7 |
8 | android {
9 | compileSdk 32
10 |
11 | defaultConfig {
12 | applicationId "cn.alvince.droidprism.sample"
13 | minSdk 19
14 | targetSdk 32
15 | versionCode 1
16 | versionName "1.0"
17 |
18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
19 | }
20 |
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility JavaVersion.VERSION_1_8
29 | targetCompatibility JavaVersion.VERSION_1_8
30 | }
31 | kotlinOptions {
32 | jvmTarget = '1.8'
33 | }
34 | buildFeatures {
35 | viewBinding true
36 | }
37 | }
38 |
39 | dependencies {
40 | implementation 'androidx.core:core-ktx:1.7.0'
41 | implementation 'androidx.appcompat:appcompat:1.4.1'
42 | implementation 'com.google.android.material:material:1.6.0'
43 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
44 | implementation 'androidx.navigation:navigation-fragment-ktx:2.4.2'
45 | implementation 'androidx.navigation:navigation-ui-ktx:2.4.2'
46 | implementation 'cn.alvince.zanpakuto:core:1.0.1'
47 | if (localMode) {
48 | implementation project(':lib-prism-core')
49 | } else {
50 | implementation('cn.alvince.droidprism:ezprism:0.0.2')
51 | }
52 | testImplementation 'junit:junit:4.13.2'
53 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
54 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/MainFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.core.os.bundleOf
8 | import androidx.fragment.app.Fragment
9 | import androidx.navigation.fragment.findNavController
10 | import cn.alvince.droidprism.app.asLogPage
11 | import cn.alvince.droidprism.sample.databinding.MainFragmentBinding
12 | import cn.alvince.droidprism.sample.trace.SampleTrace
13 | import cn.alvince.droidprism.util.traceExpose
14 |
15 | /**
16 | * Create by bytedance on 2022/9/11
17 | *
18 | * @author zhangyang.alvince@bytedance.com
19 | */
20 | class MainFragment : Fragment() {
21 |
22 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
23 | MainFragmentBinding.inflate(inflater, container, false)
24 | .also {
25 | it.initView()
26 | }
27 | .root
28 |
29 | private fun MainFragmentBinding.initView() {
30 | btnSimpleCase.apply {
31 | setOnClickListener {
32 | findNavController().navigate(R.id.action_home_to_simple_case)
33 | }
34 | traceExpose(asLogPage(), SampleTrace("simple_case_button"))
35 | }
36 | btnListCase.apply {
37 | setOnClickListener {
38 | findNavController().navigate(R.id.action_home_to_list_case)
39 | }
40 | traceExpose(asLogPage(), SampleTrace("list_case_button"))
41 | }
42 | btnListInvisibleMode.apply {
43 | setOnClickListener {
44 | findNavController().navigate(R.id.action_home_to_list_case, bundleOf("__arg_expose_when_invisible" to true))
45 | }
46 | traceExpose(asLogPage(), SampleTrace("list_mode_invisible_button"))
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/src/main/res/navigation/nav_graph.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
12 |
13 |
16 |
17 |
20 |
21 |
26 |
27 |
30 |
31 |
36 |
37 |
40 |
41 |
46 |
47 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/impl/LogPageDelegate.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.impl
2 |
3 | import cn.alvince.droidprism.internal.PAGE_UNDEFINED
4 | import cn.alvince.droidprism.log.ExposureStateHelper
5 | import cn.alvince.droidprism.log.page.ILogPage
6 | import cn.alvince.droidprism.log.page.IPageName
7 | import cn.alvince.droidprism.log.page.PageNameOf
8 | import cn.alvince.zanpakuto.core.text.takeIfNotEmpty
9 |
10 | /**
11 | * [ILogPage] implementation for delegate page base behaviors
12 | *
13 | * Created by alvince on 2022/5/23
14 | *
15 | * @author alvince.zy@gmail.com
16 | */
17 | open class LogPageDelegate(name: String) : ILogPage {
18 |
19 | override val exposureStateHelper: ExposureStateHelper
20 | get() {
21 | return _exposureStateHelper
22 | ?: ExposureStateHelper().apply {
23 | _exposureStateHelper = this
24 | pageShowing = _showing
25 | }
26 | }
27 |
28 | protected var pageId = name.takeIfNotEmpty()?.let { PageNameOf(name) } ?: PAGE_UNDEFINED
29 |
30 | private val pageShowingChangedListeners
31 | get() = synchronized(this) {
32 | _pageShowingChangedListeners ?: arrayListOf().also { _pageShowingChangedListeners = it }
33 | }
34 |
35 | private var _exposureStateHelper: ExposureStateHelper? = null
36 | private var _showing: Boolean = false
37 |
38 | private var _pageShowingChangedListeners: MutableList? = null
39 |
40 | override fun onPageShowingChanged(show: Boolean) {
41 | _showing = show
42 | exposureStateHelper.pageShowing = show
43 | pageShowingChangedListeners.forEach { it.onPageShowStatusChanged(show) }
44 | }
45 |
46 | override fun pageName(): IPageName = pageId
47 |
48 | override fun addOnPageShowStatusChangedListener(listener: ILogPage.OnPageShowStatusChangeListener) {
49 | pageShowingChangedListeners.add(listener)
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.core.view.WindowCompat
6 | import androidx.navigation.findNavController
7 | import androidx.navigation.ui.AppBarConfiguration
8 | import androidx.navigation.ui.navigateUp
9 | import androidx.navigation.ui.setupActionBarWithNavController
10 | import cn.alvince.droidprism.app.asLogPage
11 | import cn.alvince.droidprism.sample.databinding.ActivityMainBinding
12 | import cn.alvince.droidprism.sample.log.CustomPrismLogcatSink
13 | import cn.alvince.droidprism.sample.trace.SampleTrace
14 | import cn.alvince.droidprism.util.traceExpose
15 | import com.google.android.material.snackbar.Snackbar
16 |
17 | class MainActivity : AppCompatActivity() {
18 |
19 | private lateinit var appBarConfiguration: AppBarConfiguration
20 | private lateinit var binding: ActivityMainBinding
21 |
22 | override fun onCreate(savedInstanceState: Bundle?) {
23 | WindowCompat.setDecorFitsSystemWindows(window, false)
24 | super.onCreate(savedInstanceState)
25 | CustomPrismLogcatSink.prepare()
26 |
27 | binding = ActivityMainBinding.inflate(layoutInflater)
28 | setContentView(binding.root)
29 | setSupportActionBar(binding.toolbar)
30 |
31 | val navController = findNavController(R.id.nav_host_fragment_content_main)
32 | appBarConfiguration = AppBarConfiguration(navController.graph)
33 | setupActionBarWithNavController(navController, appBarConfiguration)
34 |
35 | binding.fab.setOnClickListener { view ->
36 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
37 | .setAnchorView(R.id.fab)
38 | .setAction("Action", null).show()
39 | }
40 | binding.fab.traceExpose(asLogPage(), SampleTrace("fab_button"))
41 | }
42 |
43 | override fun onSupportNavigateUp(): Boolean {
44 | val navController = findNavController(R.id.nav_host_fragment_content_main)
45 | return navController.navigateUp(appBarConfiguration)
46 | || super.onSupportNavigateUp()
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/main_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
21 |
22 |
33 |
34 |
45 |
46 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/internal/Instrumentation.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.internal
2 |
3 | import cn.alvince.droidprism.IPrismSink
4 | import cn.alvince.droidprism.log.ActionType
5 | import cn.alvince.droidprism.log.ITraceable
6 | import cn.alvince.zanpakuto.core.time.Duration
7 | import java.util.LinkedList
8 | import java.util.concurrent.TimeUnit
9 |
10 | /**
11 | * Internal prism instrumentation
12 | *
13 | * Created by alvince on 2022/5/23
14 | *
15 | * @author alvince.zy@gmail.com
16 | */
17 | internal object Instrumentation {
18 |
19 | internal val eventEmitter = TraceEmitter()
20 |
21 | internal val exposeTimeThreshold: Duration get() = customExposeTimeThreshold.takeOr { defaultExposeTimeThreshold }
22 | internal val exposeFrequencyThreshold: Duration get() = customExposeFrequencyThreshold.takeOr { defaultExposeFrequencyThreshold }
23 |
24 | internal var devMode: Boolean = false
25 |
26 | @Volatile
27 | internal var useRawPage: Boolean = false
28 |
29 | private val defaultExposeTimeThreshold = Duration.of(500L, TimeUnit.MILLISECONDS)
30 | private val defaultExposeFrequencyThreshold = Duration.of(10, TimeUnit.SECONDS)
31 | private val sinks = LinkedList()
32 |
33 | private var customExposeTimeThreshold = Duration.ZERO
34 | private var customExposeFrequencyThreshold = Duration.ZERO
35 |
36 | @Synchronized
37 | fun addSink(sink: IPrismSink) {
38 | sinks.takeIf { !it.contains(sink) }?.add(sink)
39 | }
40 |
41 | fun traverseSink(block: (IPrismSink) -> Unit) {
42 | sinks.toList().forEach(block)
43 | }
44 |
45 | fun setCustomExposeTimeThreshold(duration: Duration) {
46 | customExposeTimeThreshold = duration
47 | }
48 |
49 | fun setCustomExposeFrequencyThreshold(internal: Duration) {
50 | customExposeFrequencyThreshold = internal
51 | }
52 |
53 | internal fun emitExposeEventIfNotTooFrequent(trace: ITraceable) {
54 | trace.takeIf { ITraceable.checkExposeNotTooFrequent(it) }
55 | ?.also {
56 | runOnMain { eventEmitter.emitAction(ActionType.EXPOSE, trace) }
57 | }
58 | }
59 |
60 | private inline fun Duration.takeOr(defaultVal: () -> Duration) = this.takeUnless { it == Duration.ZERO } ?: defaultVal()
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/trace_list_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
19 |
20 |
31 |
32 |
40 |
41 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/ITraceable.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log
2 |
3 | import cn.alvince.droidprism.internal.Instrumentation
4 | import cn.alvince.zanpakuto.core.time.Duration
5 | import cn.alvince.zanpakuto.core.time.Timestamp
6 | import org.json.JSONObject
7 | import java.util.concurrent.TimeUnit
8 |
9 | /**
10 | * Traceable data defined
11 | *
12 | * Created by alvince on 2022/5/23
13 | *
14 | * @author alvince.zy@gmail.com
15 | */
16 | interface ITraceable {
17 |
18 | fun toActionJson(actionType: ActionType): JSONObject
19 |
20 | fun toExposeJson(): JSONObject = toActionJson(ActionType.EXPOSE)
21 |
22 | companion object {
23 | private val exposeMonitorMap = mutableMapOf()
24 | private val exposeTimeCleanupThreshold = Duration.of(1, TimeUnit.MINUTES)
25 | private var lastCleanupTime = Timestamp.ZERO
26 |
27 | internal fun checkExposeNotTooFrequent(trace: ITraceable): Boolean {
28 | val now = Timestamp.now()
29 | val frequencyLimit = Instrumentation.exposeFrequencyThreshold
30 | if (now - lastCleanupTime > exposeTimeCleanupThreshold) {
31 | var cleared = false
32 | exposeMonitorMap.iterator().also { iterator ->
33 | while (iterator.hasNext()) {
34 | val (_, time) = iterator.next()
35 | if (now - time > frequencyLimit) {
36 | iterator.remove()
37 | cleared = cleared || true
38 | }
39 | }
40 | }
41 | if (cleared) lastCleanupTime = now
42 | }
43 | if (exposeMonitorMap[trace].let { it != null && now - it < frequencyLimit }) {
44 | return false
45 | }
46 | exposeMonitorMap[trace] = now
47 | return true
48 | }
49 | }
50 | }
51 |
52 | /**
53 | * Indicate that should trace while target invisible to users
54 | */
55 | interface ITraceWhenInvisible
56 |
57 | /**
58 | * Trace while target invisible, with exposed duration
59 | */
60 | interface ITraceWhenInvisibleWithDuration : ITraceWhenInvisible {
61 | var duration: Duration
62 | }
63 |
64 | /**
65 | * Simple holder proxy of [ITraceWhenInvisibleWithDuration]
66 | */
67 | class SimpleDuration : ITraceWhenInvisibleWithDuration {
68 | override var duration: Duration = Duration.ZERO
69 | }
70 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | EZPrism
2 | ===
3 |
4 | EZPrism 是为 `Android` 上运行的应用程序提供埋点数据收集能力的中间件
5 | 系统基于 `View` 的行为监听,以及抽象的 `Page` 和 `Trace` 构建出的可扩展的埋点能力框架
6 |
7 | __~~Snapshot, add config:~~__
8 | ```groovy
9 | // repositories {
10 | // maven { url 'https://s01.oss.sonatype.org/content/repositories/snapshots/' }
11 | // }
12 | ```
13 |
14 | Dependency
15 | ```groovy
16 | dependencies {
17 | implementation 'cn.alvince.droidprism:ezprism:0.0.2'
18 | }
19 | ```
20 |
21 | Sample
22 | ---
23 |
24 | 运行 app 模块,`Logcat` tag: `EZPrism`
25 |
26 | - 查看事件触发日志:```emit trace: [${actionType.logType()}] $trace```
27 | - 埋点数据日志:[CustomPrismLogcatSink](app/src/main/java/cn/alvince/droidprism/sample/log/CustomPrismLogcatSink.kt) ```——> [custom sink] ${type.typeName} - $logData```
28 |
29 | 使用
30 | ---
31 |
32 | #### 配置/初始化
33 |
34 | 添加应用自定埋点记录器 | [sample for print logcat](app/src/main/java/cn/alvince/droidprism/sample/log/CustomPrismLogcatSink.kt)
35 |
36 | ```kotlin
37 | EZPrism.devMode(true) // 开启调试日志
38 | .useRawPage() // 使用原生页面(Activity/Fragment) 直接作为逻辑页面
39 | /* 添加日志输出记录,实现埋点数据的自定义上报逻辑(logcat 日志,文件 I/O, 网络上传,委托三方 SDK 上报等)*/
40 | .addPrinter(CustomPrismLogcatSink())
41 | ```
42 |
43 | #### 自定义日志数据类
44 |
45 | App 自定义埋点数据类,用于承载埋点数据和,及实现 json 序列化,需实现 `ITraceable` 接口
46 |
47 | ```kotlin
48 | class CustomTrace() : ITraceable {
49 |
50 | override fun toActionJson(actionType: ActionType): JSONObject {
51 | // 根据 action 类型序列化输出
52 | }
53 |
54 | override fun toExposeJson(): JSONObject {
55 | // 曝光数据序列化输出
56 | }
57 | }
58 | ```
59 |
60 | #### 追踪曝光
61 |
62 | `View` 的曝光监听依赖 `ViewTraceHelper` 完成,内部依赖 `ViewExposureHelper` 完成对曝光的侦听
63 | `ViewExposureHelper` 依赖 `ILogPage` (逻辑页面) 提供的 `exposureStateHelper`:`ExposureStateHelper` 管理曝光状态
64 | 每个 `View` 对象对应一个 `ViewTraceHelper` 实例
65 | 每个 `ILogPage` 对应一个 `ExposureStateHelper` 实例
66 |
67 | ```kotlin
68 | class MainActivity : AppCompatActivity() {
69 |
70 | override fun onCreate(savedInstanceState: Bundle?) {
71 | …
72 | // TraceSpot: built-in traceable data model
73 | // 快速开启 `View` 的曝光监听:fun View.traceExpose(ILogPage, ITraceable) 扩展的增强函数
74 | // 效果:fab 按钮每次从不可见变成可见时,出发埋点,json: {"event_id": "fab_button_expose"}
75 | fab.traceExpose(asLogPage(), TraceSpot.of("fab_button"))
76 | …
77 | }
78 |
79 | …
80 | }
81 | ```
82 |
83 | #### 使用方法
84 |
85 | - 获取 `ILogPage`
86 | ```kotlin
87 | // 1. 原生页面直接获取,require: EZPrism.useRawPage()
88 | val exposureStateHelper = activity.asLogPage().exposureStateHelper
89 | val exposureStateHelper = fragment.asLogPage().exposureStateHelper
90 |
91 | // 2. 实现 ILogPage 接口,比如在自定义 View、Dialog 等(如需作为独立的曝光页面)
92 | ```
93 | - 获取 `ViewTraceHelper`
94 | ```kotlin
95 | val traceHelper = view.getTraceHelper()
96 | ```
97 | - 激活
98 | ```kotlin
99 | traceHelper.apply {
100 | trace = … // 赋值 ITraceable,绑定埋点数据对象
101 | exposureStateHelper = page.exposureStateHelper // 绑定曝光状态辅助器,可从 ILogPage 获取
102 | }
103 | ```
104 |
105 | 说明
106 | ---
107 |
108 | 主要概念:
109 | - 页面:`ILogPage`. 埋点事件以页面为单位整合管理,事件行为依赖所属页面的状态
110 | - 事件:`ITraceable`. 埋点事件的数据载体,设计为接口可自由实现为业务所需的数据结构
111 | - 埋点跟踪辅助器:`ViewTraceHelper`. 视图 `View` 埋点曝光组件,与 `View` 一一对应
112 | - 曝光状态辅助器:`ExposureStateHelper`. 数据曝光状态管理辅助器,与 `ILogPage` 一一对应
113 |
114 | Changes:
115 | ---
116 |
117 | ### 0.0.2
118 |
119 | feature:
120 |
121 | - 增加新的曝光模式:视图不可见时触发
122 | ```kotlin
123 | class CustomTrace : ITraceable, ITraceWhenInvisibleWithDuration by SimpleDuration() {
124 | …
125 | }
126 | ```
127 | 携带一次从可见到不可见的曝光时长 `duration`
128 | - 优化:删除了冗余的组件: `ViewExposureHelper`,直接又 `ViewTraceHelper` 控制曝光和埋点数据
129 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/app/Fragment.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.app
2 |
3 | import androidx.collection.SparseArrayCompat
4 | import androidx.fragment.app.Fragment
5 | import androidx.lifecycle.Lifecycle
6 | import cn.alvince.droidprism.EZPrism
7 | import cn.alvince.droidprism.internal.Instrumentation
8 | import cn.alvince.droidprism.internal.getOrPut
9 | import cn.alvince.droidprism.internal.lifecycle.observeWith
10 | import cn.alvince.droidprism.internal.logDIfDebug
11 | import cn.alvince.droidprism.internal.postOnMain
12 | import cn.alvince.droidprism.log.ExposureStateHelper
13 | import cn.alvince.droidprism.log.impl.LogPageEntryDelegate
14 | import cn.alvince.droidprism.log.page.ILogPage
15 | import cn.alvince.droidprism.log.page.LogPageManager
16 | import cn.alvince.droidprism.log.page.PageNameOf
17 | import cn.alvince.zanpakuto.core.text.orDefault
18 | import java.lang.ref.WeakReference
19 |
20 | /**
21 | * Retrieves [ILogPage] from [Fragment]
22 | *
23 | * @throws IllegalArgumentException fragment destroyed
24 | * @throws IllegalStateException fragment not implements [ILogPage], nor use-raw-page via [EZPrism.useRawPage]
25 | */
26 | @Throws(IllegalArgumentException::class, IllegalStateException::class)
27 | fun Fragment.asLogPage(): ILogPage {
28 | require(lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { "Fragment $this is already destroyed." }
29 | if (this is ILogPage) return this
30 | check(Instrumentation.useRawPage) { "Must enable raw page via EZPrism.useRawPage() first." }
31 | return obtainLogPage()
32 | }
33 |
34 | val Fragment.logExposeStateHelper: ExposureStateHelper?
35 | get() = try {
36 | asLogPage().exposureStateHelper
37 | } catch (e: IllegalArgumentException) {
38 | null
39 | } catch (e: IllegalStateException) {
40 | null
41 | }
42 |
43 | private val fragmentPageCache = SparseArrayCompat()
44 |
45 | private fun Fragment.obtainLogPage(name: String = ""): ILogPage {
46 | val k = this.hashCode()
47 | return fragmentPageCache.getOrPut(k) {
48 | FragmentPageRecord(k, this, LogPageEntryDelegate().apply { setPageName(PageNameOf(name.orDefault(this@obtainLogPage::class.java.simpleName))) })
49 | }
50 | .page
51 | }
52 |
53 | private class FragmentPageRecord(private val key: Int, fragment: Fragment, val page: ILogPage) {
54 |
55 | val target = WeakReference(fragment)
56 |
57 | private var _disposed: Boolean = false
58 |
59 | init {
60 | fragment.observeWith { _, event ->
61 | if (event == Lifecycle.Event.ON_DESTROY) {
62 | dispose()
63 | return@observeWith
64 | }
65 | if (event >= Lifecycle.Event.ON_PAUSE && event < Lifecycle.Event.ON_DESTROY) {
66 | dispatchPageShowChanged(false)
67 | return@observeWith
68 | }
69 | if (event > Lifecycle.Event.ON_CREATE && event < Lifecycle.Event.ON_PAUSE) {
70 | if (event == Lifecycle.Event.ON_RESUME) {
71 | LogPageManager.changePage(page)
72 | }
73 | dispatchPageShowChanged(true)
74 | }
75 | }
76 | }
77 |
78 | private fun dispatchPageShowChanged(show: Boolean) {
79 | logDIfDebug { "dispatch page show: [$show] ${page.pageName().id} : ${target.get()}" }
80 | page.onPageShowingChanged(show)
81 | }
82 |
83 | private fun dispose() {
84 | if (_disposed) {
85 | return
86 | }
87 | logDIfDebug { "dispose page: ${page.pageName().id}, ${target.get()}" }
88 | page.onPageShowingChanged(false)
89 | _disposed = true
90 | postOnMain { fragmentPageCache.remove(key) }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/page/LogPageManager.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log.page
2 |
3 | import android.util.Log
4 | import androidx.collection.SparseArrayCompat
5 | import cn.alvince.droidprism.internal.LOG_TAG
6 | import cn.alvince.droidprism.internal.PAGE_EMPTY
7 | import cn.alvince.droidprism.internal.TraceShooter
8 | import cn.alvince.droidprism.internal.checkMainThread
9 | import cn.alvince.droidprism.log.impl.LogPageEntryDelegate
10 | import java.lang.ref.WeakReference
11 |
12 | /**
13 | * Log page state and entry manager
14 | *
15 | * Create by bytedance on 2022/9/24
16 | *
17 | * @author zhangyang.alvince@bytedance.com
18 | */
19 | object LogPageManager {
20 |
21 | /**
22 | * virtual page node that indicate current background
23 | */
24 | private val cEmptyPageHolder = LogPageEntryDelegate(PAGE_EMPTY)
25 | private val rootEntry = PageEntryNode(0, cEmptyPageHolder, null, false)
26 |
27 | private var curPageEntry: ILogPageEntry? = null
28 |
29 | private var pageNode = rootEntry
30 | private var pageEntryIndex = SparseArrayCompat()
31 |
32 | fun changePage(page: ILogPage) {
33 | checkMainThread()
34 | if (page is ILogPageEntry) {
35 | setCurrentEntry(page)
36 | } else {
37 | Log.e(LOG_TAG, "Can not recognize $page")
38 | }
39 | }
40 |
41 | private fun setCurrentEntry(pageEntry: ILogPageEntry) {
42 | if (pageNode.target == pageEntry) {
43 | return
44 | }
45 | setCurrentEntryImpl(pageEntry)
46 | }
47 |
48 | private fun setCurrentEntryImpl(pageEntry: ILogPageEntry) {
49 | val curNode = pageNode.checkAvailableEntry()
50 | val hash = pageEntry.hashCode()
51 | pageNode += PageEntryNode(hash, pageEntry, curNode)
52 | // val curEmpty = curPageEntry == null
53 | curPageEntry?.also { TraceShooter.pageExit(it) }
54 | curPageEntry = pageEntry
55 | pageEntryIndex.putIfAbsent(hash, pageNode)
56 | TraceShooter.pageEntry(pageEntry)
57 | }
58 |
59 | private fun PageEntryNode.checkAvailableEntry(): PageEntryNode {
60 | if (prev == null) return this // current is root
61 |
62 | var node = this
63 | var p: PageEntryNode
64 | while (node.pageEntry.get() == null) {
65 | p = node.requirePrev()
66 | node.discard()
67 | node = p
68 | }
69 | return node
70 | }
71 |
72 | private inline fun PageEntryNode.discard() {
73 | prev?.next = null
74 | prev = null
75 | pageEntryIndex.remove(id)
76 | }
77 |
78 | /**
79 | * Page node record
80 | *
81 | * record page entry with a list chain
82 | *
83 | * -------- ------------- ----------------
84 | * | root | -> | next node | -> … -> | current node |
85 | * -------- ------------- ----------------
86 | */
87 | private class PageEntryNode constructor(val id: Int, page: ILogPageEntry, var prev: PageEntryNode?, requirePrev: Boolean = true) {
88 |
89 | val target: ILogPageEntry? get() = pageEntry.get()
90 |
91 | var pageEntry: WeakReference = WeakReference(page)
92 |
93 | var next: PageEntryNode? = null
94 |
95 | init {
96 | if (requirePrev) {
97 | requireNotNull(prev) { "Require prev entry node" }
98 | }
99 | }
100 |
101 | operator fun plus (node: PageEntryNode): PageEntryNode {
102 | return node.also {
103 | this.next = it
104 | it.prev = this
105 | }
106 | }
107 |
108 | fun requirePrev(): PageEntryNode = checkNotNull(prev) { "Invalid error" }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | EZPrism
3 | MainActivity
4 |
5 | Home
6 | First Fragment
7 | Second Fragment
8 | List Fragment
9 | Next
10 | Previous
11 |
12 | Expose when invisible
13 | Trace event while view visible to user
14 | Trace event while view invisible to user, with exposure duration
15 |
16 |
17 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam in scelerisque sem. Mauris
18 | volutpat, dolor id interdum ullamcorper, risus dolor egestas lectus, sit amet mattis purus
19 | dui nec risus. Maecenas non sodales nisi, vel dictum dolor. Class aptent taciti sociosqu ad
20 | litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse blandit eleifend
21 | diam, vel rutrum tellus vulputate quis. Aliquam eget libero aliquet, imperdiet nisl a,
22 | ornare ex. Sed rhoncus est ut libero porta lobortis. Fusce in dictum tellus.\n\n
23 | Suspendisse interdum ornare ante. Aliquam nec cursus lorem. Morbi id magna felis. Vivamus
24 | egestas, est a condimentum egestas, turpis nisl iaculis ipsum, in dictum tellus dolor sed
25 | neque. Morbi tellus erat, dapibus ut sem a, iaculis tincidunt dui. Interdum et malesuada
26 | fames ac ante ipsum primis in faucibus. Curabitur et eros porttitor, ultricies urna vitae,
27 | molestie nibh. Phasellus at commodo eros, non aliquet metus. Sed maximus nisl nec dolor
28 | bibendum, vel congue leo egestas.\n\n
29 | Sed interdum tortor nibh, in sagittis risus mollis quis. Curabitur mi odio, condimentum sit
30 | amet auctor at, mollis non turpis. Nullam pretium libero vestibulum, finibus orci vel,
31 | molestie quam. Fusce blandit tincidunt nulla, quis sollicitudin libero facilisis et. Integer
32 | interdum nunc ligula, et fermentum metus hendrerit id. Vestibulum lectus felis, dictum at
33 | lacinia sit amet, tristique id quam. Cras eu consequat dui. Suspendisse sodales nunc ligula,
34 | in lobortis sem porta sed. Integer id ultrices magna, in luctus elit. Sed a pellentesque
35 | est.\n\n
36 | Aenean nunc velit, lacinia sed dolor sed, ultrices viverra nulla. Etiam a venenatis nibh.
37 | Morbi laoreet, tortor sed facilisis varius, nibh orci rhoncus nulla, id elementum leo dui
38 | non lorem. Nam mollis ipsum quis auctor varius. Quisque elementum eu libero sed commodo. In
39 | eros nisl, imperdiet vel imperdiet et, scelerisque a mauris. Pellentesque varius ex nunc,
40 | quis imperdiet eros placerat ac. Duis finibus orci et est auctor tincidunt. Sed non viverra
41 | ipsum. Nunc quis augue egestas, cursus lorem at, molestie sem. Morbi a consectetur ipsum, a
42 | placerat diam. Etiam vulputate dignissim convallis. Integer faucibus mauris sit amet finibus
43 | convallis.\n\n
44 | Phasellus in aliquet mi. Pellentesque habitant morbi tristique senectus et netus et
45 | malesuada fames ac turpis egestas. In volutpat arcu ut felis sagittis, in finibus massa
46 | gravida. Pellentesque id tellus orci. Integer dictum, lorem sed efficitur ullamcorper,
47 | libero justo consectetur ipsum, in mollis nisl ex sed nisl. Donec maximus ullamcorper
48 | sodales. Praesent bibendum rhoncus tellus nec feugiat. In a ornare nulla. Donec rhoncus
49 | libero vel nunc consequat, quis tincidunt nisl eleifend. Cras bibendum enim a justo luctus
50 | vestibulum. Fusce dictum libero quis erat maximus, vitae volutpat diam dignissim.
51 |
52 |
53 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/operator/ViewExposureController.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.operator
2 |
3 | import android.view.View
4 | import android.view.ViewTreeObserver
5 | import androidx.core.view.isVisible
6 | import cn.alvince.droidprism.R
7 | import cn.alvince.droidprism.log.ExposureStateHelper
8 | import cn.alvince.droidprism.log.ITraceable
9 | import java.lang.ref.WeakReference
10 |
11 | internal interface IViewExposureController {
12 |
13 | val traceable: ITraceable?
14 |
15 | val stateManager: ExposureStateHelper?
16 | }
17 |
18 | internal class ExposeListener(v: View, private val exposureHelper: IViewExposureController) : ViewTreeObserver.OnGlobalLayoutListener,
19 | ViewTreeObserver.OnScrollChangedListener, View.OnAttachStateChangeListener {
20 |
21 | private val viewRef = WeakReference(v)
22 |
23 | override fun onGlobalLayout() {
24 | viewRef.get()?.also { onViewLayoutChange(it, exposureHelper) }
25 | }
26 |
27 | override fun onScrollChanged() {
28 | viewRef.get()?.also { onViewLayoutChange(it, exposureHelper) }
29 | }
30 |
31 | override fun onViewAttachedToWindow(v: View) {
32 | v.viewTreeObserver.addOnScrollChangedListener(this)
33 | v.viewTreeObserver.addOnGlobalLayoutListener(this)
34 | onViewLayoutChange(v, exposureHelper, true)
35 | }
36 |
37 | override fun onViewDetachedFromWindow(v: View) {
38 | v.viewTreeObserver.removeOnScrollChangedListener(this)
39 | v.viewTreeObserver.removeOnGlobalLayoutListener(this)
40 | onViewLayoutChange(v, exposureHelper, false)
41 | }
42 | }
43 |
44 | internal fun View.monitorExposureState(viewExposureController: IViewExposureController?) {
45 | val original = this.getTag(R.id.view_exposure_listener_holder) as? ExposeListener
46 | if (original != null) {
47 | if (this.isAttachedToWindow) {
48 | original.onViewDetachedFromWindow(this)
49 | }
50 | this.removeOnAttachStateChangeListener(original)
51 | }
52 | if (viewExposureController == null) {
53 | return
54 | }
55 | onViewLayoutChange(this, viewExposureController)
56 | val listener = ExposeListener(this, viewExposureController)
57 | if (this.isAttachedToWindow) {
58 | listener.onViewAttachedToWindow(this)
59 | }
60 | this.addOnAttachStateChangeListener(listener)
61 | this.setTag(R.id.view_exposure_listener_holder, listener)
62 | }
63 |
64 | internal fun IViewExposureController.forceCheck(view: View) {
65 | onViewLayoutChange(view, this)
66 | }
67 |
68 | private fun onViewLayoutChange(v: View, exposureController: IViewExposureController, attachState: Boolean? = null) {
69 | val traceItem = exposureController.traceable ?: return
70 | exposureController.stateManager?.also { stateHelper ->
71 | val exposing = isViewExposing(v, attachState)
72 | stateHelper.markExposeState(traceItem, exposing)
73 | }
74 | }
75 |
76 | ///////////////////////////////////////////////////////////////////////////
77 | // following below is check the view state
78 | ///////////////////////////////////////////////////////////////////////////
79 |
80 | private val View.actualAlpha: Float
81 | get() {
82 | var r = 1.0F
83 | traverseAncestor { r *= it.alpha }
84 | return r
85 | }
86 |
87 | private val View.isActualVisible: Boolean
88 | get() {
89 | traverseAncestor {
90 | if (!it.isVisible) {
91 | return false
92 | }
93 | }
94 | return true
95 | }
96 |
97 | private fun isViewExposing(v: View, attachState: Boolean?): Boolean {
98 | if (!v.isActualVisible) {
99 | return false
100 | }
101 | if (v.actualAlpha < 0.01) {
102 | return false
103 | }
104 | if (!(attachState ?: v.isAttachedToWindow)) {
105 | return false
106 | }
107 | val w = v.width
108 | val h = v.height
109 | if (w <= 0 || h <= 0) return false
110 | val out = intArrayOf(0, 0)
111 | v.getLocationOnScreen(out)
112 | val x = out[0] + w / 2
113 | val y = out[1] + h / 2
114 | return checkPointShowing(x, y, v, out)
115 | }
116 |
117 | private fun checkPointShowing(x: Int, y: Int, v: View, out: IntArray): Boolean {
118 | v.traverseAncestor { view ->
119 | view.getLocationOnScreen(out)
120 | val vx = out[0]
121 | val vy = out[1]
122 | if (x !in vx..vx + view.width || y !in vy..vy + view.height) {
123 | return false
124 | }
125 | }
126 | return true
127 | }
128 |
129 | private inline fun View.traverseAncestor(withThis: Boolean = true, block: (View) -> Unit) {
130 | var view: View? = this
131 | while (view != null) {
132 | if (withThis || view !== this) {
133 | block(view)
134 | }
135 | view = view.parent as? View
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/operator/ViewTraceHelper.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.operator
2 |
3 | import android.view.View
4 | import androidx.annotation.MainThread
5 | import cn.alvince.droidprism.R
6 | import cn.alvince.droidprism.internal.Instrumentation
7 | import cn.alvince.droidprism.log.ActionType
8 | import cn.alvince.droidprism.log.ExposureStateHelper
9 | import cn.alvince.droidprism.log.ITraceable
10 | import cn.alvince.zanpakuto.core.property.NullableProperty
11 | import cn.alvince.zanpakuto.core.property.ObservableProperty
12 | import java.lang.ref.WeakReference
13 |
14 | /**
15 | * Universal [android.view.View] trace handler
16 | *
17 | * Created by alvince on 2022/5/23
18 | *
19 | * @author alvince.zy@gmail.com
20 | */
21 | class ViewTraceHelper internal constructor(val option: ViewTraceOption) : ViewTraceOption.Observer, IViewExposureController {
22 |
23 | override val traceable: ITraceable? get() = trace
24 |
25 | override val stateManager: ExposureStateHelper? get() = exposureStateHelper
26 |
27 | var trace: ITraceable? by NullableProperty { value -> applyTraceItemChanged(value) }
28 |
29 | var exposureStateHelper: ExposureStateHelper? by NullableProperty { value ->
30 | value?.also { applyViewExposureHelper() }
31 | }
32 |
33 | private val targetView: View? get() = targetViewRef?.get()
34 |
35 | private var targetViewRef: WeakReference? = null
36 |
37 | override fun onOptionChanged(optionName: String) {
38 | when (optionName) {
39 | "enableExposureTrace" -> {
40 | if (option.enableExposureTrace) {
41 | exposureStateHelper?.also { applyViewExposureHelper() }
42 | } else {
43 | // clear exposure helper
44 | targetView?.monitorExposureState(null)
45 | }
46 | }
47 | }
48 | }
49 |
50 | fun attachToView(view: View) {
51 | val attached = from(view)
52 | if (attached === this) {
53 | return
54 | }
55 | attached?.detachFromView()
56 | // attach to new target
57 | view.setTag(R.id.view_trace_helper_holder, this)
58 | targetViewRef = WeakReference(view)
59 | if (option.enableExposureTrace) {
60 | view.monitorExposureState(this)
61 | }
62 | }
63 |
64 | fun deactivate() {
65 | detachFromView()
66 | trace = null
67 | }
68 |
69 | private fun detachFromView() {
70 | targetViewRef?.get()?.also { v ->
71 | // clear target trace helper
72 | v.setTag(R.id.view_trace_helper_holder, "")
73 | // clear exposure listener
74 | if (option.enableExposureTrace) {
75 | v.monitorExposureState(null)
76 | }
77 | }
78 | }
79 |
80 | private fun applyTraceItemChanged(trace: ITraceable?) {
81 | if (option.enableExposureTrace) {
82 | trace?.also { exposureStateHelper?.markExposeState(it, false) }
83 | targetView?.also { forceCheck(it) }
84 | }
85 | }
86 |
87 | private fun applyViewExposureHelper() {
88 | trace ?: return
89 | if (!option.enableExposureTrace) {
90 | return
91 | }
92 | targetView?.monitorExposureState(this)
93 | }
94 |
95 | companion object {
96 |
97 | @JvmStatic
98 | @MainThread
99 | fun clear(view: View) {
100 | from(view)?.deactivate()
101 | }
102 |
103 | @JvmStatic
104 | @MainThread
105 | fun traceClickIfNeeded(view: View) {
106 | from(view)
107 | ?.takeIf { it.option.enableClickTrace }
108 | ?.trace
109 | ?.also {
110 | Instrumentation.eventEmitter.emitAction(ActionType.CLICK, it)
111 | }
112 | }
113 |
114 | @JvmStatic
115 | fun from(view: View): ViewTraceHelper? {
116 | return view.getTag(R.id.view_trace_helper_holder) as? ViewTraceHelper
117 | }
118 |
119 | /**
120 | * Create [ViewTraceHelper] instance with exposure enable specified
121 | */
122 | @JvmStatic
123 | fun create(enableExposure: Boolean = true): ViewTraceHelper {
124 | return ViewTraceOption().apply {
125 | enableExposureTrace = enableExposure
126 | }.let {
127 | ViewTraceHelper(it)
128 | }
129 | }
130 | }
131 | }
132 |
133 | class ViewTraceOption {
134 |
135 | interface Observer {
136 | fun onOptionChanged(optionName: String)
137 | }
138 |
139 | var enableClickTrace: Boolean by ObservableProperty(true) { observer?.onOptionChanged("enableClickTrace") }
140 |
141 | var enableExposureTrace: Boolean by ObservableProperty(true) { observer?.onOptionChanged("enableExposureTrace") }
142 |
143 | private var observer: Observer? = null
144 | }
145 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/log/ExposureStateHelper.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.log
2 |
3 | import androidx.collection.ArraySet
4 | import androidx.collection.arrayMapOf
5 | import cn.alvince.droidprism.internal.Instrumentation
6 | import cn.alvince.droidprism.internal.logDIfDebug
7 | import cn.alvince.droidprism.internal.mainHandler
8 | import cn.alvince.zanpakuto.core.property.ObservableProperty
9 | import cn.alvince.zanpakuto.core.time.Duration
10 | import cn.alvince.zanpakuto.core.time.Timestamp
11 |
12 | /**
13 | * [ITraceable] exposure state handler
14 | *
15 | * Created by alvince on 2022/5/23
16 | *
17 | * @author alvince.zy@gmail.com
18 | */
19 | class ExposureStateHelper internal constructor() {
20 |
21 | var pageShowing: Boolean by ObservableProperty(false) { show ->
22 | if (show) {
23 | traceElements.forEach { getState(it).showing = true }
24 | } else {
25 | traceElements.forEach { getState(it).showing = false }
26 | }
27 | }
28 |
29 | private val traceElements = ArraySet()
30 | private val stateMap = arrayMapOf()
31 |
32 | fun markExposeState(traceItem: ITraceable, showing: Boolean) {
33 | logDIfDebug { "mark expose state: $showing - $traceItem" }
34 | val hasChanged = if (showing) traceElements.add(traceItem) else traceElements.remove(traceItem)
35 | if (hasChanged && pageShowing) {
36 | getState(traceItem).also { state ->
37 | if (state.showing != showing) {
38 | state.showing = showing
39 | }
40 | }
41 | }
42 | }
43 |
44 | private fun getState(spot: ITraceable): TraceItemState = stateMap.getOrPut(spot) { gc(); TraceItemState(spot) }
45 |
46 | private fun gc() {
47 | if (stateMap.size > 1000) {
48 | val now = Timestamp.now()
49 | stateMap.entries.removeAll { (_, state) -> !state.showing && now - state.lastHideTime > Instrumentation.exposeTimeThreshold }
50 | }
51 | }
52 |
53 | private class TraceItemState(val trace: ITraceable) : Runnable {
54 |
55 | var lastShowTime: Timestamp = Timestamp.ZERO
56 | var lastHideTime: Timestamp = Timestamp.ZERO
57 |
58 | var showing: Boolean by ObservableProperty(false) { changeShowingState(it) }
59 |
60 | private val traceWhenInvisible: Boolean = trace is ITraceWhenInvisible
61 |
62 | private var scheduled = false
63 | private var hasCancelledScheduling = false
64 |
65 | private var exposureDuration: Duration = Duration.ZERO
66 |
67 | override fun run() {
68 | logDIfDebug { "request emit expose event: $trace" }
69 | trace.also {
70 | beforeTryEmitEvent(it)
71 | Instrumentation.emitExposeEventIfNotTooFrequent(it)
72 | (it as? ITraceWhenInvisibleWithDuration)?.duration = Duration.ZERO
73 | }
74 | scheduled = false
75 | }
76 |
77 | private fun beforeTryEmitEvent(trace: ITraceable) {
78 | (trace as? ITraceWhenInvisibleWithDuration)?.duration = exposureDuration
79 | }
80 |
81 | private fun changeShowingState(showing: Boolean) {
82 | logDIfDebug { "change trace state: $showing - $trace" }
83 | val now = Timestamp.now()
84 | if (showing) {
85 | lastShowTime = now
86 | } else {
87 | lastHideTime = now
88 | }
89 | if (traceWhenInvisible) {
90 | checkStateOrEmitWhenInvisible(showing, now)
91 | } else {
92 | checkStateOrEmit(showing, now)
93 | }
94 | }
95 |
96 | private fun clearScheduler() {
97 | hasCancelledScheduling = scheduled
98 | mainHandler.removeCallbacks(this)
99 | scheduled = false
100 | exposureDuration = Duration.ZERO
101 | (trace as? ITraceWhenInvisibleWithDuration)?.duration = Duration.ZERO
102 | }
103 |
104 | private fun checkStateOrEmit(showing: Boolean, now: Timestamp) {
105 | if (!showing) {
106 | clearScheduler()
107 | return
108 | }
109 | val threshold = Instrumentation.exposeTimeThreshold
110 | if (now - lastHideTime >= threshold || hasCancelledScheduling) {
111 | logDIfDebug { "schedule delayed expose event: $trace" }
112 | scheduled = true
113 | mainHandler.postDelayed(this, threshold.inMillis)
114 | }
115 | hasCancelledScheduling = false
116 | }
117 |
118 | private fun checkStateOrEmitWhenInvisible(showing: Boolean, now: Timestamp) {
119 | if (showing) {
120 | clearScheduler()
121 | return
122 | }
123 | val threshold = Instrumentation.exposeTimeThreshold
124 | val interval = now - lastShowTime
125 | // require the target has been shown once
126 | if (lastShowTime > Timestamp.ZERO && (interval >= threshold || hasCancelledScheduling)) {
127 | logDIfDebug { "schedule delayed expose event: $trace" }
128 | scheduled = true
129 | exposureDuration = interval
130 | mainHandler.postDelayed(this, threshold.inMillis)
131 | }
132 | hasCancelledScheduling = false
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/java/cn/alvince/droidprism/sample/list/TraceListFragment.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.sample.list
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import android.widget.TextView
8 | import androidx.appcompat.widget.AppCompatTextView
9 | import androidx.fragment.app.Fragment
10 | import androidx.recyclerview.widget.DiffUtil
11 | import androidx.recyclerview.widget.LinearLayoutManager
12 | import androidx.recyclerview.widget.RecyclerView
13 | import cn.alvince.droidprism.app.asLogPage
14 | import cn.alvince.droidprism.log.ExposureStateHelper
15 | import cn.alvince.droidprism.sample.R
16 | import cn.alvince.droidprism.sample.databinding.TraceListFragmentBinding
17 | import cn.alvince.droidprism.sample.trace.SampleInvisibleTrace
18 | import cn.alvince.droidprism.sample.trace.SampleTrace
19 | import cn.alvince.droidprism.util.exposeWith
20 | import cn.alvince.droidprism.util.getTraceHelper
21 | import cn.alvince.zanpakuto.core.dimens.dp
22 |
23 | /**
24 | * Create by bytedance on 2022/9/10
25 | *
26 | * @author zhangyang.alvince@bytedance.com
27 | */
28 | class TraceListFragment : Fragment() {
29 |
30 | private val defaultModeInvisible: Boolean get() = arguments?.getBoolean("__arg_expose_when_invisible", false) == true
31 |
32 | private lateinit var listAdapter: ListAdapter
33 |
34 | private var _binding: TraceListFragmentBinding? = null
35 |
36 | override fun onCreate(savedInstanceState: Bundle?) {
37 | super.onCreate(savedInstanceState)
38 | listAdapter = ListAdapter(object : DiffUtil.ItemCallback() {
39 | override fun areItemsTheSame(oldItem: ListItem, newItem: ListItem): Boolean = oldItem === newItem
40 |
41 | override fun areContentsTheSame(oldItem: ListItem, newItem: ListItem): Boolean = oldItem == newItem
42 | }, asLogPage().exposureStateHelper)
43 | }
44 |
45 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
46 | TraceListFragmentBinding.inflate(inflater, container, false)
47 | .also {
48 | _binding = it
49 | it.initView()
50 | }
51 | .root
52 |
53 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
54 | super.onViewCreated(view, savedInstanceState)
55 | applyListItem(!defaultModeInvisible)
56 | }
57 |
58 | override fun onDestroyView() {
59 | _binding = null
60 | super.onDestroyView()
61 | }
62 |
63 | private fun TraceListFragmentBinding.initView() {
64 | switchExposureMode.apply {
65 | isChecked = defaultModeInvisible
66 | setOnCheckedChangeListener { _, isChecked ->
67 | tvModeExplain.text = getString(if (isChecked) R.string.trace_list_exposure_mode_invisible else R.string.trace_list_exposure_mode_normal)
68 | applyListItem(!isChecked)
69 | }
70 | }
71 | rvList.apply {
72 | layoutManager = LinearLayoutManager(requireContext())
73 | adapter = listAdapter
74 | }
75 | }
76 |
77 | private fun applyListItem(normalOrInvisible: Boolean) {
78 | listAdapter.submitList(arrayListOf().apply {
79 | for (i in 0 until 100) {
80 | add(ListItem("list item $i", i.toString(), !normalOrInvisible))
81 | }
82 | })
83 | }
84 |
85 | class ListAdapter(callback: DiffUtil.ItemCallback, private val exposureStateHelper: ExposureStateHelper) :
86 | androidx.recyclerview.widget.ListAdapter(callback) {
87 |
88 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
89 | return ListViewHolder(AppCompatTextView(parent.context).apply {
90 | textSize = 18F
91 | val (horiz, vertical) = 16.dp.toPxInt(context) to 12.dp.toPxInt(context)
92 | setPaddingRelative(horiz, vertical, horiz, vertical)
93 | exposeWith(exposureStateHelper, null)
94 | })
95 | }
96 |
97 | override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
98 | getItem(position)?.also { item ->
99 | holder.view.apply {
100 | text = item.content
101 | getTraceHelper().trace = item.trace
102 | }
103 | }
104 | }
105 | }
106 |
107 | class ListViewHolder(val view: TextView) : RecyclerView.ViewHolder(view)
108 |
109 | class ListItem(val content: String, val id: Any, val traceWhenInvisible: Boolean) {
110 |
111 | val trace: SampleTrace = if (traceWhenInvisible) SampleInvisibleTrace("item_$id") else SampleTrace("item_$id")
112 |
113 | override fun equals(other: Any?): Boolean {
114 | if (this === other) return true
115 | if (other !is ListItem) return false
116 |
117 | if (content != other.content) return false
118 | if (id != other.id) return false
119 | if (traceWhenInvisible != other.traceWhenInvisible) return false
120 |
121 | return true
122 | }
123 |
124 | override fun hashCode(): Int {
125 | var result = content.hashCode()
126 | result = 31 * result + id.hashCode()
127 | result = 31 * result + traceWhenInvisible.hashCode()
128 | return result
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/lib-prism-core/src/main/java/cn/alvince/droidprism/app/Activity.kt:
--------------------------------------------------------------------------------
1 | package cn.alvince.droidprism.app
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.os.Build
6 | import android.os.Bundle
7 | import androidx.collection.SparseArrayCompat
8 | import androidx.lifecycle.Lifecycle
9 | import androidx.lifecycle.LifecycleOwner
10 | import cn.alvince.droidprism.EZPrism
11 | import cn.alvince.droidprism.internal.Instrumentation
12 | import cn.alvince.droidprism.internal.getOrPut
13 | import cn.alvince.droidprism.internal.lifecycle.observeWith
14 | import cn.alvince.droidprism.internal.logDIfDebug
15 | import cn.alvince.droidprism.internal.postOnMain
16 | import cn.alvince.droidprism.internal.runOnMain
17 | import cn.alvince.droidprism.log.ExposureStateHelper
18 | import cn.alvince.droidprism.log.impl.LogPageEntryDelegate
19 | import cn.alvince.droidprism.log.page.ILogPage
20 | import cn.alvince.droidprism.log.page.LogPageManager
21 | import cn.alvince.droidprism.log.page.PageNameOf
22 | import cn.alvince.zanpakuto.core.text.orDefault
23 | import java.lang.ref.WeakReference
24 |
25 | /**
26 | * Retrieves [ILogPage] from [Activity]
27 | *
28 | * @throws IllegalArgumentException activity destroyed
29 | * @throws IllegalStateException activity not implements [ILogPage], nor use-raw-page via [EZPrism.useRawPage]
30 | */
31 | @Throws(IllegalArgumentException::class, IllegalStateException::class)
32 | fun Activity.asLogPage(): ILogPage {
33 | require(!isFinishing && !isDestroyed) { "Activity $this is already destroyed." }
34 | if (this is ILogPage) return this
35 | check(Instrumentation.useRawPage) { "Must enable raw page via EZPrism.useRawPage() first." }
36 | return obtainLogPage()
37 | }
38 |
39 | val Activity.logExposeStateHelper: ExposureStateHelper?
40 | get() = try {
41 | asLogPage().exposureStateHelper
42 | } catch (e: IllegalArgumentException) {
43 | null
44 | } catch (e: IllegalStateException) {
45 | null
46 | }
47 |
48 | private val activityPageCache = SparseArrayCompat()
49 |
50 | private fun Activity.obtainLogPage(name: String = ""): ILogPage {
51 | val k = this.hashCode()
52 | return activityPageCache.getOrPut(k) {
53 | ActivityPageRecord(k, this, LogPageEntryDelegate().apply { setPageName(PageNameOf(name.orDefault(this@obtainLogPage::class.java.simpleName))) })
54 | }
55 | .page
56 | }
57 |
58 | private class ActivityPageRecord(private val key: Int, activity: Activity, val page: ILogPage) : Application.ActivityLifecycleCallbacks {
59 |
60 | val target = WeakReference(activity)
61 |
62 | private var _disposed: Boolean = false
63 |
64 | init {
65 | if (activity is LifecycleOwner) {
66 | observeComponentActivity(activity)
67 | } else {
68 | observeActivityCompat(activity)
69 | }
70 | }
71 |
72 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
73 | }
74 |
75 | override fun onActivityStarted(activity: Activity) {
76 | if (activity === target.get()) {
77 | LogPageManager.changePage(page)
78 | }
79 | }
80 |
81 | override fun onActivityResumed(activity: Activity) {
82 | if (activity === target.get()) {
83 | dispatchPageShowChanged(true)
84 | }
85 | }
86 |
87 | override fun onActivityPaused(activity: Activity) {
88 | if (activity === target.get()) {
89 | dispatchPageShowChanged(false)
90 | }
91 | }
92 |
93 | override fun onActivityStopped(activity: Activity) {
94 | }
95 |
96 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
97 | }
98 |
99 | override fun onActivityDestroyed(activity: Activity) {
100 | if (activity === target.get()) {
101 | dispose()
102 | }
103 | }
104 |
105 | private fun observeComponentActivity(activity: LifecycleOwner) {
106 | activity.observeWith { _, event ->
107 | if (event == Lifecycle.Event.ON_DESTROY) {
108 | runOnMain { dispose() }
109 | return@observeWith
110 | }
111 | if (event >= Lifecycle.Event.ON_PAUSE && event < Lifecycle.Event.ON_DESTROY) {
112 | dispatchPageShowChanged(false)
113 | return@observeWith
114 | }
115 | if (event >= Lifecycle.Event.ON_START && event < Lifecycle.Event.ON_PAUSE) {
116 | if (event == Lifecycle.Event.ON_START) {
117 | LogPageManager.changePage(page)
118 | }
119 | dispatchPageShowChanged(true)
120 | }
121 | }
122 | }
123 |
124 | private fun observeActivityCompat(activity: Activity) {
125 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
126 | activity.registerActivityLifecycleCallbacks(this)
127 | } else {
128 | activity.application.registerActivityLifecycleCallbacks(this)
129 | }
130 | }
131 |
132 | private fun dispatchPageShowChanged(show: Boolean) {
133 | logDIfDebug { "dispatch page show: [$show] ${page.pageName().id} : ${target.get()}" }
134 | page.onPageShowingChanged(show)
135 | }
136 |
137 | private fun dispose() {
138 | if (_disposed) {
139 | return
140 | }
141 | logDIfDebug { "dispose page: ${page.pageName().id}, ${target.get()}" }
142 | page.onPageShowingChanged(false)
143 | _disposed = true
144 | postOnMain { activityPageCache.remove(key) }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 alvince
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------