build: Task 24 완료 - :feature:feature-reader 1차 모듈 분리 (WebReaderActivity, PagedTextLayout, TouchArea)

- core/core-common: SimpleGesture.kt를 :app에서 :core:core-common으로 이동 (BuildConfig 경로 현행화)
- feature/feature-reader 모듈 신규 생성 (namespace: bums.lunatic.launcher.feature.reader):
  * WebReaderActivity.kt 및 activity_wr.xml 이동 (R 네임스페이스 분리)
  * PagedTextLayout.kt 이동 및 layout_textviewer/뷰 ID를 companion object 주입(LunaticLauncher 바인딩)으로 디커플링
  * Settings.kt에서 TouchArea enum을 feature-reader의 TouchArea.kt로 추출
- settings.gradle.kts, app/build.gradle.kts, ARCHITECTURE.md, TODO.md(6-3 갱신) 업데이트
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (19s, 121 actionable tasks)
This commit is contained in:
2026-11-16 13:30:52 +09:00
parent 684a10993e
commit ed8c3eb815
13 changed files with 66 additions and 12 deletions
@@ -118,6 +118,13 @@ prefs:
PrefHelper.initialize(this)
bums.lunatic.launcher.model.RssDataType.enabledChecker = { key -> PrefHelper.getBoolean(key, false) }
bums.lunatic.launcher.workers.WorkersDb.schemaVersion = BuildConfig.BuildDateTime
bums.lunatic.launcher.home.tokiz.view.PagedTextLayout.apply {
layoutResId = R.layout.layout_textviewer
firstViewId = R.id.first_view
secondViewId = R.id.sencond_view
currentPageId = R.id.current_page
currentChapterId = R.id.current_chapter
}
bums.lunatic.launcher.wall.MyWallpaperService.weatherSummaryProvider = {
bums.lunatic.launcher.workers.LocationUpdateService.lastWeather
}
@@ -1,295 +0,0 @@
package bums.lunatic.launcher.home
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.WindowManager
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import bums.lunatic.launcher.R
import androidx.core.net.toUri
import bums.lunatic.launcher.utils.Blog
class WebReaderActivity : AppCompatActivity() {
private lateinit var webView: WebView
private var filePathCallback: ValueCallback<Array<Uri>>? = null
// 원본 서버 주소 (이 주소로 위조할 예정)
private val SERVER_URL = "https://git.lunaticbum.kr/reader.html"
private val BASE_URL = "https://git.lunaticbum.kr/"
// 백업 데이터를 임시로 저장할 변수
private var pendingBackupData: String? = null
// 1. 파일 열기 (업로드/복원용) 런처
// 1. 파일 열기 (업로드/복원용) 런처 - 다중 파일 지원으로 수정
private val fileChooserLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
var uriList: Array<Uri>? = null
// 다중 선택을 했을 경우 (clipData로 데이터가 들어옴)
if (data?.clipData != null) {
val count = data.clipData!!.itemCount
uriList = Array(count) { i ->
data.clipData!!.getItemAt(i).uri
}
}
// 단일 선택을 했을 경우 (data로 데이터가 들어옴)
else if (data?.data != null) {
uriList = arrayOf(data.data!!)
}
filePathCallback?.onReceiveValue(uriList)
} else {
filePathCallback?.onReceiveValue(null)
}
filePathCallback = null
}
private fun isNetworkConnected(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork ?: return false
val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
return when {
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
// 2. 파일 저장 (백업용) 런처 - 안드로이드 표준 저장 탐색기 호출
private val fileSaveLauncher = registerForActivityResult(
ActivityResultContracts.CreateDocument("application/json")
) { uri: Uri? ->
uri?.let { saveUri ->
pendingBackupData?.let { jsonData ->
try {
// 선택한 경로에 백업 데이터 쓰기
contentResolver.openOutputStream(saveUri)?.use { outputStream ->
outputStream.write(jsonData.toByteArray(Charsets.UTF_8))
}
Toast.makeText(this, "서재 백업이 완료되었습니다.", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(this, "백업 저장에 실패했습니다.", Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
}
}
pendingBackupData = null // 작업 후 초기화
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_wr)
webView = findViewById(R.id.webView)
setupWebView()
// 🌟 수정된 부분: 인터넷 상태를 먼저 체크합니다!
if (isNetworkConnected()) {
// 뒤에 ?v=현재시간 을 붙여서 서버/프록시 캐시 우회 (reader.html의 ?id= 파싱에는 영향 없음)
webView.loadUrl("$SERVER_URL?v=${System.currentTimeMillis()}")
} else {
loadLocalHtmlAsServer()
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
var uri : Uri? = webView.url?.toUri()
if (webView.canGoBack() && (uri?.queryParameterNames?.size ?: 0) > 0) {
webView.loadUrl(SERVER_URL)
} else {
this@WebReaderActivity.finish()
}
}
})
}
private fun setupWebView() {
webView.clearCache(true)
webView.settings.apply {
cacheMode = WebSettings.LOAD_NO_CACHE
javaScriptEnabled = true
domStorageEnabled = true
allowFileAccess = true
allowContentAccess = true
useWideViewPort = true
loadWithOverviewMode = true
}
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url = request?.url.toString()
// 1. 현재 오프라인 상태이고
// 2. 이동하려는 주소가 내 서버 주소(예: reader.html?id=123)일 때
if (!isNetworkConnected() && url.startsWith(BASE_URL)) {
// 실제 네트워크 통신을 차단하고, 해당 URL로 위조된 로컬 HTML을 다시 로드
loadLocalHtmlAsServer(url)
// return true를 하면 웹뷰가 자체적인 네트워크 통신을 진행하지 않음
return true
}
return super.shouldOverrideUrlLoading(view, request)
}
// 🌐 에러 감지 1: 비행기 모드, 인터넷 끊김 등
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
if (request?.isForMainFrame == true) {
loadLocalHtmlAsServer()
}
}
// 🌐 에러 감지 2: 서버 점검, 404/500 에러 등
override fun onReceivedHttpError(
view: WebView?,
request: WebResourceRequest?,
errorResponse: WebResourceResponse?
) {
super.onReceivedHttpError(view, request, errorResponse)
if (request?.isForMainFrame == true) {
loadLocalHtmlAsServer()
}
}
// 🚨 핵심 포인트: JS 파일 가로채기
// HTML이 로컬에서 로드되더라도 주소가 위조되었기 때문에 JS파일도 서버에 요청해버립니다.
// 이를 중간에 가로채서 로컬 assets 폴더의 jszip.min.js를 던져줍니다.
override fun shouldInterceptRequest(
view: WebView?,
request: WebResourceRequest?
): WebResourceResponse? {
val url = request?.url.toString()
if (url.contains("sw.js")) {
// 서비스 워커 스크립트 차단 (네이티브 앱은 assets 폴백을 쓰므로 불필요)
return WebResourceResponse("text/javascript", "UTF-8", "".byteInputStream())
}
if (url.contains("jszip.min.js")) {
return try {
val inputStream = assets.open("jszip.min.js")
WebResourceResponse("text/javascript", "UTF-8", inputStream)
} catch (e: Exception) {
null
}
}
return super.shouldInterceptRequest(view, request)
}
}
// 3. 웹 -> 안드로이드 통신을 위한 브릿지 연결
webView.addJavascriptInterface(WebAppInterface(), "AndroidBridge")
webView.webChromeClient = object : WebChromeClient() {
override fun onShowFileChooser(
webView: WebView?,
filePathCallback: ValueCallback<Array<Uri>>?,
fileChooserParams: FileChooserParams?
): Boolean {
this@WebReaderActivity.filePathCallback?.onReceiveValue(null)
this@WebReaderActivity.filePathCallback = filePathCallback
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
// ⭐ 추가된 핵심 코드: 웹에서 multiple 속성을 보냈는지 확인 후 안드로이드 파일 탐색기에도 적용
if (fileChooserParams?.mode == FileChooserParams.MODE_OPEN_MULTIPLE) {
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
}
}
fileChooserLauncher.launch(intent)
return true
}
}
}
/**
* assets 폴더의 html 파일을 읽어와서 서버 주소로 위조하여 웹뷰에 로드합니다.
*/
private fun loadLocalHtmlAsServer(targetUrl: String = SERVER_URL) {
try {
Blog.LOGE("targetUrl ${targetUrl}")
val htmlString = assets.open("reader.html").bufferedReader().use { it.readText() }
webView.loadDataWithBaseURL(
targetUrl,
htmlString,
"text/html",
"UTF-8",
targetUrl // 🌟 핵심: ?id= 파라미터가 붙은 주소로 히스토리를 위조!
)
Toast.makeText(this, "오프라인 모드로 실행되었습니다.", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(this, "로컬 파일을 불러오지 못했습니다.", Toast.LENGTH_SHORT).show()
}
}
// 웹에서 호출할 수 있는 인터페이스 클래스
inner class WebAppInterface {
@JavascriptInterface
fun saveBackup(jsonData: String) {
// 웹에서 전달받은 JSON 데이터를 임시 저장
pendingBackupData = jsonData
// UI 스레드에서 파일 저장 탐색기 실행
runOnUiThread {
val fileName = "web_reader_backup_${System.currentTimeMillis()}.json"
fileSaveLauncher.launch(fileName)
}
}
}
// 볼륨 키 이벤트 가로채기 (페이지 넘김)
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_VOLUME_DOWN -> {
webView.evaluateJavascript("window.dispatchEvent(new KeyboardEvent('keydown', {'key': 'ArrowRight'}));", null)
return true
}
KeyEvent.KEYCODE_VOLUME_UP -> {
webView.evaluateJavascript("window.dispatchEvent(new KeyboardEvent('keydown', {'key': 'ArrowLeft'}));", null)
return true
}
}
return super.onKeyDown(keyCode, event)
}
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
}
@@ -91,9 +91,6 @@ fun getIndex(collection : PairArray<Any>, key : String) : Int {
}
return returns
}
enum class TouchArea {
Left,Center,Right, DoubleLeft, DoubleRight
}
class Settings : CommonActivity() {
@@ -1,435 +0,0 @@
package bums.lunatic.launcher.home.tokiz.view
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Build
import android.os.Handler
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Guideline
import bums.lunatic.launcher.R
import bums.lunatic.launcher.home.tokiz.TouchArea
import bums.lunatic.launcher.utils.Blog
import bums.lunatic.launcher.utils.SimpleFingerGestures
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.min
interface PagedTextViewInterface {
fun onTouch(touchArea: TouchArea)
fun onTimeoverTouch()
fun onSwipeLeft(touchCount : Int)
fun onSwipeRight(touchCount : Int)
fun onSwipeDown(touchCount : Int)
fun onSwipeUp(touchCount : Int)
fun onLongClick()
fun usePageInfo() : Boolean
}
interface PagedTextGenerateInterface {
fun completePagination(pageList: ArrayList<CharSequence>)
}
class PagedTextLayout : ConstraintLayout , PagedTextGenerateInterface {
constructor(context: Context) : super(context) {initView(context)}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {initView(context)}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {initView(context)}
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {initView(context)}
var mainTextView : TextView? = null
var sencondTextView : TextView? = null
var demp : View? = null
// var hiddenTextView : PagedTextView? = null
var guideLine : Guideline? = null
var pageList = mutableListOf<CharSequence>()
var summaryText : String = ""
var text: String = ""
set(value) {
field = value
if (value.isNotEmpty()) {
// 액티비티가 준 한 페이지 분량의 텍스트를 곧바로 자식 텍스트뷰에 바인딩합니다.
mainTextView?.text = value
// 만약 듀얼 페이지 모드를 지원한다면 액티비티에서 2페이지 분량을
// 각각 나눠서 주입하는 것이 좋으므로, 여기서는 단순 텍스트 셋팅만 수행합니다.
if (isDualPage()) {
// 필요 시 듀얼 페이지 처리 로직을 액티비티 스펙에 맞게 확장할 수 있습니다.
// 현재는 단일 페이지 기반으로 작동하므로 비워두거나 서브 뷰를 비웁니다.
sencondTextView?.text = ""
}
} else {
mainTextView?.text = ""
sencondTextView?.text = ""
}
}
private fun cleanText(text: String): String {
return text
// 1. 전체 텍스트의 앞/뒤 공백 제거
.trim()
// 2. 중간에 포함된 '빈 줄' 제거
// (\n\s*)+\n : 줄바꿈(\n) 뒤에 공백(\s*)이 오고 다시 줄바꿈이 반복되는 패턴을 찾습니다.
// 이것을 단일 줄바꿈(\n)으로 교체하여 빈 라인을 없애고 문단만 나눕니다.
.replace(Regex("(\\n\\n\\s*)+\\n"), "\n")
}
suspend fun paginateAsync(text: CharSequence, width: Int, height: Int): List<CharSequence> = withContext(Dispatchers.Default) {
val resultPages = ArrayList<CharSequence>()
val paint = mainTextView?.paint ?: TextPaint()
val lineSpacingMult = mainTextView?.lineSpacingMultiplier ?: 1.0f
val lineSpacingAdd = mainTextView?.lineSpacingExtra ?: 1.0f
val letterSpacing = mainTextView?.letterSpacing ?: 1.0f
val includePad = false
Blog.LOGE("text ${text.length}, width $width, height $height")
// 1. 전체 텍스트에 대한 StaticLayout 생성 (API 버전에 따른 분기 처리 권장)
val layout = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StaticLayout.Builder.obtain(text, 0, text.length, paint, width)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setLineSpacing(lineSpacingAdd, lineSpacingMult)
.setIncludePad(includePad)
.build()
} else {
@Suppress("DEPRECATION")
StaticLayout(text, paint, width, Layout.Alignment.ALIGN_NORMAL, lineSpacingMult, lineSpacingAdd, includePad)
}
val totalLines = layout.lineCount
var startLine = 0
var startOffset = 0
// 2. 라인 정보를 순회하며 높이 계산
while (startLine < totalLines) {
// 현재 페이지의 시작 y 좌표
val pageTopY = layout.getLineTop(startLine)
// 현재 페이지가 끝날 수 있는 최대 y 좌표
val targetBottomY = pageTopY + height
// 이 페이지에 들어갈 수 있는 마지막 라인 찾기
var endLine = layout.getLineForVertical(targetBottomY)
// getLineForVertical은 정확한 좌표가 없으면 마지막 라인을 반환하므로 검증 필요
if (layout.getLineBottom(endLine) > targetBottomY) {
endLine--
}
// 한 줄도 못 들어가는 경우(폰트가 뷰보다 큰 경우 등) 방어 코드
if (endLine < startLine) endLine = startLine
// 페이지 범위의 텍스트 추출
// endLine의 끝 오프셋을 가져옴
val endOffset = layout.getLineEnd(endLine)
// 텍스트 자르기 (subSequence는 메모리 복사를 최소화함)
if (startOffset < endOffset) {
resultPages.add(text.subSequence(startOffset, endOffset))
}
// 다음 페이지 준비
startOffset = endOffset
startLine = endLine + 1
}
return@withContext resultPages
}
private val hanler = Handler()
var mPagedTextViewInterface : PagedTextViewInterface? = null
val touchTimeover = Runnable {
mPagedTextViewInterface?.onTimeoverTouch()
}
var currentPageTextView : TextView? = null
var currentChapter : TextView? = null
fun initView(context: Context) {
inflate(context, R.layout.layout_textviewer, this)
mainTextView = findViewById(R.id.first_view)
sencondTextView = findViewById(R.id.sencond_view)
currentPageTextView = findViewById(R.id.current_page)
currentChapter = findViewById(R.id.current_chapter)
if (mPagedTextViewInterface?.usePageInfo() ?: false) {
} else {
currentPageTextView?.text = ""
}
hanler.removeCallbacks(touchTimeover)
setOnLongClickListener { v ->
mPagedTextViewInterface?.onLongClick()
return@setOnLongClickListener true
}
setOnTouchListener(SimpleFingerGestures(omfgl = object : SimpleFingerGestures.OnFingerGestureListener{
override fun onSwipeUp(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
mPagedTextViewInterface?.onSwipeUp(fingers)
return true
}
override fun onSwipeDown(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
mPagedTextViewInterface?.onSwipeDown(fingers)
return true
}
override fun onSwipeLeft(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
mPagedTextViewInterface?.onSwipeLeft(fingers)
return true
}
override fun onSwipeRight(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
mPagedTextViewInterface?.onSwipeRight(fingers)
return true
}
override fun onPinch(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
Blog.LOGE("onPinch")
return false
}
override fun onUnpinch(
targetView: View,
fingers: Int,
gestureDuration: Long,
gestureDistance: Double
): Boolean {
// mPagedTextViewInterface?.onLongClick()
return true
}
override fun onDoubleTap(
targetView: View,
fingers: Int
): Boolean {
hanler.removeCallbacks(touchTimeover)
// mPagedTextViewInterface?.onLongClick()
hanler?.postDelayed(touchTimeover, 3000L)
return false
}
override fun onLongPress(
targetView: View,
fingers: Int
): Boolean {
Blog.LOGE("onLongPress")
return false
}
override fun onClick(
targetView: View,
fingers: Int
): Boolean {
Blog.LOGE("onClick")
mPagedTextViewInterface?.onTouch(TouchArea.Center)
return false
}
}))
}
fun layoutChange(needDualPage: Boolean) {
Blog.LOGD(log = "layoutChange>> ${this::class.java.name}")
if (needDualPage) {
sencondTextView?.visibility = VISIBLE
demp?.visibility = VISIBLE
} else {
sencondTextView?.visibility = GONE
demp?.visibility = GONE
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
// Blog.LOGD(log = "onLayout>> ${this::class.java.name} changed >> ${changed}")
if(changed) {
// forceUpdateUI()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
// Blog.LOGD(log = "onSizeChanged>> ${this::class.java.name}")
if (w != oldw || oldh != h) {
postDelayed(Runnable {
layoutChange(w > (h * 0.7f))
// Blog.LOGD(log = "onSizeChanged>> ${w} ${h} ${h * 0.7}")
},20)
}else {
}
}
var currentPage = 0
override fun completePagination(pageList: ArrayList<CharSequence>) {
if(text.length > 0 && pageList!= null && pageList.size == 0) {
} else {
this.pageList = pageList
setPageBy(0)
}
}
var defaultAlpha = 171
fun setColorStyle(colors : Array<String>) {
var bgColor = Color.parseColor(colors.get(1))
val newColorInt = (bgColor and 0x00FFFFFF) or (defaultAlpha shl 24)
setBackgroundColor(newColorInt)
mainTextView?.setBackgroundColor(newColorInt)
sencondTextView?.setBackgroundColor(newColorInt)
mainTextView?.setTextColor(Color.parseColor("#FFFFFF"))
sencondTextView?.setTextColor(Color.parseColor("#FFFFFF"))
}
fun setTextSize(fl: Float) {
mainTextView?.setTextSize(fl)
sencondTextView?.setTextSize(fl)
}
fun next(page : Int) {
}
fun isDualPage() : Boolean {
return sencondTextView?.visibility == VISIBLE
}
fun setPageBy(num : Int) {
if (pageList.size > 0) {
this@PagedTextLayout.currentPage = num
var realPage = if (isDualPage()) this@PagedTextLayout.currentPage * 2 else this@PagedTextLayout.currentPage
// Blog.LOGE("realPage = if(${pageList?.size} ?: 0 > ${realPage}) { realPage} else { ${(pageList?.size ?: 0) - 1}}")
realPage = if (pageList?.size ?: 0 > realPage) {
realPage
} else {
(pageList?.size ?: 0) - 1
}
if (mPagedTextViewInterface?.usePageInfo() ?: false) {
} else {
currentPageTextView?.text = "${realPage + 1}/${pageList?.size ?: 0 + 1}"
}
mainTextView?.text = pageList?.get(realPage) ?: "NONE"
// Blog.LOGE("pageList.get($realPage) ${pageList?.get(realPage)}")
if (isDualPage()) {
realPage = realPage.inc()
sencondTextView?.text = if (pageList?.size ?: 0 > realPage) {
pageList?.get(realPage)
} else {
"끝"
}
} else {
sencondTextView?.text = ""
}
}
}
fun size(): Int = (if(isDualPage()) {
Math.round(pageList.size * 0.5f)
}else {
pageList.size
})
fun getFastPageCount() = if(isDualPage()) 3 else 6
fun current(): Int = this@PagedTextLayout.currentPage
fun doNext(fast : Boolean = false) {
if (fast) {
setPageBy(if((this@PagedTextLayout.currentPage + getFastPageCount()) >= 0) {
this@PagedTextLayout.currentPage + getFastPageCount()
} else {size()})
} else {
setPageBy(this@PagedTextLayout.currentPage.inc())
}
}
fun doPrev(fast : Boolean = false) {
if (fast) {
setPageBy(if((this@PagedTextLayout.currentPage - getFastPageCount()) >= 0) {
this@PagedTextLayout.currentPage - getFastPageCount()
} else {0})
} else {
setPageBy(if(this@PagedTextLayout.currentPage > 0 ) this@PagedTextLayout.currentPage.dec() else 0)
}
}
override fun setPadding(left: Int, top: Int, right: Int, bottom: Int) {
mainTextView?.setPadding(left,top,right, bottom)
sencondTextView?.setPadding(left,top,right, bottom)
}
fun setTypeface(tf: Typeface?) {
mainTextView?.setTypeface(tf)
sencondTextView?.setTypeface(tf)
if (text.isNotEmpty()) {
invalidatePagination()
}
}
private fun invalidatePagination() {
val currentText = text
text = "" // 트리거를 위해 비움
text = currentText // 다시 할당하여 paginateAsync 실행
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun setLetterSpacing(letterSpacing: Float) {
mainTextView?.letterSpacing = letterSpacing.times(0.01f)
sencondTextView?.letterSpacing = letterSpacing.times(0.01f)
}
fun setLineSpacing(mult: Float) {
mainTextView?.setLineSpacing(1f, 1f.plus(mult.times(0.01f)))
sencondTextView?.setLineSpacing(1f, 1f.plus(mult.times(0.01f)))
}
}
@@ -1,810 +0,0 @@
package bums.lunatic.launcher.utils
import android.content.Context
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import bums.lunatic.launcher.BuildConfig
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
class GestureAnalyser @JvmOverloads constructor(
swipeSlopeIntolerance: Int = 2,
doubleTapMaxDelayMillis: Int = 500,
doubleTapMaxDownMillis: Int = 100
) {
var minValue = 100
private val initialX = DoubleArray(5)
private val initialY = DoubleArray(5)
private val finalX = DoubleArray(5)
private val finalY = DoubleArray(5)
private val currentX = DoubleArray(5)
private val currentY = DoubleArray(5)
private val delX = DoubleArray(5)
private val delY = DoubleArray(5)
private var numFingers = 0
private var initialT: Long = 0
private var finalT: Long = 0
private var currentT: Long = 0
private var prevInitialT: Long = 0
private var prevFinalT: Long = 0
private var swipeSlopeIntolerance = 2
private val doubleTapMaxDelayMillis: Long
private val doubleTapMaxDownMillis: Long
init {
this.swipeSlopeIntolerance = swipeSlopeIntolerance
this.doubleTapMaxDownMillis = doubleTapMaxDownMillis.toLong()
this.doubleTapMaxDelayMillis = doubleTapMaxDelayMillis.toLong()
}
fun trackGesture(ev: MotionEvent) {
val n = ev.pointerCount
for (i in 0 until n) {
initialX[i] = ev.getX(i).toDouble()
initialY[i] = ev.getY(i).toDouble()
}
numFingers = n
initialT = SystemClock.uptimeMillis()
}
fun untrackGesture() {
numFingers = 0
prevFinalT = SystemClock.uptimeMillis()
prevInitialT = initialT
}
fun getGesture(ev: MotionEvent): GestureType {
var averageDistance = 0.0
for (i in 0 until numFingers) {
finalX[i] = ev.getX(i).toDouble()
finalY[i] = ev.getY(i).toDouble()
delX[i] = finalX[i] - initialX[i]
delY[i] = finalY[i] - initialY[i]
averageDistance += sqrt(
(finalX[i] - initialX[i]).pow(2.0) + (finalY[i] - initialY[i]).pow(
2.0
)
)
}
averageDistance /= numFingers.toDouble()
finalT = SystemClock.uptimeMillis()
val gt = GestureType()
gt.gestureFlag = calcGesture()
gt.gestureDuration = finalT - initialT
gt.gestureDistance = averageDistance
return gt
}
fun getOngoingGesture(ev: MotionEvent): Int {
for (i in 0 until numFingers) {
currentX[i] = ev.getX(i).toDouble()
currentY[i] = ev.getY(i).toDouble()
delX[i] = finalX[i] - initialX[i]
delY[i] = finalY[i] - initialY[i]
}
currentT = SystemClock.uptimeMillis()
return calcGesture()
}
private fun calcGesture(): Int {
if (isDoubleTap) {
return DOUBLE_TAP_1
}
if (numFingers == 1) {
if ((-(delY[0])) > (swipeSlopeIntolerance * (abs(
delX[0]
))) && abs(delY[0]) > minValue
) {
return SWIPE_1_UP
}
if (((delY[0])) > (swipeSlopeIntolerance * (abs(
delX[0]
))) && abs(delY[0]) > minValue
) {
return SWIPE_1_DOWN
}
if ((-(delX[0])) > (swipeSlopeIntolerance * (abs(
delY[0]
))) && abs(delX[0]) > minValue
) {
return SWIPE_1_LEFT
}
if (((delX[0])) > (swipeSlopeIntolerance * (abs(
delY[0]
))) && abs(delX[0]) > minValue
) {
return SWIPE_1_RIGHT
}
// BLog.LOGE("initialT = ${initialT} , finalT = ${finalT} , result = ${finalT - initialT}")
if (finalT - initialT < 300) {
return CLICK_1
} else if(finalT - initialT > doubleTapMaxDelayMillis) {
return LONG_CLICK_1
}
}
if (numFingers == 2) {
if (((-delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
))) && ((-delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
))) && (abs(delY[0]) > minValue || abs(delY[1]) > minValue)
) {
return SWIPE_2_UP
}
if (((delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
))) && ((delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
))) && (abs(delY[0]) > minValue || abs(delY[1]) > minValue)
) {
return SWIPE_2_DOWN
}
if (((-delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
))) && ((-delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
))) && (abs(delX[0]) > minValue || abs(delX[1]) > minValue)
) {
return SWIPE_2_LEFT
}
if (((delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
))) && ((delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
))) && (abs(delX[0]) > minValue || abs(delX[1]) > minValue)
) {
return SWIPE_2_RIGHT
}
if (finalFingDist(0, 1) > 2 * (initialFingDist(0, 1))) {
return UNPINCH_2
}
if (finalFingDist(0, 1) < 0.5 * (initialFingDist(0, 1))) {
return PINCH_2
}
if (finalT - initialT < 300) {
return CLICK_2
} else if(finalT - initialT > doubleTapMaxDelayMillis) {
return LONG_CLICK_2
}
}
if (numFingers == 3) {
if (((-delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
)))
&& ((-delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
)))
&& ((-delY[2]) > (swipeSlopeIntolerance * abs(
delX[2]
))) && (abs(delY[0]) > minValue || abs(delY[1]) > minValue && abs(delY[2]) > minValue)
) {
return SWIPE_3_UP
}
if (((delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
)))
&& ((delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
)))
&& ((delY[2]) > (swipeSlopeIntolerance * abs(
delX[2]
))) && (abs(delY[0]) > minValue || abs(delY[1]) > minValue && abs(delY[2]) > minValue)
) {
return SWIPE_3_DOWN
}
if (((-delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
)))
&& ((-delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
)))
&& ((-delX[2]) > (swipeSlopeIntolerance * abs(
delY[2]
))) && (abs(delX[0]) > minValue || abs(delX[1]) > minValue && abs(delX[2]) > minValue)
) {
return SWIPE_3_LEFT
}
if (((delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
)))
&& ((delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
)))
&& ((delX[2]) > (swipeSlopeIntolerance * abs(
delY[2]
))) && (abs(delX[0]) > minValue || abs(delX[1]) > minValue && abs(delX[2]) > minValue)
) {
return SWIPE_3_RIGHT
}
if ((finalFingDist(0, 1) > 1.75 * (initialFingDist(0, 1)))
&& (finalFingDist(1, 2) > 1.75 * (initialFingDist(1, 2)))
&& (finalFingDist(2, 0) > 1.75 * (initialFingDist(2, 0)))
) {
return UNPINCH_3
}
if ((finalFingDist(0, 1) < 0.66 * (initialFingDist(0, 1)))
&& (finalFingDist(1, 2) < 0.66 * (initialFingDist(1, 2)))
&& (finalFingDist(2, 0) < 0.66 * (initialFingDist(2, 0)))
) {
return PINCH_3
}
if (finalT - initialT < 300) {
return CLICK_3
} else if(finalT - initialT > doubleTapMaxDelayMillis) {
return LONG_CLICK_3
}
}
if (numFingers == 4) {
if (((-delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
)))
&& ((-delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
)))
&& ((-delY[2]) > (swipeSlopeIntolerance * abs(
delX[2]
)))
&& ((-delY[3]) > (swipeSlopeIntolerance * abs(
delX[3]
)))
) {
return SWIPE_4_UP
}
if (((delY[0]) > (swipeSlopeIntolerance * abs(
delX[0]
)))
&& ((delY[1]) > (swipeSlopeIntolerance * abs(
delX[1]
)))
&& ((delY[2]) > (swipeSlopeIntolerance * abs(
delX[2]
)))
&& ((delY[3]) > (swipeSlopeIntolerance * abs(
delX[3]
)))
) {
return SWIPE_4_DOWN
}
if (((-delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
)))
&& ((-delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
)))
&& ((-delX[2]) > (swipeSlopeIntolerance * abs(
delY[2]
)))
&& ((-delX[3]) > (swipeSlopeIntolerance * abs(
delY[3]
)))
) {
return SWIPE_4_LEFT
}
if (((delX[0]) > (swipeSlopeIntolerance * abs(
delY[0]
)))
&& ((delX[1]) > (swipeSlopeIntolerance * abs(
delY[1]
)))
&& ((delX[2]) > (swipeSlopeIntolerance * abs(
delY[2]
)))
&& ((delX[3]) > (swipeSlopeIntolerance * abs(
delY[3]
)))
) {
return SWIPE_4_RIGHT
}
if ((finalFingDist(0, 1) > 1.5 * (initialFingDist(0, 1)))
&& (finalFingDist(1, 2) > 1.5 * (initialFingDist(1, 2)))
&& (finalFingDist(2, 3) > 1.5 * (initialFingDist(2, 3)))
&& (finalFingDist(3, 0) > 1.5 * (initialFingDist(3, 0)))
) {
return UNPINCH_4
}
if ((finalFingDist(0, 1) < 0.8 * (initialFingDist(0, 1)))
&& (finalFingDist(1, 2) < 0.8 * (initialFingDist(1, 2)))
&& (finalFingDist(2, 3) < 0.8 * (initialFingDist(2, 3)))
&& (finalFingDist(3, 0) < 0.8 * (initialFingDist(3, 0)))
) {
return PINCH_4
}
}
return 0
}
private fun initialFingDist(fingNum1: Int, fingNum2: Int): Double {
return sqrt(
(initialX[fingNum1] - initialX[fingNum2]).pow(2.0) + (initialY[fingNum1] - initialY[fingNum2]).pow(
2.0
)
)
}
private fun finalFingDist(fingNum1: Int, fingNum2: Int): Double {
return sqrt(
(finalX[fingNum1] - finalX[fingNum2]).pow(2.0) + (finalY[fingNum1] - finalY[fingNum2]).pow(
2.0
)
)
}
val isDoubleTap: Boolean
get() = if (initialT - prevFinalT < doubleTapMaxDelayMillis && finalT - initialT < doubleTapMaxDownMillis && prevFinalT - prevInitialT < doubleTapMaxDownMillis) {
true
} else {
false
}
inner class GestureType {
var gestureFlag: Int = 0
var gestureDuration: Long = 0
var gestureDistance: Double = 0.0
}
companion object {
const val DEBUG: Boolean = true
// Finished gestures flags
const val SWIPE_1_UP: Int = 11
const val SWIPE_1_DOWN: Int = 12
const val SWIPE_1_LEFT: Int = 13
const val SWIPE_1_RIGHT: Int = 14
const val SWIPE_2_UP: Int = 21
const val SWIPE_2_DOWN: Int = 22
const val SWIPE_2_LEFT: Int = 23
const val SWIPE_2_RIGHT: Int = 24
const val SWIPE_3_UP: Int = 31
const val SWIPE_3_DOWN: Int = 32
const val SWIPE_3_LEFT: Int = 33
const val SWIPE_3_RIGHT: Int = 34
const val SWIPE_4_UP: Int = 41
const val SWIPE_4_DOWN: Int = 42
const val SWIPE_4_LEFT: Int = 43
const val SWIPE_4_RIGHT: Int = 44
const val PINCH_2: Int = 25
const val UNPINCH_2: Int = 26
const val PINCH_3: Int = 35
const val UNPINCH_3: Int = 36
const val PINCH_4: Int = 45
const val UNPINCH_4: Int = 46
const val DOUBLE_TAP_1: Int = 107
const val CLICK_1 = 19001
const val CLICK_2 = 19002
const val CLICK_3 = 19003
const val LONG_CLICK_1 = 29001
const val LONG_CLICK_2 = 29002
const val LONG_CLICK_3 = 29003
//Ongoing gesture flags
const val SWIPING_1_UP: Int = 101
const val SWIPING_1_DOWN: Int = 102
const val SWIPING_1_LEFT: Int = 103
const val SWIPING_1_RIGHT: Int = 104
const val SWIPING_2_UP: Int = 201
const val SWIPING_2_DOWN: Int = 202
const val SWIPING_2_LEFT: Int = 203
const val SWIPING_2_RIGHT: Int = 204
const val PINCHING: Int = 205
const val UNPINCHING: Int = 206
private const val TAG = "GestureAnalyser"
}
}
class SimpleFingerGestures : OnTouchListener {
private var debug = BuildConfig.DEBUG
var consumeTouchEvents: Boolean = false
var screenUnit : Int = 100
protected var tracking: BooleanArray = booleanArrayOf(false, false, false, false, false)
private var ga: GestureAnalyser
private var onFingerGestureListener: OnFingerGestureListener? = null
var targetView : View? = null
var mContext : Context? = null
constructor(context : Context,targetView : View, onFingerGestureListener: OnFingerGestureListener) {
this.mContext = context
this.targetView = targetView
ga = GestureAnalyser()
this.mContext?.resources?.displayMetrics?.let {
screenUnit = (Math.min(it.widthPixels,it.heightPixels) * 0.3).toInt()
ga.minValue = Math.max(screenUnit, 100)
}
this.onFingerGestureListener = onFingerGestureListener
this.targetView?.setOnClickListener { onFingerGestureListener.onClick(it,1) }
this.targetView?.setOnLongClickListener { onFingerGestureListener.onLongPress(it,1) }
}
/**
* Constructor that creates an internal [in.championswimmer.sfg.lib.GestureAnalyser] object as well
*/
constructor() {
ga = GestureAnalyser()
}
constructor(
swipeSlopeIntolerance: Int,
doubleTapMaxDelayMillis: Int,
doubleTapMaxDownMillis: Int
) {
ga = GestureAnalyser(swipeSlopeIntolerance, doubleTapMaxDelayMillis, doubleTapMaxDownMillis)
}
fun setDebug(debug: Boolean) {
this.debug = debug
}
constructor(omfgl: OnFingerGestureListener?) {
ga = GestureAnalyser()
setOnFingerGestureListener(omfgl)
}
/**
* Register a callback to be invoked when multi-finger gestures take place
*
*
* <br></br>
*
*
* For the callbacks implemented via this, check the interface [in.championswimmer.sfg.lib.SimpleFingerGestures.OnFingerGestureListener]
*
*
* @param omfgl The callback that will run
*/
fun setOnFingerGestureListener(omfgl: OnFingerGestureListener?) {
onFingerGestureListener = omfgl
}
override fun onTouch(view: View, ev: MotionEvent): Boolean {
// if (debug) Log.d(TAG, "onTouch")
when (ev.action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_DOWN -> {
// if (debug) Log.d(TAG, "ACTION_DOWN")
startTracking(0)
ga.trackGesture(ev)
return consumeTouchEvents
}
MotionEvent.ACTION_UP -> {
// if (debug) Log.d(TAG, "ACTION_UP")
if (tracking[0]) {
doCallBack(view,ga.getGesture(ev))
}
stopTracking(0)
ga.untrackGesture()
return consumeTouchEvents
}
MotionEvent.ACTION_POINTER_DOWN -> {
// if (debug) Log.d(TAG, "ACTION_POINTER_DOWN" + " " + "num" + ev.pointerCount)
startTracking(ev.pointerCount - 1)
ga.trackGesture(ev)
return consumeTouchEvents
}
MotionEvent.ACTION_POINTER_UP -> {
// if (debug) Log.d(TAG, "ACTION_POINTER_UP" + " " + "num" + ev.pointerCount)
if (tracking[1]) {
doCallBack(view,ga.getGesture(ev))
}
stopTracking(ev.pointerCount - 1)
ga.untrackGesture()
return consumeTouchEvents
}
MotionEvent.ACTION_CANCEL -> {
// if (debug) Log.d(TAG, "ACTION_CANCEL")
return true
}
MotionEvent.ACTION_MOVE -> {
// if (debug) Log.d(TAG, "ACTION_MOVE")
return consumeTouchEvents
}
}
return consumeTouchEvents
}
private fun doCallBack(targetView : View, mGt: GestureAnalyser.GestureType) {
when (mGt.gestureFlag) {
GestureAnalyser.SWIPE_1_UP -> onFingerGestureListener!!.onSwipeUp(
targetView,
1,
mGt.gestureDuration,
mGt.gestureDistance
).apply { consumeTouchEvents = this }
GestureAnalyser.SWIPE_1_DOWN -> onFingerGestureListener!!.onSwipeDown(
targetView,
1,
mGt.gestureDuration,
mGt.gestureDistance
).apply { consumeTouchEvents = this }
GestureAnalyser.SWIPE_1_LEFT -> onFingerGestureListener!!.onSwipeLeft(
targetView,
1,
mGt.gestureDuration,
mGt.gestureDistance
).apply { consumeTouchEvents = this }
GestureAnalyser.SWIPE_1_RIGHT -> onFingerGestureListener!!.onSwipeRight(
targetView,
1,
mGt.gestureDuration,
mGt.gestureDistance
).apply { consumeTouchEvents = this }
GestureAnalyser.SWIPE_2_UP -> onFingerGestureListener!!.onSwipeUp(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_2_DOWN -> onFingerGestureListener!!.onSwipeDown(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_2_LEFT -> onFingerGestureListener!!.onSwipeLeft(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_2_RIGHT -> onFingerGestureListener!!.onSwipeRight(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.PINCH_2 -> onFingerGestureListener!!.onPinch(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.UNPINCH_2 -> onFingerGestureListener!!.onUnpinch(
targetView,
2,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_3_UP -> onFingerGestureListener!!.onSwipeUp(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_3_DOWN -> onFingerGestureListener!!.onSwipeDown(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_3_LEFT -> onFingerGestureListener!!.onSwipeLeft(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_3_RIGHT -> onFingerGestureListener!!.onSwipeRight(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.PINCH_3 -> onFingerGestureListener!!.onPinch(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.UNPINCH_3 -> onFingerGestureListener!!.onUnpinch(
targetView,
3,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_4_UP -> onFingerGestureListener!!.onSwipeUp(
targetView,
4,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_4_DOWN -> onFingerGestureListener!!.onSwipeDown(
targetView,
4,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_4_LEFT -> onFingerGestureListener!!.onSwipeLeft(
targetView,
4,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.SWIPE_4_RIGHT -> onFingerGestureListener!!.onSwipeRight(
targetView,
4,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.PINCH_4 -> onFingerGestureListener!!.onPinch(
targetView,
4,
mGt.gestureDuration,
mGt.gestureDistance
)
GestureAnalyser.UNPINCH_4 -> {
onFingerGestureListener!!.onUnpinch(targetView,4, mGt.gestureDuration, mGt.gestureDistance)
// onFingerGestureListener!!.onDoubleTap(1)
}
GestureAnalyser.CLICK_1 -> {
// BLog.LOGE("GestureAnalyser.CLICK_1")
onFingerGestureListener!!.onClick(targetView, 1).apply { consumeTouchEvents = this }
// onFingerGestureListener!!.onDoubleTap(1)
}
GestureAnalyser.CLICK_2 -> {
// BLog.LOGE("GestureAnalyser.CLICK_2")
onFingerGestureListener!!.onClick(targetView, 2).apply { consumeTouchEvents = this }
// onFingerGestureListener!!.onDoubleTap(1)
}
GestureAnalyser.CLICK_3 -> {
// BLog.LOGE("GestureAnalyser.CLICK_3")
onFingerGestureListener!!.onClick(targetView, 3).apply { consumeTouchEvents = this }
// onFingerGestureListener!!.onDoubleTap(1)
}
// GestureAnalyser.CLICK_2 -> {
// onFingerGestureListener!!.onUnpinch(targetView,4, mGt.gestureDuration, mGt.gestureDistance)
//// onFingerGestureListener!!.onDoubleTap(1)
// }
// GestureAnalyser.CLICK_3 -> {
// onFingerGestureListener!!.onUnpinch(targetView,4, mGt.gestureDuration, mGt.gestureDistance)
//// onFingerGestureListener!!.onDoubleTap(1)
// }
GestureAnalyser.LONG_CLICK_1 -> {
// BLog.LOGE("GestureAnalyser.LONG_CLICK_1")
onFingerGestureListener!!.onLongPress(targetView,1).apply { consumeTouchEvents = this }
}
GestureAnalyser.LONG_CLICK_2 -> {
// BLog.LOGE("GestureAnalyser.LONG_CLICK_2")
onFingerGestureListener!!.onLongPress(targetView,2).apply { consumeTouchEvents = this }
}
GestureAnalyser.LONG_CLICK_3 -> {
// BLog.LOGE("GestureAnalyser.LONG_CLICK_3")
onFingerGestureListener!!.onLongPress(targetView,3).apply { consumeTouchEvents = this }
}
GestureAnalyser.DOUBLE_TAP_1 -> onFingerGestureListener!!.onDoubleTap(targetView,1)
}
}
private fun startTracking(nthPointer: Int) {
for (i in 0..nthPointer) {
tracking[i] = true
}
}
private fun stopTracking(nthPointer: Int) {
for (i in nthPointer until tracking.size) {
tracking[i] = false
}
}
/**
* Interface definition for the callback to be invoked when 2-finger gestures are performed
*/
interface OnFingerGestureListener {
/**
* Called when user swipes **up** with two fingers
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onSwipeUp(targetView : View, fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
/**
* Called when user swipes **down** with two fingers
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onSwipeDown(targetView : View,fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
/**
* Called when user swipes **left** with two fingers
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onSwipeLeft(targetView : View,fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
/**
* Called when user swipes **right** with two fingers
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onSwipeRight(targetView : View,fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
/**
* Called when user **pinches** with two fingers (bring together)
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onPinch(targetView : View,fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
/**
* Called when user **un-pinches** with two fingers (take apart)
*
* @param fingers number of fingers involved in this gesture
* @param gestureDuration duration in milliSeconds
* @return
*/
fun onUnpinch(targetView : View,fingers: Int, gestureDuration: Long, gestureDistance: Double): Boolean
fun onDoubleTap(targetView : View,fingers: Int): Boolean
fun onLongPress(targetView : View, fingers: Int): Boolean
fun onClick(targetView : View, fingers: Int): Boolean
}
companion object {
// Will see if these need to be used. For now just returning duration in milliS
const val GESTURE_SPEED_SLOW: Long = 1500
const val GESTURE_SPEED_MEDIUM: Long = 1000
const val GESTURE_SPEED_FAST: Long = 500
private const val TAG = "SimpleFingerGestures"
}
}
-12
View File
@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>