content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.utils.extensions import android.content.Context import android.net.Uri import org.readium.r2.shared.extensions.tryOrNull import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.utils.ContentResolverUtil import java.io.File import java.util.* suspend fun Uri.copyToTempFile(context: Context, dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() val mediaType = MediaType.ofUri(this, context.contentResolver) val path = "$dir$filename.${mediaType?.fileExtension ?: "tmp"}" ContentResolverUtil.getContentInputStream(context, this, path) return@tryOrNull File(path) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Uri.kt
3734368706
/* Module: r2-testapp-kotlin * Developers: Quentin Gliosca * * Copyright (c) 2020. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.readium.r2.shared.extensions.extension import org.readium.r2.shared.extensions.tryOr import org.readium.r2.shared.extensions.tryOrNull import java.io.File import java.io.FileOutputStream import java.net.URL import java.util.* suspend fun URL.download(path: String): File? = tryOr(null) { val file = File(path) withContext(Dispatchers.IO) { openStream().use { input -> FileOutputStream(file).use { output -> input.copyTo(output) } } } file } suspend fun URL.copyToTempFile(dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() val path = "$dir$filename.$extension" download(path) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/URL.kt
837749763
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils.extensions import android.content.Context import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat /** * Extensions */ @ColorInt fun Context.color(@ColorRes id: Int): Int { return ContextCompat.getColor(this, id) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Context.kt
180714804
/* Module: r2-testapp-kotlin * Developers: Quentin Gliosca, Aferdita Muriqi, Clément Baumann * * Copyright (c) 2020. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.FileFilter import java.io.IOException suspend fun File.moveTo(target: File) = withContext(Dispatchers.IO) { if (!this@moveTo.renameTo(target)) throw IOException() } /** * As there are cases where [File.listFiles] returns null even though it is a directory, we return * an empty list instead. */ fun File.listFilesSafely(filter: FileFilter? = null): List<File> { val array: Array<File>? = if (filter == null) listFiles() else listFiles(filter) return array?.toList() ?: emptyList() }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/File.kt
2966336976
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.utils.extensions import android.graphics.Bitmap import android.util.Base64 import timber.log.Timber import java.io.ByteArrayOutputStream /** * Converts the receiver bitmap into a data URL ready to be used in HTML or CSS. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs */ fun Bitmap.toDataUrl(): String? = try { val stream = ByteArrayOutputStream() compress(Bitmap.CompressFormat.PNG, 100, stream) .also { success -> if (!success) throw Exception("Can't compress image to PNG") } val b64 = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT) "data:image/png;base64,$b64" } catch (e: Exception) { Timber.e(e) null }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Bitmap.kt
428728235
/* * Module: r2-testapp-kotlin * Developers: Mickaël Menu * * Copyright (c) 2020. Readium Foundation. All rights reserved. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils.extensions import org.readium.r2.shared.publication.Metadata val Metadata.authorName: String get() = authors.firstOrNull()?.name ?: ""
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Metadata.kt
3941181849
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.readium.r2.shared.extensions.tryOrNull import java.io.File import java.io.InputStream import java.util.* suspend fun InputStream.toFile(path: String) { withContext(Dispatchers.IO) { use { input -> File(path).outputStream().use { input.copyTo(it) } } } } suspend fun InputStream.copyToTempFile(dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() File(dir + filename) .also { toFile(it.path) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/InputStream.kt
1510309123
package org.readium.r2.testapp.utils.extensions import org.readium.r2.shared.publication.Link val Link.outlineTitle: String get() = title ?: href
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Link.kt
639819915
/* * Copyright 2020 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.utils import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import org.readium.r2.shared.extensions.tryOrNull /** * Creates a [FragmentFactory] for a single type of [Fragment] using the result of the given * [factory] closure. */ inline fun <reified T : Fragment> createFragmentFactory(crossinline factory: () -> T): FragmentFactory = object : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment { return when (className) { T::class.java.name -> factory() else -> super.instantiate(classLoader, className) } } } /** * A [FragmentFactory] which will iterate over a provided list of [factories] until finding one * instantiating successfully the requested [Fragment]. * * ``` * supportFragmentManager.fragmentFactory = CompositeFragmentFactory( * EpubNavigatorFragment.createFactory(publication, baseUrl, initialLocator, this), * PdfNavigatorFragment.createFactory(publication, initialLocator, this) * ) * ``` */ class CompositeFragmentFactory(private val factories: List<FragmentFactory>) : FragmentFactory() { constructor(vararg factories: FragmentFactory) : this(factories.toList()) override fun instantiate(classLoader: ClassLoader, className: String): Fragment { for (factory in factories) { tryOrNull { factory.instantiate(classLoader, className) } ?.let { return it } } return super.instantiate(classLoader, className) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/FragmentFactory.kt
4187447666
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ // See https://proandroiddev.com/android-singleliveevent-redux-with-kotlin-flow-b755c70bb055 package org.readium.r2.testapp.utils import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class EventChannel<T>(private val channel: Channel<T>, private val sendScope: CoroutineScope) { fun send(event: T) { sendScope.launch { channel.send(event) } } fun receive(lifecycleOwner: LifecycleOwner, callback: suspend (T) -> Unit) { val observer = FlowObserver(lifecycleOwner, channel.receiveAsFlow(), callback) lifecycleOwner.lifecycle.addObserver(observer) } } class FlowObserver<T> ( private val lifecycleOwner: LifecycleOwner, private val flow: Flow<T>, private val collector: suspend (T) -> Unit ) : LifecycleObserver { private var job: Job? = null @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { if (job == null) { job = lifecycleOwner.lifecycleScope.launch { flow.collect { collector(it) } } } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { job?.cancel() job = null } } inline fun <reified T> Flow<T>.observeWhenStarted( lifecycleOwner: LifecycleOwner, noinline collector: suspend (T) -> Unit ) { val observer = FlowObserver(lifecycleOwner, this, collector) lifecycleOwner.lifecycle.addObserver(observer) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/EventChannel.kt
4225782394
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.utils import android.app.Activity import android.view.View import android.view.WindowInsets import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowInsetsCompat // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Returns `true` if fullscreen or immersive mode is not set. */ private fun Activity.isSystemUiVisible(): Boolean { return this.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0 } // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Enable fullscreen or immersive mode. */ fun Activity.hideSystemUi() { this.window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN ) } // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Disable fullscreen or immersive mode. */ fun Activity.showSystemUi() { this.window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN ) } /** Toggle fullscreen or immersive mode. */ fun Activity.toggleSystemUi() { if (this.isSystemUiVisible()) { this.hideSystemUi() } else { this.showSystemUi() } } /** Set padding around view so that content doesn't overlap system UI */ fun View.padSystemUi(insets: WindowInsets, activity: Activity) = WindowInsetsCompat.toWindowInsetsCompat(insets, this) .getInsets(WindowInsetsCompat.Type.statusBars()).apply { setPadding( left, top + (activity as AppCompatActivity).supportActionBar!!.height, right, bottom ) } /** Clear padding around view */ fun View.clearPadding() = setPadding(0, 0, 0, 0)
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/SystemUiManagement.kt
3709392840
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.readium.r2.testapp.R class AboutFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_about, container, false) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/about/AboutFragment.kt
2347446097
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.search import androidx.paging.PagingSource import androidx.paging.PagingState import org.readium.r2.shared.Search import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.LocatorCollection import org.readium.r2.shared.publication.services.search.SearchIterator import org.readium.r2.shared.publication.services.search.SearchTry @OptIn(Search::class) class SearchPagingSource( private val listener: Listener? ) : PagingSource<Unit, Locator>() { interface Listener { suspend fun next(): SearchTry<LocatorCollection?> } override val keyReuseSupported: Boolean get() = true override fun getRefreshKey(state: PagingState<Unit, Locator>): Unit? = null override suspend fun load(params: LoadParams<Unit>): LoadResult<Unit, Locator> { listener ?: return LoadResult.Page(data = emptyList(), prevKey = null, nextKey = null) return try { val page = listener.next().getOrThrow() LoadResult.Page( data = page?.locators ?: emptyList(), prevKey = null, nextKey = if (page == null) null else Unit ) } catch (e: Exception) { LoadResult.Error(e) } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchPagingSource.kt
4044823683
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.search import android.os.Build import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import org.readium.r2.shared.publication.Locator import org.readium.r2.testapp.databinding.ItemRecycleSearchBinding import org.readium.r2.testapp.utils.singleClick /** * This class is an adapter for Search results' recycler view. */ class SearchResultAdapter(private var listener: Listener) : PagingDataAdapter<Locator, SearchResultAdapter.ViewHolder>(ItemCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemRecycleSearchBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val locator = getItem(position) ?: return val html = "${locator.text.before}<span style=\"background:yellow;\"><b>${locator.text.highlight}</b></span>${locator.text.after}" holder.textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT) } else { @Suppress("DEPRECATION") Html.fromHtml(html) } holder.itemView.singleClick { v -> listener.onItemClicked(v, locator) } } inner class ViewHolder(val binding: ItemRecycleSearchBinding) : RecyclerView.ViewHolder(binding.root) { val textView = binding.text } interface Listener { fun onItemClicked(v: View, locator: Locator) } private class ItemCallback : DiffUtil.ItemCallback<Locator>() { override fun areItemsTheSame(oldItem: Locator, newItem: Locator): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: Locator, newItem: Locator): Boolean = oldItem == newItem } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchResultAdapter.kt
1889688067
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.search import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.setFragmentResult import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.readium.r2.shared.publication.Locator import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentSearchBinding import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.SectionDecoration class SearchFragment : Fragment(R.layout.fragment_search) { private val viewModel: ReaderViewModel by activityViewModels() private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewScope = viewLifecycleOwner.lifecycleScope val searchAdapter = SearchResultAdapter(object : SearchResultAdapter.Listener { override fun onItemClicked(v: View, locator: Locator) { val result = Bundle().apply { putParcelable(SearchFragment::class.java.name, locator) } setFragmentResult(SearchFragment::class.java.name, result) } }) viewModel.searchResult .onEach { searchAdapter.submitData(it) } .launchIn(viewScope) viewModel.searchLocators .onEach { binding.noResultLabel.isVisible = it.isEmpty() } .launchIn(viewScope) viewModel.channel .receive(viewLifecycleOwner) { event -> when (event) { ReaderViewModel.Event.StartNewSearch -> binding.searchRecyclerView.scrollToPosition(0) else -> {} } } binding.searchRecyclerView.apply { adapter = searchAdapter layoutManager = LinearLayoutManager(activity) addItemDecoration(SectionDecoration(context, object : SectionDecoration.Listener { override fun isStartOfSection(itemPos: Int): Boolean = viewModel.searchLocators.value.run { when { itemPos == 0 -> true itemPos < 0 -> false itemPos >= size -> false else -> getOrNull(itemPos)?.title != getOrNull(itemPos-1)?.title } } override fun sectionTitle(itemPos: Int): String = viewModel.searchLocators.value.getOrNull(itemPos)?.title ?: "" })) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchFragment.kt
2443852028
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.readium.r2.shared.publication.Link import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.toLocator import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleNavigationBinding import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle /* * Fragment to show navigation links (Table of Contents, Page lists & Landmarks) */ class NavigationFragment : Fragment() { private lateinit var publication: Publication private lateinit var links: List<Link> private lateinit var navAdapter: NavigationAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication } links = requireNotNull(requireArguments().getParcelableArrayList(LINKS_ARG)) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navAdapter = NavigationAdapter(onLinkSelected = { link -> onLinkSelected(link) }) val flatLinks = mutableListOf<Pair<Int, Link>>() for (link in links) { val children = childrenOf(Pair(0, link)) // Append parent. flatLinks.add(Pair(0, link)) // Append children, and their children... recursive. flatLinks.addAll(children) } binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = navAdapter } navAdapter.submitList(flatLinks) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onLinkSelected(link: Link) { val locator = link.toLocator().let { // progression is mandatory in some contexts if (it.locations.fragments.isEmpty()) it.copyWithLocations(progression = 0.0) else it } setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(locator) ) } companion object { private const val LINKS_ARG = "links" fun newInstance(links: List<Link>) = NavigationFragment().apply { arguments = Bundle().apply { putParcelableArrayList(LINKS_ARG, if (links is ArrayList<Link>) links else ArrayList(links)) } } } } class NavigationAdapter(private val onLinkSelected: (Link) -> Unit) : ListAdapter<Pair<Int, Link>, NavigationAdapter.ViewHolder>(NavigationDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleNavigationBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleNavigationBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Pair<Int, Link>) { binding.navigationTextView.text = item.second.outlineTitle binding.indentation.layoutParams = LinearLayout.LayoutParams(item.first * 50, ViewGroup.LayoutParams.MATCH_PARENT) binding.root.setOnClickListener { onLinkSelected(item.second) } } } } private class NavigationDiff : DiffUtil.ItemCallback<Pair<Int, Link>>() { override fun areItemsTheSame( oldItem: Pair<Int, Link>, newItem: Pair<Int, Link> ): Boolean { return oldItem.first == newItem.first && oldItem.second == newItem.second } override fun areContentsTheSame( oldItem: Pair<Int, Link>, newItem: Pair<Int, Link> ): Boolean { return oldItem.first == newItem.first && oldItem.second == newItem.second } } fun childrenOf(parent: Pair<Int, Link>): MutableList<Pair<Int, Link>> { val indentation = parent.first + 1 val children = mutableListOf<Pair<Int, Link>>() for (link in parent.second.children) { children.add(Pair(indentation, link)) children.addAll(childrenOf(Pair(indentation, link))) } return children }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/NavigationFragment.kt
2027551679
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleBookmarkBinding import org.readium.r2.testapp.domain.model.Bookmark import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle import kotlin.math.roundToInt class BookmarksFragment : Fragment() { lateinit var publication: Publication lateinit var viewModel: ReaderViewModel private lateinit var bookmarkAdapter: BookmarkAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication viewModel = it } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bookmarkAdapter = BookmarkAdapter(publication, onBookmarkDeleteRequested = { bookmark -> viewModel.deleteBookmark(bookmark.id!!) }, onBookmarkSelectedRequested = { bookmark -> onBookmarkSelected(bookmark) }) binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = bookmarkAdapter } val comparator: Comparator<Bookmark> = compareBy({ it.resourceIndex }, { it.locator.locations.progression }) viewModel.getBookmarks().observe(viewLifecycleOwner, { val bookmarks = it.sortedWith(comparator).toMutableList() bookmarkAdapter.submitList(bookmarks) }) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onBookmarkSelected(bookmark: Bookmark) { setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(bookmark.locator) ) } } class BookmarkAdapter(private val publication: Publication, private val onBookmarkDeleteRequested: (Bookmark) -> Unit, private val onBookmarkSelectedRequested: (Bookmark) -> Unit) : ListAdapter<Bookmark, BookmarkAdapter.ViewHolder>(BookmarksDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleBookmarkBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleBookmarkBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(bookmark: Bookmark) { val title = getBookSpineItem(bookmark.resourceHref) ?: "*Title Missing*" binding.bookmarkChapter.text = title bookmark.locator.locations.progression?.let { progression -> val formattedProgression = "${(progression * 100).roundToInt()}% through resource" binding.bookmarkProgression.text = formattedProgression } val formattedDate = DateTime(bookmark.creation).toString(DateTimeFormat.shortDateTime()) binding.bookmarkTimestamp.text = formattedDate binding.overflow.setOnClickListener { val popupMenu = PopupMenu(binding.overflow.context, binding.overflow) popupMenu.menuInflater.inflate(R.menu.menu_bookmark, popupMenu.menu) popupMenu.show() popupMenu.setOnMenuItemClickListener { item -> if (item.itemId == R.id.delete) { onBookmarkDeleteRequested(bookmark) } false } } binding.root.setOnClickListener { onBookmarkSelectedRequested(bookmark) } } } private fun getBookSpineItem(href: String): String? { for (link in publication.tableOfContents) { if (link.href == href) { return link.outlineTitle } } for (link in publication.readingOrder) { if (link.href == href) { return link.outlineTitle } } return null } } private class BookmarksDiff : DiffUtil.ItemCallback<Bookmark>() { override fun areItemsTheSame( oldItem: Bookmark, newItem: Bookmark ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: Bookmark, newItem: Bookmark ): Boolean { return oldItem.bookId == newItem.bookId && oldItem.location == newItem.location } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/BookmarksFragment.kt
1685889148
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentResultListener import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.epub.landmarks import org.readium.r2.shared.publication.epub.pageList import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentOutlineBinding import org.readium.r2.testapp.reader.ReaderViewModel class OutlineFragment : Fragment() { lateinit var publication: Publication private var _binding: FragmentOutlineBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication } childFragmentManager.setFragmentResultListener( OutlineContract.REQUEST_KEY, this, FragmentResultListener { requestKey, bundle -> setFragmentResult(requestKey, bundle) } ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentOutlineBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val outlines: List<Outline> = when (publication.type) { Publication.TYPE.EPUB -> listOf(Outline.Contents, Outline.Bookmarks, Outline.Highlights, Outline.PageList, Outline.Landmarks) else -> listOf(Outline.Contents, Outline.Bookmarks) } binding.outlinePager.adapter = OutlineFragmentStateAdapter(this, publication, outlines) TabLayoutMediator(binding.outlineTabLayout, binding.outlinePager) { tab, idx -> tab.setText(outlines[idx].label) }.attach() } override fun onDestroyView() { _binding = null super.onDestroyView() } } private class OutlineFragmentStateAdapter(fragment: Fragment, val publication: Publication, val outlines: List<Outline>) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int { return outlines.size } override fun createFragment(position: Int): Fragment { return when (this.outlines[position]) { Outline.Bookmarks -> BookmarksFragment() Outline.Highlights -> HighlightsFragment() Outline.Landmarks -> createLandmarksFragment() Outline.Contents -> createContentsFragment() Outline.PageList -> createPageListFragment() } } private fun createContentsFragment() = NavigationFragment.newInstance(when { publication.tableOfContents.isNotEmpty() -> publication.tableOfContents publication.readingOrder.isNotEmpty() -> publication.readingOrder publication.images.isNotEmpty() -> publication.images else -> mutableListOf() }) private fun createPageListFragment() = NavigationFragment.newInstance(publication.pageList) private fun createLandmarksFragment() = NavigationFragment.newInstance(publication.landmarks) } private enum class Outline(val label: Int) { Contents(R.string.contents_tab_label), Bookmarks(R.string.bookmarks_tab_label), Highlights(R.string.highlights_tab_label), PageList(R.string.pagelist_tab_label), Landmarks(R.string.landmarks_tab_label) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/OutlineFragment.kt
2947580352
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleHighlightBinding import org.readium.r2.testapp.domain.model.Highlight import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle class HighlightsFragment : Fragment() { lateinit var publication: Publication lateinit var viewModel: ReaderViewModel private lateinit var highlightAdapter: HighlightAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication viewModel = it } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) highlightAdapter = HighlightAdapter(publication, onDeleteHighlightRequested = { highlight -> viewModel.deleteHighlight(highlight.id) }, onHighlightSelectedRequested = { highlight -> onHighlightSelected(highlight) }) binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = highlightAdapter } viewModel.highlights .onEach { highlightAdapter.submitList(it) } .launchIn(viewLifecycleOwner.lifecycleScope) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onHighlightSelected(highlight: Highlight) { setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(highlight.locator) ) } } class HighlightAdapter(private val publication: Publication, private val onDeleteHighlightRequested: (Highlight) -> Unit, private val onHighlightSelectedRequested: (Highlight) -> Unit) : ListAdapter<Highlight, HighlightAdapter.ViewHolder>(HighlightsDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleHighlightBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleHighlightBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(highlight: Highlight) { binding.highlightChapter.text = highlight.title binding.highlightText.text = highlight.locator.text.highlight binding.annotation.text = highlight.annotation val formattedDate = DateTime(highlight.creation).toString(DateTimeFormat.shortDateTime()) binding.highlightTimeStamp.text = formattedDate binding.highlightOverflow.setOnClickListener { val popupMenu = PopupMenu(binding.highlightOverflow.context, binding.highlightOverflow) popupMenu.menuInflater.inflate(R.menu.menu_bookmark, popupMenu.menu) popupMenu.show() popupMenu.setOnMenuItemClickListener { item -> if (item.itemId == R.id.delete) { onDeleteHighlightRequested(highlight) } false } } binding.root.setOnClickListener { onHighlightSelectedRequested(highlight) } } } } private class HighlightsDiff : DiffUtil.ItemCallback<Highlight>() { override fun areItemsTheSame(oldItem: Highlight, newItem: Highlight): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Highlight, newItem: Highlight): Boolean = oldItem == newItem }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/HighlightsFragment.kt
1485027986
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.outline import android.os.Bundle import org.readium.r2.shared.publication.Locator object OutlineContract { private const val DESTINATION_KEY = "locator" val REQUEST_KEY: String = OutlineContract::class.java.name data class Result(val destination: Locator) fun createResult(locator: Locator): Bundle = Bundle().apply { putParcelable(DESTINATION_KEY, locator) } fun parseResult(result: Bundle): Result { val destination = requireNotNull(result.getParcelable<Locator>(DESTINATION_KEY)) return Result(destination) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/OutlineContract.kt
237565236
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import androidx.lifecycle.LiveData import org.readium.r2.testapp.db.CatalogDao import org.readium.r2.testapp.domain.model.Catalog class CatalogRepository(private val catalogDao: CatalogDao) { suspend fun insertCatalog(catalog: Catalog): Long { return catalogDao.insertCatalog(catalog) } fun getCatalogsFromDatabase(): LiveData<List<Catalog>> = catalogDao.getCatalogModels() suspend fun deleteCatalog(id: Long) = catalogDao.deleteCatalog(id) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogRepository.kt
2883945364
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.google.android.material.snackbar.Snackbar import com.squareup.picasso.Picasso import org.readium.r2.shared.extensions.getPublicationOrNull import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.MainActivity import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentCatalogDetailBinding class CatalogDetailFragment : Fragment() { private var publication: Publication? = null private val catalogViewModel: CatalogViewModel by viewModels() private var _binding: FragmentCatalogDetailBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.fragment_catalog_detail, container, false ) catalogViewModel.detailChannel.receive(this) { handleEvent(it) } publication = arguments?.getPublicationOrNull() binding.publication = publication binding.viewModel = catalogViewModel return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (activity as MainActivity).supportActionBar?.title = publication?.metadata?.title Picasso.with(requireContext()).load(publication?.images?.first()?.href) .into(binding.catalogDetailCoverImage) binding.catalogDetailDownloadButton.setOnClickListener { publication?.let { it1 -> catalogViewModel.downloadPublication( it1 ) } } } private fun handleEvent(event: CatalogViewModel.Event.DetailEvent) { val message = when (event) { is CatalogViewModel.Event.DetailEvent.ImportPublicationSuccess -> getString(R.string.import_publication_success) is CatalogViewModel.Event.DetailEvent.ImportPublicationFailed -> getString(R.string.unable_add_pub_database) } Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogDetailFragment.kt
4259353571
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.databinding.ObservableBoolean import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import org.readium.r2.opds.OPDS1Parser import org.readium.r2.opds.OPDS2Parser import org.readium.r2.shared.opds.ParseData import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.shared.publication.services.cover import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.http.HttpRequest import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.R2App import org.readium.r2.testapp.bookshelf.BookRepository import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.opds.OPDSDownloader import org.readium.r2.testapp.utils.EventChannel import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL class CatalogViewModel(application: Application) : AndroidViewModel(application) { private val bookDao = BookDatabase.getDatabase(application).booksDao() private val bookRepository = BookRepository(bookDao) private var opdsDownloader = OPDSDownloader(application.applicationContext) private var r2Directory = R2App.R2DIRECTORY val detailChannel = EventChannel(Channel<Event.DetailEvent>(Channel.BUFFERED), viewModelScope) val eventChannel = EventChannel(Channel<Event.FeedEvent>(Channel.BUFFERED), viewModelScope) val parseData = MutableLiveData<ParseData>() val showProgressBar = ObservableBoolean() fun parseCatalog(catalog: Catalog) = viewModelScope.launch { var parseRequest: Try<ParseData, Exception>? = null catalog.href.let { val request = HttpRequest(it) try { parseRequest = if (catalog.type == 1) { OPDS1Parser.parseRequest(request) } else { OPDS2Parser.parseRequest(request) } } catch (e: MalformedURLException) { eventChannel.send(Event.FeedEvent.CatalogParseFailed) } } parseRequest?.onSuccess { parseData.postValue(it) } parseRequest?.onFailure { Timber.e(it) eventChannel.send(Event.FeedEvent.CatalogParseFailed) } } fun downloadPublication(publication: Publication) = viewModelScope.launch { showProgressBar.set(true) val downloadUrl = getDownloadURL(publication) val publicationUrl = opdsDownloader.publicationUrl(downloadUrl.toString()) publicationUrl.onSuccess { val id = addPublicationToDatabase(it.first, MediaType.EPUB, publication) if (id != -1L) { detailChannel.send(Event.DetailEvent.ImportPublicationSuccess) } else { detailChannel.send(Event.DetailEvent.ImportPublicationFailed) } } .onFailure { detailChannel.send(Event.DetailEvent.ImportPublicationFailed) } showProgressBar.set(false) } private fun getDownloadURL(publication: Publication): URL? = publication.links .firstOrNull { it.mediaType.isPublication } ?.let { URL(it.href) } private suspend fun addPublicationToDatabase( href: String, mediaType: MediaType, publication: Publication ): Long { val id = bookRepository.insertBook(href, mediaType, publication) storeCoverImage(publication, id.toString()) return id } private fun storeCoverImage(publication: Publication, imageName: String) = viewModelScope.launch(Dispatchers.IO) { // TODO Figure out where to store these cover images val coverImageDir = File("${r2Directory}covers/") if (!coverImageDir.exists()) { coverImageDir.mkdirs() } val coverImageFile = File("${r2Directory}covers/${imageName}.png") val bitmap: Bitmap? = publication.cover() ?: getBitmapFromURL(publication.images.first().href) val resized = bitmap?.let { Bitmap.createScaledBitmap(it, 120, 200, true) } val fos = FileOutputStream(coverImageFile) resized?.compress(Bitmap.CompressFormat.PNG, 80, fos) fos.flush() fos.close() } private fun getBitmapFromURL(src: String): Bitmap? { return try { val url = URL(src) val connection = url.openConnection() as HttpURLConnection connection.doInput = true connection.connect() val input = connection.inputStream BitmapFactory.decodeStream(input) } catch (e: IOException) { e.printStackTrace() null } } sealed class Event { sealed class FeedEvent : Event() { object CatalogParseFailed : FeedEvent() } sealed class DetailEvent : Event() { object ImportPublicationSuccess : DetailEvent() object ImportPublicationFailed : DetailEvent() } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogViewModel.kt
3376533546
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.os.Bundle import android.view.* import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.os.bundleOf import androidx.core.view.setPadding import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import org.readium.r2.shared.opds.Facet import org.readium.r2.testapp.MainActivity import org.readium.r2.testapp.R import org.readium.r2.testapp.bookshelf.BookshelfFragment import org.readium.r2.testapp.catalogs.CatalogFeedListAdapter.Companion.CATALOGFEED import org.readium.r2.testapp.databinding.FragmentCatalogBinding import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.opds.GridAutoFitLayoutManager class CatalogFragment : Fragment() { private val catalogViewModel: CatalogViewModel by viewModels() private lateinit var catalogListAdapter: CatalogListAdapter private lateinit var catalog: Catalog private var showFacetMenu = false private lateinit var facets: MutableList<Facet> private var _binding: FragmentCatalogBinding? = null private val binding get() = _binding!! // FIXME the entire way this fragment is built feels like a hack. Need a cleaner UI override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { catalogViewModel.eventChannel.receive(this) { handleEvent(it) } catalog = arguments?.get(CATALOGFEED) as Catalog _binding = FragmentCatalogBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) catalogListAdapter = CatalogListAdapter() setHasOptionsMenu(true) binding.catalogDetailList.apply { layoutManager = GridAutoFitLayoutManager(requireContext(), 120) adapter = catalogListAdapter addItemDecoration( BookshelfFragment.VerticalSpaceItemDecoration( 10 ) ) } (activity as MainActivity).supportActionBar?.title = catalog.title // TODO this feels hacky, I don't want to parse the file if it has not changed if (catalogViewModel.parseData.value == null) { binding.catalogProgressBar.visibility = View.VISIBLE catalogViewModel.parseCatalog(catalog) } catalogViewModel.parseData.observe(viewLifecycleOwner, { result -> facets = result.feed?.facets ?: mutableListOf() if (facets.size > 0) { showFacetMenu = true } requireActivity().invalidateOptionsMenu() result.feed!!.navigation.forEachIndexed { index, navigation -> val button = Button(requireContext()) button.apply { layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) text = navigation.title setOnClickListener { val catalog1 = Catalog( href = navigation.href, title = navigation.title!!, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } } binding.catalogLinearLayout.addView(button, index) } if (result.feed!!.publications.isNotEmpty()) { catalogListAdapter.submitList(result.feed!!.publications) } for (group in result.feed!!.groups) { if (group.publications.isNotEmpty()) { val linearLayout = LinearLayout(requireContext()).apply { orientation = LinearLayout.HORIZONTAL setPadding(10) layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) weightSum = 2f addView(TextView(requireContext()).apply { text = group.title layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) }) if (group.links.size > 0) { addView(TextView(requireContext()).apply { text = getString(R.string.catalog_list_more) gravity = Gravity.END layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) setOnClickListener { val catalog1 = Catalog( href = group.links.first().href, title = group.title, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } }) } } val publicationRecyclerView = RecyclerView(requireContext()).apply { layoutManager = LinearLayoutManager(requireContext()) (layoutManager as LinearLayoutManager).orientation = LinearLayoutManager.HORIZONTAL adapter = CatalogListAdapter().apply { submitList(group.publications) } } binding.catalogLinearLayout.addView(linearLayout) binding.catalogLinearLayout.addView(publicationRecyclerView) } if (group.navigation.isNotEmpty()) { for (navigation in group.navigation) { val button = Button(requireContext()) button.apply { layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) text = navigation.title setOnClickListener { val catalog1 = Catalog( href = navigation.href, title = navigation.title!!, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } } binding.catalogLinearLayout.addView(button) } } } binding.catalogProgressBar.visibility = View.GONE }) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun handleEvent(event: CatalogViewModel.Event.FeedEvent) { val message = when (event) { is CatalogViewModel.Event.FeedEvent.CatalogParseFailed -> getString(R.string.failed_parsing_catalog) } binding.catalogProgressBar.visibility = View.GONE Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() if (showFacetMenu) { facets.let { for (i in facets.indices) { val submenu = menu.addSubMenu(facets[i].title) for (link in facets[i].links) { val item = submenu.add(link.title) item.setOnMenuItemClickListener { val catalog1 = Catalog( title = link.title!!, href = link.href, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(requireView()) .navigate(R.id.action_navigation_catalog_self, bundle) true } } } } } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFragment.kt
3621607906
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.navigation.Navigation import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.ItemRecycleCatalogListBinding import org.readium.r2.testapp.domain.model.Catalog class CatalogFeedListAdapter(private val onLongClick: (Catalog) -> Unit) : ListAdapter<Catalog, CatalogFeedListAdapter.ViewHolder>(CatalogListDiff()) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_recycle_catalog_list, parent, false ) ) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val catalog = getItem(position) viewHolder.bind(catalog) } inner class ViewHolder(private val binding: ItemRecycleCatalogListBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(catalog: Catalog) { binding.catalog = catalog binding.catalogListButton.setOnClickListener { val bundle = bundleOf(CATALOGFEED to catalog) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_list_to_navigation_catalog, bundle) } binding.catalogListButton.setOnLongClickListener { onLongClick(catalog) true } } } companion object { const val CATALOGFEED = "catalogFeed" } private class CatalogListDiff : DiffUtil.ItemCallback<Catalog>() { override fun areItemsTheSame( oldItem: Catalog, newItem: Catalog ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: Catalog, newItem: Catalog ): Boolean { return oldItem.title == newItem.title && oldItem.href == newItem.href && oldItem.type == newItem.type } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListAdapter.kt
2892746881
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.content.Context import android.graphics.Rect import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.URLUtil import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentCatalogFeedListBinding import org.readium.r2.testapp.domain.model.Catalog class CatalogFeedListFragment : Fragment() { private val catalogFeedListViewModel: CatalogFeedListViewModel by viewModels() private lateinit var catalogsAdapter: CatalogFeedListAdapter private var _binding: FragmentCatalogFeedListBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { catalogFeedListViewModel.eventChannel.receive(this) { handleEvent(it) } _binding = FragmentCatalogFeedListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val preferences = requireContext().getSharedPreferences("org.readium.r2.testapp", Context.MODE_PRIVATE) catalogsAdapter = CatalogFeedListAdapter(onLongClick = { catalog -> onLongClick(catalog) }) binding.catalogFeedList.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = catalogsAdapter addItemDecoration( VerticalSpaceItemDecoration( 10 ) ) } catalogFeedListViewModel.catalogs.observe(viewLifecycleOwner, { catalogsAdapter.submitList(it) }) val version = 2 val VERSION_KEY = "OPDS_CATALOG_VERSION" if (preferences.getInt(VERSION_KEY, 0) < version) { preferences.edit().putInt(VERSION_KEY, version).apply() val oPDS2Catalog = Catalog( title = "OPDS 2.0 Test Catalog", href = "https://test.opds.io/2.0/home.json", type = 2 ) val oTBCatalog = Catalog( title = "Open Textbooks Catalog", href = "http://open.minitex.org/textbooks/", type = 1 ) val sEBCatalog = Catalog( title = "Standard eBooks Catalog", href = "https://standardebooks.org/opds/all", type = 1 ) catalogFeedListViewModel.insertCatalog(oPDS2Catalog) catalogFeedListViewModel.insertCatalog(oTBCatalog) catalogFeedListViewModel.insertCatalog(sEBCatalog) } binding.catalogFeedAddCatalogFab.setOnClickListener { val alertDialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.add_catalog)) .setView(R.layout.add_catalog_dialog) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.save), null) .show() alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val title = alertDialog.findViewById<EditText>(R.id.catalogTitle) val url = alertDialog.findViewById<EditText>(R.id.catalogUrl) if (TextUtils.isEmpty(title?.text)) { title?.error = getString(R.string.invalid_title) } else if (TextUtils.isEmpty(url?.text)) { url?.error = getString(R.string.invalid_url) } else if (!URLUtil.isValidUrl(url?.text.toString())) { url?.error = getString(R.string.invalid_url) } else { catalogFeedListViewModel.parseCatalog( url?.text.toString(), title?.text.toString() ) alertDialog.dismiss() } } } } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun handleEvent(event: CatalogFeedListViewModel.Event) { val message = when (event) { is CatalogFeedListViewModel.Event.FeedListEvent.CatalogParseFailed -> getString(R.string.catalog_parse_error) } Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } private fun deleteCatalogModel(catalogModelId: Long) { catalogFeedListViewModel.deleteCatalog(catalogModelId) } private fun onLongClick(catalog: Catalog) { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.confirm_delete_catalog_title)) .setMessage(getString(R.string.confirm_delete_catalog_text)) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.delete)) { dialog, _ -> catalog.id?.let { deleteCatalogModel(it) } dialog.dismiss() } .show() } class VerticalSpaceItemDecoration(private val verticalSpaceHeight: Int) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.bottom = verticalSpaceHeight } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListFragment.kt
2571393462
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import org.json.JSONObject import org.readium.r2.opds.OPDS1Parser import org.readium.r2.opds.OPDS2Parser import org.readium.r2.shared.opds.ParseData import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.http.DefaultHttpClient import org.readium.r2.shared.util.http.HttpRequest import org.readium.r2.shared.util.http.fetchWithDecoder import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.utils.EventChannel import java.net.URL class CatalogFeedListViewModel(application: Application) : AndroidViewModel(application) { private val catalogDao = BookDatabase.getDatabase(application).catalogDao() private val repository = CatalogRepository(catalogDao) val eventChannel = EventChannel(Channel<Event>(Channel.BUFFERED), viewModelScope) val catalogs = repository.getCatalogsFromDatabase() fun insertCatalog(catalog: Catalog) = viewModelScope.launch { repository.insertCatalog(catalog) } fun deleteCatalog(id: Long) = viewModelScope.launch { repository.deleteCatalog(id) } fun parseCatalog(url: String, title: String) = viewModelScope.launch { val parseData = parseURL(URL(url)) parseData.onSuccess { data -> val catalog = Catalog( title = title, href = url, type = data.type ) insertCatalog(catalog) } parseData.onFailure { eventChannel.send(Event.FeedListEvent.CatalogParseFailed) } } private suspend fun parseURL(url: URL): Try<ParseData, Exception> { return DefaultHttpClient().fetchWithDecoder(HttpRequest(url.toString())) { val result = it.body if (isJson(result)) { OPDS2Parser.parse(result, url) } else { OPDS1Parser.parse(result, url) } } } private fun isJson(byteArray: ByteArray): Boolean { return try { JSONObject(String(byteArray)) true } catch (e: Exception) { false } } sealed class Event { sealed class FeedListEvent : Event() { object CatalogParseFailed : FeedListEvent() } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListViewModel.kt
2135652928
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.catalogs import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.navigation.Navigation import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso import org.readium.r2.shared.extensions.putPublication import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.ItemRecycleCatalogBinding class CatalogListAdapter : ListAdapter<Publication, CatalogListAdapter.ViewHolder>(PublicationListDiff()) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_recycle_catalog, parent, false ) ) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val publication = getItem(position) viewHolder.bind(publication) } inner class ViewHolder(private val binding: ItemRecycleCatalogBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(publication: Publication) { binding.catalogListTitleText.text = publication.metadata.title publication.linkWithRel("http://opds-spec.org/image/thumbnail")?.let { link -> Picasso.with(binding.catalogListCoverImage.context).load(link.href) .into(binding.catalogListCoverImage) } ?: run { if (publication.images.isNotEmpty()) { Picasso.with(binding.catalogListCoverImage.context) .load(publication.images.first().href).into(binding.catalogListCoverImage) } } binding.root.setOnClickListener { val bundle = Bundle().apply { putPublication(publication) } Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_to_navigation_catalog_detail, bundle) } } } private class PublicationListDiff : DiffUtil.ItemCallback<Publication>() { override fun areItemsTheSame( oldItem: Publication, newItem: Publication ): Boolean { return oldItem.metadata.identifier == newItem.metadata.identifier } override fun areContentsTheSame( oldItem: Publication, newItem: Publication ): Boolean { return oldItem.jsonManifest == newItem.jsonManifest } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogListAdapter.kt
1358629104
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.tts import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.TextViewCompat import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.indexOfFirstWithHref import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentScreenReaderBinding import org.readium.r2.testapp.reader.ReaderViewModel class ScreenReaderFragment : Fragment(), ScreenReaderEngine.Listener { private lateinit var preferences: SharedPreferences private lateinit var publication: Publication private lateinit var screenReader: ScreenReaderEngine private var _binding: FragmentScreenReaderBinding? = null private val binding get() = _binding!! // A reference to the listener must be kept in order to prevent garbage collection // See https://developer.android.com/reference/android/content/SharedPreferences#registerOnSharedPreferenceChangeListener(android.content.SharedPreferences.OnSharedPreferenceChangeListener) private val preferencesListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "reader_TTS_speed") { updateScreenReaderSpeed(restart = true) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val activity = requireActivity() preferences = activity.getSharedPreferences("org.readium.r2.settings", Context.MODE_PRIVATE) ViewModelProvider(activity).get(ReaderViewModel::class.java).let { publication = it.publication } screenReader = ScreenReaderEngine(activity, publication) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentScreenReaderBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) screenReader.addListener(this) binding.titleView.text = publication.metadata.title binding.playPause.setOnClickListener { if (screenReader.isPaused) { screenReader.resumeReading() } else { screenReader.pauseReading() } } binding.fastForward.setOnClickListener { if (!screenReader.nextSentence()) { binding.nextChapter.callOnClick() } } binding.nextChapter.setOnClickListener { screenReader.nextResource() } binding.fastBack.setOnClickListener { if (!screenReader.previousSentence()) { binding.prevChapter.callOnClick() } } binding.prevChapter.setOnClickListener { screenReader.previousResource() } updateScreenReaderSpeed(restart = false) preferences.registerOnSharedPreferenceChangeListener(preferencesListener) val initialLocator = ScreenReaderContract.parseArguments(requireArguments()).locator val resourceIndex = requireNotNull(publication.readingOrder.indexOfFirstWithHref(initialLocator.href)) screenReader.goTo(resourceIndex) } override fun onPlayStateChanged(playing: Boolean) { if (playing) { binding.playPause.setImageResource(R.drawable.ic_baseline_pause_24) } else { binding.playPause.setImageResource(R.drawable.ic_baseline_play_arrow_24) } } override fun onEndReached() { Toast.makeText(requireActivity().applicationContext, "No further chapter contains text to read", Toast.LENGTH_LONG).show() } override fun onPlayTextChanged(text: String) { binding.ttsTextView.text = text TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(binding.ttsTextView, 1, 30, 1, TypedValue.COMPLEX_UNIT_DIP) } override fun onDestroyView() { screenReader.removeListener(this) _binding = null super.onDestroyView() } override fun onDestroy() { super.onDestroy() try { screenReader.shutdown() } catch (e: Exception) { } } override fun onPause() { super.onPause() screenReader.pauseReading() } override fun onStop() { super.onStop() screenReader.stopReading() val result = ScreenReaderContract.createResult(screenReader.currentLocator) setFragmentResult(ScreenReaderContract.REQUEST_KEY, result) } private fun updateScreenReaderSpeed(restart: Boolean) { // Get user settings speed when opening the screen reader. Get a neutral percentage (corresponding to // the normal speech speed) if no user settings exist. val speed = preferences.getInt( "reader_TTS_speed", (2.75 * 3.toDouble() / 11.toDouble() * 100).toInt() ) // Convert percentage to a float value between 0.25 and 3.0 val ttsRate = 0.25.toFloat() + (speed.toFloat() / 100.toFloat()) * 2.75.toFloat() screenReader.setSpeechSpeed(ttsRate, restart) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderFragment.kt
52956030
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.tts import android.content.Context import android.os.Handler import android.os.Looper import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import android.widget.Toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.jsoup.Jsoup import org.jsoup.select.Elements import org.readium.r2.shared.publication.Link import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.toLocator import org.readium.r2.testapp.BuildConfig.DEBUG import timber.log.Timber import java.io.IOException import java.util.* /** * ScreenReader * * Basic screen reader engine that uses Android's TextToSpeech */ class ScreenReaderEngine(val context: Context, val publication: Publication) { interface Listener { fun onPlayTextChanged(text: String) fun onPlayStateChanged(playing: Boolean) fun onEndReached() } private var listeners: MutableList<Listener> = mutableListOf() fun addListener(listener: Listener) { listeners.add(listener) } fun removeListener(listener: Listener) { listeners.remove(listener) } // To avoid lifecycle issues, all `notify` functions will be called on the UI thread and // dispatch events to every listener attached at this time. private fun notifyPlayTextChanged(text: String) { for (listener in listeners) { listener.onPlayTextChanged(text) } } private fun notifyPlayStateChanged(playing: Boolean) { for (listener in listeners) { listener.onPlayStateChanged(playing) } } private fun notifyEndReached() { for (listener in listeners) { listener.onEndReached() } } private enum class PlaySentence(val value: Int) { SAME(0), NEXT(1), PREV(-1) } var isPaused: Boolean = false private var initialized = false private var pendingStartReadingResource = false private val items = publication.readingOrder private var resourceIndex = 0 set(value) { when { value >= items.size -> { field = items.size - 1 currentUtterance = 0 } value < 0 -> { field = 0 currentUtterance = 0 } else -> { field = value } } } private var utterances = mutableListOf<String>() var currentUtterance: Int = 0 get() = if (field != -1) field else 0 set(value) { field = when { value == -1 -> 0 value == 0 -> 0 value > utterances.size - 1 -> utterances.size - 1 value < 0 -> 0 else -> value } if (DEBUG) Timber.d("Current utterance index: $currentUtterance") } private var textToSpeech: TextToSpeech = TextToSpeech(context, TextToSpeech.OnInitListener { status -> initialized = (status != TextToSpeech.ERROR) onPrepared() }) private fun onPrepared() { if (DEBUG) Timber.d("textToSpeech initialization status: $initialized") if (!initialized) { Toast.makeText( context.applicationContext, "There was an error with the TTS initialization", Toast.LENGTH_LONG ).show() } if (pendingStartReadingResource) { pendingStartReadingResource = false startReadingResource() } } val currentLocator: Locator get() = publication.readingOrder[resourceIndex].toLocator() /** * - Update the resource index. * - Mark [textToSpeech] as reading. * - Stop [textToSpeech] if it is reading. * - Start [textToSpeech] setup. * * @param resource: Int - The index of the resource we want read. */ fun goTo(resource: Int) { resourceIndex = resource isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } fun previousResource() { resourceIndex-- isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } fun nextResource() { resourceIndex++ isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } private fun setTTSLanguage() { val language = textToSpeech.setLanguage(Locale(publication.metadata.languages.firstOrNull() ?: "")) if (language == TextToSpeech.LANG_MISSING_DATA || language == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText( context.applicationContext, "There was an error with the TTS language, switching " + "to EN-US", Toast.LENGTH_LONG ).show() textToSpeech.language = Locale.US } } /** * Inner function that sets the utterances variable. * * @return: Boolean - Whether utterances was able to be filled or not. */ private suspend fun setUtterances(): Boolean { //Load resource as sentences utterances = mutableListOf() splitResourceAndAddToUtterances(items[resourceIndex]) return utterances.size != 0 } /** * Call the core setup functions to set the language, the utterances and the callbacks. * * @return: Boolean - Whether executing the function was successful or not. */ private suspend fun configure(): Boolean { setTTSLanguage() return withContext(Dispatchers.Default) { setUtterances() } && flushUtterancesQueue() && setTTSCallbacks() } /** * Set the TTS callbacks. * * @return: Boolean - Whether setting the callbacks was successful or not. */ private fun setTTSCallbacks(): Boolean { val res = textToSpeech.setOnUtteranceProgressListener(object : UtteranceProgressListener() { /** * Called when an utterance "starts" as perceived by the caller. This will * be soon before audio is played back in the case of a [TextToSpeech.speak] * or before the first bytes of a file are written to the file system in the case * of [TextToSpeech.synthesizeToFile]. * * @param utteranceId The utterance ID of the utterance. */ override fun onStart(utteranceId: String?) { Handler(Looper.getMainLooper()).post { currentUtterance = utteranceId!!.toInt() notifyPlayTextChanged(utterances[currentUtterance]) } } /** * Called when an utterance has successfully completed processing. * All audio will have been played back by this point for audible output, and all * output will have been written to disk for file synthesis requests. * * This request is guaranteed to be called after [.onStart]. * * @param utteranceId The utterance ID of the utterance. */ override fun onDone(utteranceId: String?) { Handler(Looper.getMainLooper()).post { if (utteranceId.equals((utterances.size - 1).toString())) { if (items.size - 1 == resourceIndex) { stopReading() Handler(Looper.getMainLooper()).post { notifyPlayStateChanged(false) } } else { nextResource() } } } } /** * Called when an error has occurred during processing. This can be called * at any point in the synthesis process. Note that there might be calls * to [.onStart] for specified utteranceId but there will never * be a call to both [.onDone] and [.onError] for * the same utterance. * * @param utteranceId The utterance ID of the utterance. */ override fun onError(utteranceId: String?) { if (DEBUG) Timber .e("Error saying: ${utterances[utteranceId!!.toInt()]}") } }) if (res == TextToSpeech.ERROR) { if (DEBUG) Timber.e("TTS failed to set callbacks") return false } return true } /** * Stop reading and destroy the [textToSpeech]. */ fun shutdown() { initialized = false stopReading() textToSpeech.shutdown() } /** * Set [isPaused] to false and add the [utterances] to the [textToSpeech] queue if [configure] worked * successfully */ private fun startReadingResource() { if (!initialized) { pendingStartReadingResource = true return } isPaused = false notifyPlayStateChanged(true) if (runBlocking { configure() }) { if (currentUtterance >= utterances.size) { if (DEBUG) Timber .e("Invalid currentUtterance value: $currentUtterance . Expected less than $utterances.size") currentUtterance = 0 } val index = currentUtterance for (i in index until utterances.size) { addToUtterancesQueue(utterances[i], i) } } else if ((items.size - 1) > resourceIndex) { nextResource() } else { Handler(Looper.getMainLooper()).post { notifyPlayStateChanged(false) notifyEndReached() } } } /** * Stop text to speech and set [isPaused] to true so that subsequent playing of TTS will not automatically * start playing. */ fun pauseReading() { isPaused = true textToSpeech.stop() notifyPlayStateChanged(false) } /** * Stop text to speech and set [isPaused] to false so that subsequent playing of TTS will automatically * start playing. */ fun stopReading() { isPaused = false textToSpeech.stop() notifyPlayStateChanged(false) } /** * Allow to resume playing from the start of the current track while still being in a completely black box. * * @return Boolean - Whether resuming playing from the start of the current track was successful. */ fun resumeReading() { playSentence(PlaySentence.SAME) notifyPlayStateChanged(true) } /** * Allow to go the next sentence while still being in a completely black box. * * @return Boolean - Whether moving to the next sentence was successful. */ fun nextSentence(): Boolean { return playSentence(PlaySentence.NEXT) } /** * Allow to go the previous sentence while still being in a completely black box. * * @return Boolean - Whether moving to the previous sentence was successful. */ fun previousSentence(): Boolean { return playSentence(PlaySentence.PREV) } /** * The entry point for the hosting activity to adjust speech speed. Input is considered valid and within arbitrary * set boundaries. The update is not instantaneous and [TextToSpeech] needs to be paused and resumed for it to work. * * Print an exception if [textToSpeech.setSpeechRate(speed)] fails. * * @param speed: Float - The speech speed we wish to use with Android's [TextToSpeech]. */ fun setSpeechSpeed(speed: Float, restart: Boolean): Boolean { try { if (textToSpeech.setSpeechRate(speed) == TextToSpeech.ERROR) throw Exception("Failed to update speech speed") if (restart) { pauseReading() resumeReading() } } catch (e: Exception) { if (DEBUG) Timber.e(e.toString()) return false } return true } /** * Reorder the text to speech queue (after flushing it) according to the current track and the argument value. * * @param playSentence: [PlaySentence] - The track to play (relative to the current track). * * @return Boolean - Whether the function was executed successfully. */ private fun playSentence(playSentence: PlaySentence): Boolean { isPaused = false val index = currentUtterance + playSentence.value if (index >= utterances.size || index < 0) return false if (!flushUtterancesQueue()) return false for (i in index until utterances.size) { if (!addToUtterancesQueue(utterances[i], i)) { return false } } return true } /** * Helper function that manages adding an utterance to the Text To Speech for us. * * @return: Boolean - Whether adding the utterance to the Text To Speech queue was successful. */ private fun addToUtterancesQueue(utterance: String, index: Int): Boolean { if (textToSpeech.speak(utterance, TextToSpeech.QUEUE_ADD, null, index.toString()) == TextToSpeech.ERROR) { if (DEBUG) Timber .e("Error while adding utterance: $utterance to the TTS queue") return false } return true } /** * Helper function that manages flushing the Text To Speech for us. * * @return: Boolean - Whether flushing the Text To Speech queue was successful. */ private fun flushUtterancesQueue(): Boolean { if (textToSpeech.speak("", TextToSpeech.QUEUE_FLUSH, null, null) == TextToSpeech.ERROR) { if (DEBUG) Timber.e("Error while flushing TTS queue.") return false } return true } /** * Split all the paragraphs of the resource into sentences. The sentences are then added to the [utterances] list. * * @param elements: Elements - The list of elements (paragraphs) */ private fun splitParagraphAndAddToUtterances(elements: Elements) { val elementSize = elements.size var index = 0 for (i in 0 until elementSize) { val element = elements.eq(i) if (element.`is`("p") || element.`is`("h1") || element.`is`("h2") || element.`is`("h3") || element.`is`("div") || element.`is`("span") ) { //val sentences = element.text().split(Regex("(?<=\\. |(,{1}))")) val sentences = element.text().split(Regex("(?<=\\.)")) for (sentence in sentences) { var sentenceCleaned = sentence if (sentenceCleaned.isNotEmpty()) { if (sentenceCleaned.first() == ' ') sentenceCleaned = sentenceCleaned.removeRange(0, 1) if (sentenceCleaned.last() == ' ') sentenceCleaned = sentenceCleaned.removeRange(sentenceCleaned.length - 1, sentenceCleaned.length) utterances.add(sentenceCleaned) index++ } } } } } /** * Fetch a resource and get short sentences from it. * * @param link: String - A link to the html resource to fetch, containing the text to be voiced. * * @return: Boolean - Whether the function executed successfully. */ private suspend fun splitResourceAndAddToUtterances(link: Link): Boolean { return try { val resource = publication.get(link).readAsString(charset = null).getOrThrow() val document = Jsoup.parse(resource) val elements = document.select("*") splitParagraphAndAddToUtterances(elements) true } catch (e: IOException) { if (DEBUG) Timber.e(e.toString()) false } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderEngine.kt
4180017824
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.tts import android.os.Bundle import org.readium.r2.shared.publication.Locator object ScreenReaderContract { private const val LOCATOR_KEY = "locator" val REQUEST_KEY: String = ScreenReaderContract::class.java.name data class Arguments(val locator: Locator) fun createArguments(locator: Locator): Bundle = Bundle().apply { putParcelable(LOCATOR_KEY, locator) } fun parseArguments(result: Bundle): Arguments { val locator = requireNotNull(result.getParcelable<Locator>(LOCATOR_KEY)) return Arguments(locator) } data class Result(val locator: Locator) fun createResult(locator: Locator): Bundle = Bundle().apply { putParcelable(LOCATOR_KEY, locator) } fun parseResult(result: Bundle): Result { val destination = requireNotNull(result.getParcelable<Locator>(LOCATOR_KEY)) return Result(destination) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderContract.kt
4174439663
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import org.readium.r2.testapp.domain.model.Catalog @Dao interface CatalogDao { /** * Inserts an Catalog * @param catalog The Catalog model to insert * @return ID of the Catalog model that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertCatalog(catalog: Catalog): Long /** * Retrieve list of Catalog models based on Catalog model * @return List of Catalog models as LiveData */ @Query("SELECT * FROM " + Catalog.TABLE_NAME + " WHERE " + Catalog.TITLE + " = :title AND " + Catalog.HREF + " = :href AND " + Catalog.TYPE + " = :type") fun getCatalogModels(title: String, href: String, type: Int): LiveData<List<Catalog>> /** * Retrieve list of all Catalog models * @return List of Catalog models as LiveData */ @Query("SELECT * FROM " + Catalog.TABLE_NAME) fun getCatalogModels(): LiveData<List<Catalog>> /** * Deletes an Catalog model * @param id The id of the Catalog model to delete */ @Query("DELETE FROM " + Catalog.TABLE_NAME + " WHERE " + Catalog.ID + " = :id") suspend fun deleteCatalog(id: Long) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/CatalogDao.kt
1463906175
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.db import androidx.annotation.ColorInt import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.domain.model.Bookmark import org.readium.r2.testapp.domain.model.Highlight @Dao interface BooksDao { /** * Inserts a book * @param book The book to insert * @return ID of the book that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertBook(book: Book): Long /** * Deletes a book * @param bookId The ID of the book */ @Query("DELETE FROM " + Book.TABLE_NAME + " WHERE " + Book.ID + " = :bookId") suspend fun deleteBook(bookId: Long) /** * Retrieve a book from its ID. */ @Query("SELECT * FROM " + Book.TABLE_NAME + " WHERE " + Book.ID + " = :id") suspend fun get(id: Long): Book? /** * Retrieve all books * @return List of books as LiveData */ @Query("SELECT * FROM " + Book.TABLE_NAME + " ORDER BY " + Book.CREATION_DATE + " desc") fun getAllBooks(): LiveData<List<Book>> /** * Retrieve all bookmarks for a specific book * @param bookId The ID of the book * @return List of bookmarks for the book as LiveData */ @Query("SELECT * FROM " + Bookmark.TABLE_NAME + " WHERE " + Bookmark.BOOK_ID + " = :bookId") fun getBookmarksForBook(bookId: Long): LiveData<MutableList<Bookmark>> /** * Retrieve all highlights for a specific book */ @Query("SELECT * FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.BOOK_ID} = :bookId ORDER BY ${Highlight.TOTAL_PROGRESSION} ASC") fun getHighlightsForBook(bookId: Long): Flow<List<Highlight>> /** * Retrieves the highlight with the given ID. */ @Query("SELECT * FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.ID} = :highlightId") suspend fun getHighlightById(highlightId: Long): Highlight? /** * Inserts a bookmark * @param bookmark The bookmark to insert * @return The ID of the bookmark that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertBookmark(bookmark: Bookmark): Long /** * Inserts a highlight * @param highlight The highlight to insert * @return The ID of the highlight that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertHighlight(highlight: Highlight): Long /** * Updates a highlight's annotation. */ @Query("UPDATE ${Highlight.TABLE_NAME} SET ${Highlight.ANNOTATION} = :annotation WHERE ${Highlight.ID} = :id") suspend fun updateHighlightAnnotation(id: Long, annotation: String) /** * Updates a highlight's tint and style. */ @Query("UPDATE ${Highlight.TABLE_NAME} SET ${Highlight.TINT} = :tint, ${Highlight.STYLE} = :style WHERE ${Highlight.ID} = :id") suspend fun updateHighlightStyle(id: Long, style: Highlight.Style, @ColorInt tint: Int) /** * Deletes a bookmark */ @Query("DELETE FROM " + Bookmark.TABLE_NAME + " WHERE " + Bookmark.ID + " = :id") suspend fun deleteBookmark(id: Long) /** * Deletes the highlight with given id. */ @Query("DELETE FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.ID} = :id") suspend fun deleteHighlight(id: Long) /** * Saves book progression * @param locator Location of the book * @param id The book to update */ @Query("UPDATE " + Book.TABLE_NAME + " SET " + Book.PROGRESSION + " = :locator WHERE " + Book.ID + "= :id") suspend fun saveProgression(locator: String, id: Long) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/BooksDao.kt
3495697265
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import org.readium.r2.testapp.domain.model.* @Database( entities = [Book::class, Bookmark::class, Highlight::class, Catalog::class], version = 1, exportSchema = false ) @TypeConverters(HighlightConverters::class) abstract class BookDatabase : RoomDatabase() { abstract fun booksDao(): BooksDao abstract fun catalogDao(): CatalogDao companion object { @Volatile private var INSTANCE: BookDatabase? = null fun getDatabase(context: Context): BookDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, BookDatabase::class.java, "books_database" ).build() INSTANCE = instance return instance } } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/Database.kt
3435371980
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.domain.model import android.net.Uri import android.os.Build import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import org.readium.r2.shared.util.mediatype.MediaType import java.net.URI import java.nio.file.Paths @Entity(tableName = Book.TABLE_NAME) data class Book( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = Bookmark.CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") val creation: Long? = null, @ColumnInfo(name = HREF) val href: String, @ColumnInfo(name = TITLE) val title: String, @ColumnInfo(name = AUTHOR) val author: String? = null, @ColumnInfo(name = IDENTIFIER) val identifier: String, @ColumnInfo(name = PROGRESSION) val progression: String? = null, @ColumnInfo(name = TYPE) val type: String ) { val fileName: String? get() { val url = URI(href) if (!url.scheme.isNullOrEmpty() && url.isAbsolute) { val uri = Uri.parse(href) return uri.lastPathSegment } return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val path = Paths.get(href) path.fileName.toString() } else { val uri = Uri.parse(href) uri.lastPathSegment } } val url: URI? get() { val url = URI(href) if (url.isAbsolute && url.scheme.isNullOrEmpty()) { return null } return url } suspend fun mediaType(): MediaType? = MediaType.of(type) companion object { const val TABLE_NAME = "books" const val ID = "id" const val CREATION_DATE = "creation_date" const val HREF = "href" const val TITLE = "title" const val AUTHOR = "author" const val IDENTIFIER = "identifier" const val PROGRESSION = "progression" const val TYPE = "type" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Book.kt
1676128334
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.domain.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import org.json.JSONObject import org.readium.r2.shared.publication.Locator @Entity( tableName = Bookmark.TABLE_NAME, indices = [Index( value = ["BOOK_ID", "LOCATION"], unique = true )] ) data class Bookmark( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") var creation: Long? = null, @ColumnInfo(name = BOOK_ID) val bookId: Long, @ColumnInfo(name = PUBLICATION_ID) val publicationId: String, @ColumnInfo(name = RESOURCE_INDEX) val resourceIndex: Long, @ColumnInfo(name = RESOURCE_HREF) val resourceHref: String, @ColumnInfo(name = RESOURCE_TYPE) val resourceType: String, @ColumnInfo(name = RESOURCE_TITLE) val resourceTitle: String, @ColumnInfo(name = LOCATION) val location: String, @ColumnInfo(name = LOCATOR_TEXT) val locatorText: String ) { val locator get() = Locator( href = resourceHref, type = resourceType, title = resourceTitle, locations = Locator.Locations.fromJSON(JSONObject(location)), text = Locator.Text.fromJSON(JSONObject(locatorText)) ) companion object { const val TABLE_NAME = "BOOKMARKS" const val ID = "ID" const val CREATION_DATE = "CREATION_DATE" const val BOOK_ID = "BOOK_ID" const val PUBLICATION_ID = "PUBLICATION_ID" const val RESOURCE_INDEX = "RESOURCE_INDEX" const val RESOURCE_HREF = "RESOURCE_HREF" const val RESOURCE_TYPE = "RESOURCE_TYPE" const val RESOURCE_TITLE = "RESOURCE_TITLE" const val LOCATION = "LOCATION" const val LOCATOR_TEXT = "LOCATOR_TEXT" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Bookmark.kt
2758096399
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.domain.model import androidx.annotation.ColorInt import androidx.room.* import org.json.JSONObject import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.util.MapWithDefaultCompanion /** * @param id Primary key, auto-incremented * @param style Look and feel of this annotation (highlight, underline) * @param title Provides additional context about the annotation * @param tint Color associated with the annotation * @param bookId Foreign key to the book * @param href References a resource within a publication * @param type References the media type of a resource within a publication * @param totalProgression Overall progression in the publication * @param locations Locator locations object * @param text Locator text object * @param annotation User-provided note attached to the annotation */ @Entity( tableName = "highlights", foreignKeys = [ ForeignKey(entity = Book::class, parentColumns = [Book.ID], childColumns = [Highlight.BOOK_ID], onDelete = ForeignKey.CASCADE) ], ) data class Highlight( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) var id: Long = 0, @ColumnInfo(name = CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") var creation: Long? = null, @ColumnInfo(name = BOOK_ID) val bookId: Long, @ColumnInfo(name = STYLE) var style: Style, @ColumnInfo(name = TINT, defaultValue = "0") @ColorInt var tint: Int, @ColumnInfo(name = HREF) var href: String, @ColumnInfo(name = TYPE) var type: String, @ColumnInfo(name = TITLE, defaultValue = "NULL") var title: String? = null, @ColumnInfo(name = TOTAL_PROGRESSION, defaultValue = "0") var totalProgression: Double = 0.0, @ColumnInfo(name = LOCATIONS, defaultValue = "{}") var locations: Locator.Locations = Locator.Locations(), @ColumnInfo(name = TEXT, defaultValue = "{}") var text: Locator.Text = Locator.Text(), @ColumnInfo(name = ANNOTATION, defaultValue = "") var annotation: String = "", ) { constructor(bookId: Long, style: Style, @ColorInt tint: Int, locator: Locator, annotation: String) : this( bookId = bookId, style = style, tint = tint, href = locator.href, type = locator.type, title = locator.title, totalProgression = locator.locations.totalProgression ?: 0.0, locations = locator.locations, text = locator.text, annotation = annotation ) val locator: Locator get() = Locator( href = href, type = type, title = title, locations = locations, text = text, ) enum class Style(val value: String) { HIGHLIGHT("highlight"), UNDERLINE("underline"); companion object : MapWithDefaultCompanion<String, Style>(values(), Style::value, HIGHLIGHT) } companion object { const val TABLE_NAME = "HIGHLIGHTS" const val ID = "ID" const val CREATION_DATE = "CREATION_DATE" const val BOOK_ID = "BOOK_ID" const val STYLE = "STYLE" const val TINT = "TINT" const val HREF = "HREF" const val TYPE = "TYPE" const val TITLE = "TITLE" const val TOTAL_PROGRESSION = "TOTAL_PROGRESSION" const val LOCATIONS = "LOCATIONS" const val TEXT = "TEXT" const val ANNOTATION = "ANNOTATION" } } class HighlightConverters { @TypeConverter fun styleFromString(value: String?): Highlight.Style = Highlight.Style(value) @TypeConverter fun styleToString(style: Highlight.Style): String = style.value @TypeConverter fun textFromString(value: String?): Locator.Text = Locator.Text.fromJSON(value?.let { JSONObject(it) }) @TypeConverter fun textToString(text: Locator.Text): String = text.toJSON().toString() @TypeConverter fun locationsFromString(value: String?): Locator.Locations = Locator.Locations.fromJSON(value?.let { JSONObject(it) }) @TypeConverter fun locationsToString(text: Locator.Locations): String = text.toJSON().toString() }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Highlight.kt
1406578602
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.domain.model import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity(tableName = Catalog.TABLE_NAME) data class Catalog( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = TITLE) var title: String, @ColumnInfo(name = HREF) var href: String, @ColumnInfo(name = TYPE) var type: Int ) : Parcelable { companion object { const val TABLE_NAME = "CATALOG" const val ID = "ID" const val TITLE = "TITLE" const val HREF = "HREF" const val TYPE = "TYPE" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Catalog.kt
2229768703
/* * Module: r2-navigator-kotlin * Developers: Aferdita Muriqi, Clément Baumann, Mostapha Idoubihi, Paul Stoica * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.epub import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AppCompatActivity import org.json.JSONArray import org.readium.r2.navigator.R2BasicWebView import org.readium.r2.navigator.R2WebView import org.readium.r2.navigator.epub.fxl.R2FXLLayout import org.readium.r2.navigator.pager.R2EpubPageFragment import org.readium.r2.navigator.pager.R2PagerAdapter import org.readium.r2.navigator.pager.R2ViewPager import org.readium.r2.shared.* import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.PopupWindowUserSettingsBinding import org.readium.r2.testapp.utils.extensions.color import java.io.File class UserSettings(var preferences: SharedPreferences, val context: Context, private val UIPreset: MutableMap<ReadiumCSSName, Boolean>) { lateinit var resourcePager: R2ViewPager private val appearanceValues = listOf("readium-default-on", "readium-sepia-on", "readium-night-on") private val fontFamilyValues = listOf("Original", "PT Serif", "Roboto", "Source Sans Pro", "Vollkorn", "OpenDyslexic", "AccessibleDfA", "IA Writer Duospace") private val textAlignmentValues = listOf("justify", "start") private val columnCountValues = listOf("auto", "1", "2") private var fontSize = 100f private var fontOverride = false private var fontFamily = 0 private var appearance = 0 private var verticalScroll = false //Advanced settings private var publisherDefaults = false private var textAlignment = 0 private var columnCount = 0 private var wordSpacing = 0f private var letterSpacing = 0f private var pageMargins = 2f private var lineHeight = 1f private var userProperties: UserProperties init { appearance = preferences.getInt(APPEARANCE_REF, appearance) verticalScroll = preferences.getBoolean(SCROLL_REF, verticalScroll) fontFamily = preferences.getInt(FONT_FAMILY_REF, fontFamily) if (fontFamily != 0) { fontOverride = true } publisherDefaults = preferences.getBoolean(PUBLISHER_DEFAULT_REF, publisherDefaults) textAlignment = preferences.getInt(TEXT_ALIGNMENT_REF, textAlignment) columnCount = preferences.getInt(COLUMN_COUNT_REF, columnCount) fontSize = preferences.getFloat(FONT_SIZE_REF, fontSize) wordSpacing = preferences.getFloat(WORD_SPACING_REF, wordSpacing) letterSpacing = preferences.getFloat(LETTER_SPACING_REF, letterSpacing) pageMargins = preferences.getFloat(PAGE_MARGINS_REF, pageMargins) lineHeight = preferences.getFloat(LINE_HEIGHT_REF, lineHeight) userProperties = getUserSettings() //Setting up screen brightness val backLightValue = preferences.getInt("reader_brightness", 50).toFloat() / 100 val layoutParams = (context as AppCompatActivity).window.attributes layoutParams.screenBrightness = backLightValue context.window.attributes = layoutParams } private fun getUserSettings(): UserProperties { val userProperties = UserProperties() // Publisher default system userProperties.addSwitchable("readium-advanced-off", "readium-advanced-on", publisherDefaults, PUBLISHER_DEFAULT_REF, PUBLISHER_DEFAULT_NAME) // Font override userProperties.addSwitchable("readium-font-on", "readium-font-off", fontOverride, FONT_OVERRIDE_REF, FONT_OVERRIDE_NAME) // Column count userProperties.addEnumerable(columnCount, columnCountValues, COLUMN_COUNT_REF, COLUMN_COUNT_NAME) // Appearance userProperties.addEnumerable(appearance, appearanceValues, APPEARANCE_REF, APPEARANCE_NAME) // Page margins userProperties.addIncremental(pageMargins, 0.5f, 4f, 0.25f, "", PAGE_MARGINS_REF, PAGE_MARGINS_NAME) // Text alignment userProperties.addEnumerable(textAlignment, textAlignmentValues, TEXT_ALIGNMENT_REF, TEXT_ALIGNMENT_NAME) // Font family userProperties.addEnumerable(fontFamily, fontFamilyValues, FONT_FAMILY_REF, FONT_FAMILY_NAME) // Font size userProperties.addIncremental(fontSize, 100f, 300f, 25f, "%", FONT_SIZE_REF, FONT_SIZE_NAME) // Line height userProperties.addIncremental(lineHeight, 1f, 2f, 0.25f, "", LINE_HEIGHT_REF, LINE_HEIGHT_NAME) // Word spacing userProperties.addIncremental(wordSpacing, 0f, 0.5f, 0.25f, "rem", WORD_SPACING_REF, WORD_SPACING_NAME) // Letter spacing userProperties.addIncremental(letterSpacing, 0f, 0.5f, 0.0625f, "em", LETTER_SPACING_REF, LETTER_SPACING_NAME) // Scroll userProperties.addSwitchable("readium-scroll-on", "readium-scroll-off", verticalScroll, SCROLL_REF, SCROLL_NAME) return userProperties } private fun makeJson(): JSONArray { val array = JSONArray() for (userProperty in userProperties.properties) { array.put(userProperty.getJson()) } return array } fun saveChanges() { val json = makeJson() val dir = File(context.filesDir.path + "/" + Injectable.Style.rawValue + "/") dir.mkdirs() val file = File(dir, "UserProperties.json") file.printWriter().use { out -> out.println(json) } } private fun updateEnumerable(enumerable: Enumerable) { preferences.edit().putInt(enumerable.ref, enumerable.index).apply() saveChanges() } private fun updateSwitchable(switchable: Switchable) { preferences.edit().putBoolean(switchable.ref, switchable.on).apply() saveChanges() } private fun updateIncremental(incremental: Incremental) { preferences.edit().putFloat(incremental.ref, incremental.value).apply() saveChanges() } fun updateViewCSS(ref: String) { for (i in 0 until resourcePager.childCount) { val webView = resourcePager.getChildAt(i).findViewById(R.id.webView) as? R2WebView webView?.let { applyCSS(webView, ref) } ?: run { val zoomView = resourcePager.getChildAt(i).findViewById(R.id.r2FXLLayout) as R2FXLLayout val webView1 = zoomView.findViewById(R.id.firstWebView) as? R2BasicWebView val webView2 = zoomView.findViewById(R.id.secondWebView) as? R2BasicWebView val webViewSingle = zoomView.findViewById(R.id.webViewSingle) as? R2BasicWebView webView1?.let { applyCSS(webView1, ref) } webView2?.let { applyCSS(webView2, ref) } webViewSingle?.let { applyCSS(webViewSingle, ref) } } } } private fun applyCSS(view: R2BasicWebView, ref: String) { val userSetting = userProperties.getByRef<UserProperty>(ref) view.setProperty(userSetting.name, userSetting.toString()) } // There isn't an easy way to migrate from TabHost/TabWidget to TabLayout @Suppress("DEPRECATION") fun userSettingsPopUp(): PopupWindow { val layoutInflater = LayoutInflater.from(context) val layout = PopupWindowUserSettingsBinding.inflate(layoutInflater) val userSettingsPopup = PopupWindow(context) userSettingsPopup.contentView = layout.root userSettingsPopup.width = ListPopupWindow.WRAP_CONTENT userSettingsPopup.height = ListPopupWindow.WRAP_CONTENT userSettingsPopup.isOutsideTouchable = true userSettingsPopup.isFocusable = true val host = layout.tabhost host.setup() //Tab 1 var spec: TabHost.TabSpec = host.newTabSpec("Settings") spec.setContent(R.id.SettingsTab) spec.setIndicator("Settings") host.addTab(spec) //Tab 2 spec = host.newTabSpec("Advanced") spec.setContent(R.id.Advanced) spec.setIndicator("Advanced") host.addTab(spec) val tw = host.findViewById(android.R.id.tabs) as TabWidget (tw.getChildTabViewAt(0).findViewById(android.R.id.title) as TextView).textSize = 10f (tw.getChildTabViewAt(1).findViewById(android.R.id.title) as TextView).textSize = 10f val fontFamily = (userProperties.getByRef<Enumerable>(FONT_FAMILY_REF)) val fontOverride = (userProperties.getByRef<Switchable>(FONT_OVERRIDE_REF)) val appearance = userProperties.getByRef<Enumerable>(APPEARANCE_REF) val fontSize = userProperties.getByRef<Incremental>(FONT_SIZE_REF) val publisherDefault = userProperties.getByRef<Switchable>(PUBLISHER_DEFAULT_REF) val scrollMode = userProperties.getByRef<Switchable>(SCROLL_REF) val alignment = userProperties.getByRef<Enumerable>(TEXT_ALIGNMENT_REF) val columnsCount = userProperties.getByRef<Enumerable>(COLUMN_COUNT_REF) val pageMargins = userProperties.getByRef<Incremental>(PAGE_MARGINS_REF) val wordSpacing = userProperties.getByRef<Incremental>(WORD_SPACING_REF) val letterSpacing = userProperties.getByRef<Incremental>(LETTER_SPACING_REF) val lineHeight = userProperties.getByRef<Incremental>(LINE_HEIGHT_REF) val fontSpinner: Spinner = layout.spinnerActionSettingsIntervallValues val fonts = context.resources.getStringArray(R.array.font_list) val dataAdapter = object : ArrayAdapter<String>(context, R.layout.item_spinner_font, fonts) { override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val v: View? = super.getDropDownView(position, null, parent) // Makes the selected font appear in dark // If this is the selected item position if (position == fontFamily.index) { v!!.setBackgroundColor(context.color(R.color.colorPrimaryDark)) v.findViewById<TextView>(android.R.id.text1).setTextColor(Color.WHITE) } else { // for other views v!!.setBackgroundColor(Color.WHITE) v.findViewById<TextView>(android.R.id.text1).setTextColor(Color.BLACK) } return v } } fun findIndexOfId(id: Int, list: MutableList<RadioButton>): Int { for (i in 0..list.size) { if (list[i].id == id) { return i } } return 0 } // Font family dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) fontSpinner.adapter = dataAdapter fontSpinner.setSelection(fontFamily.index) fontSpinner.contentDescription = "Font Family" fontSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { fontFamily.index = pos fontOverride.on = (pos != 0) updateSwitchable(fontOverride) updateEnumerable(fontFamily) updateViewCSS(FONT_OVERRIDE_REF) updateViewCSS(FONT_FAMILY_REF) } override fun onNothingSelected(parent: AdapterView<out Adapter>?) { // fontSpinner.setSelection(selectedFontIndex) } } // Appearance val appearanceGroup = layout.appearance val appearanceRadios = mutableListOf<RadioButton>() appearanceRadios.add(layout.appearanceDefault) layout.appearanceDefault.contentDescription = "Appearance Default" appearanceRadios.add(layout.appearanceSepia) layout.appearanceSepia.contentDescription = "Appearance Sepia" appearanceRadios.add(layout.appearanceNight) layout.appearanceNight.contentDescription = "Appearance Night" UIPreset[ReadiumCSSName.appearance]?.let { appearanceGroup.isEnabled = false for (appearanceRadio in appearanceRadios) { appearanceRadio.isEnabled = false } } ?: run { appearanceRadios[appearance.index].isChecked = true appearanceGroup.setOnCheckedChangeListener { _, id -> val i = findIndexOfId(id, list = appearanceRadios) appearance.index = i when (i) { 0 -> { resourcePager.setBackgroundColor(Color.parseColor("#ffffff")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#000000")) } 1 -> { resourcePager.setBackgroundColor(Color.parseColor("#faf4e8")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#000000")) } 2 -> { resourcePager.setBackgroundColor(Color.parseColor("#000000")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#ffffff")) } } updateEnumerable(appearance) updateViewCSS(APPEARANCE_REF) } } // Font size val fontDecreaseButton = layout.fontDecrease val fontIncreaseButton = layout.fontIncrease UIPreset[ReadiumCSSName.fontSize]?.let { fontDecreaseButton.isEnabled = false fontIncreaseButton.isEnabled = false } ?: run { fontDecreaseButton.setOnClickListener { fontSize.decrement() updateIncremental(fontSize) updateViewCSS(FONT_SIZE_REF) } fontIncreaseButton.setOnClickListener { fontSize.increment() updateIncremental(fontSize) updateViewCSS(FONT_SIZE_REF) } } // Publisher defaults val publisherDefaultSwitch = layout.publisherDefault publisherDefaultSwitch.contentDescription = "\u00A0" publisherDefaultSwitch.isChecked = publisherDefault.on publisherDefaultSwitch.setOnCheckedChangeListener { _, b -> publisherDefault.on = b updateSwitchable(publisherDefault) updateViewCSS(PUBLISHER_DEFAULT_REF) } // Vertical scroll val scrollModeSwitch = layout.scrollMode UIPreset[ReadiumCSSName.scroll]?.let { isSet -> scrollModeSwitch.isChecked = isSet scrollModeSwitch.isEnabled = false } ?: run { scrollModeSwitch.isChecked = scrollMode.on scrollModeSwitch.setOnCheckedChangeListener { _, b -> scrollMode.on = scrollModeSwitch.isChecked updateSwitchable(scrollMode) updateViewCSS(SCROLL_REF) val currentFragment = (resourcePager.adapter as R2PagerAdapter).getCurrentFragment() val previousFragment = (resourcePager.adapter as R2PagerAdapter).getPreviousFragment() val nextFragment = (resourcePager.adapter as R2PagerAdapter).getNextFragment() if (currentFragment is R2EpubPageFragment) { currentFragment.webView?.let { webView -> webView.scrollToPosition(webView.progression) (previousFragment as? R2EpubPageFragment)?.webView?.scrollToEnd() (nextFragment as? R2EpubPageFragment)?.webView?.scrollToStart() webView.setScrollMode(b) (previousFragment as? R2EpubPageFragment)?.webView?.setScrollMode(b) (nextFragment as? R2EpubPageFragment)?.webView?.setScrollMode(b) } } } } // Text alignment val alignmentGroup = layout.TextAlignment val alignmentRadios = mutableListOf<RadioButton>() alignmentRadios.add(layout.alignmentLeft) (layout.alignmentLeft).contentDescription = "Alignment Left" alignmentRadios.add(layout.alignmentJustify) layout.alignmentJustify.contentDescription = "Alignment Justified" UIPreset[ReadiumCSSName.textAlignment]?.let { alignmentGroup.isEnabled = false alignmentGroup.isActivated = false for (alignmentRadio in alignmentRadios) { alignmentRadio.isEnabled = false } } ?: run { alignmentRadios[alignment.index].isChecked = true alignmentGroup.setOnCheckedChangeListener { _, i -> alignment.index = findIndexOfId(i, alignmentRadios) publisherDefaultSwitch.isChecked = false updateEnumerable(alignment) updateViewCSS(TEXT_ALIGNMENT_REF) } } // Column count val columnsCountGroup = layout.columns val columnsRadios = mutableListOf<RadioButton>() columnsRadios.add(layout.columnAuto) layout.columnAuto.contentDescription = "Columns Auto" columnsRadios.add(layout.columnOne) layout.columnOne.contentDescription = "Columns 1" columnsRadios.add(layout.columnTwo) layout.columnTwo.contentDescription = "Columns 2" UIPreset[ReadiumCSSName.columnCount]?.let { columnsCountGroup.isEnabled = false columnsCountGroup.isActivated = false for (columnRadio in columnsRadios) { columnRadio.isEnabled = false } } ?: run { columnsRadios[columnsCount.index].isChecked = true columnsCountGroup.setOnCheckedChangeListener { _, id -> val i = findIndexOfId(id, columnsRadios) columnsCount.index = i publisherDefaultSwitch.isChecked = false updateEnumerable(columnsCount) updateViewCSS(COLUMN_COUNT_REF) } } // Page margins val pageMarginsDecreaseButton = layout.pmDecrease val pageMarginsIncreaseButton = layout.pmIncrease val pageMarginsDisplay = layout.pmDisplay pageMarginsDisplay.text = pageMargins.value.toString() UIPreset[ReadiumCSSName.pageMargins]?.let { pageMarginsDecreaseButton.isEnabled = false pageMarginsIncreaseButton.isEnabled = false } ?: run { pageMarginsDecreaseButton.setOnClickListener { pageMargins.decrement() pageMarginsDisplay.text = pageMargins.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(pageMargins) updateViewCSS(PAGE_MARGINS_REF) } pageMarginsIncreaseButton.setOnClickListener { pageMargins.increment() pageMarginsDisplay.text = pageMargins.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(pageMargins) updateViewCSS(PAGE_MARGINS_REF) } } // Word spacing val wordSpacingDecreaseButton = layout.wsDecrease val wordSpacingIncreaseButton = layout.wsIncrease val wordSpacingDisplay = layout.wsDisplay wordSpacingDisplay.text = (if (wordSpacing.value == wordSpacing.min) "auto" else wordSpacing.value.toString()) UIPreset[ReadiumCSSName.wordSpacing]?.let { wordSpacingDecreaseButton.isEnabled = false wordSpacingIncreaseButton.isEnabled = false } ?: run { wordSpacingDecreaseButton.setOnClickListener { wordSpacing.decrement() wordSpacingDisplay.text = (if (wordSpacing.value == wordSpacing.min) "auto" else wordSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(wordSpacing) updateViewCSS(WORD_SPACING_REF) } wordSpacingIncreaseButton.setOnClickListener { wordSpacing.increment() wordSpacingDisplay.text = wordSpacing.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(wordSpacing) updateViewCSS(WORD_SPACING_REF) } } // Letter spacing val letterSpacingDecreaseButton = layout.lsDecrease val letterSpacingIncreaseButton = layout.lsIncrease val letterSpacingDisplay = layout.lsDisplay letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) UIPreset[ReadiumCSSName.letterSpacing]?.let { letterSpacingDecreaseButton.isEnabled = false letterSpacingIncreaseButton.isEnabled = false } ?: run { letterSpacingDecreaseButton.setOnClickListener { letterSpacing.decrement() letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(letterSpacing) updateViewCSS(LETTER_SPACING_REF) } letterSpacingIncreaseButton.setOnClickListener { letterSpacing.increment() letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(letterSpacing) updateViewCSS(LETTER_SPACING_REF) } } // Line height val lineHeightDecreaseButton = layout.lhDecrease val lineHeightIncreaseButton = layout.lhIncrease val lineHeightDisplay = layout.lhDisplay lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) UIPreset[ReadiumCSSName.lineHeight]?.let { lineHeightDecreaseButton.isEnabled = false lineHeightIncreaseButton.isEnabled = false } ?: run { lineHeightDecreaseButton.setOnClickListener { lineHeight.decrement() lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(lineHeight) updateViewCSS(LINE_HEIGHT_REF) } lineHeightIncreaseButton.setOnClickListener { lineHeight.increment() lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(lineHeight) updateViewCSS(LINE_HEIGHT_REF) } } // Brightness val brightnessSeekbar = layout.brightness val brightness = preferences.getInt("reader_brightness", 50) brightnessSeekbar.progress = brightness brightnessSeekbar.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(bar: SeekBar, progress: Int, from_user: Boolean) { val backLightValue = progress.toFloat() / 100 val layoutParams = (context as AppCompatActivity).window.attributes layoutParams.screenBrightness = backLightValue context.window.attributes = layoutParams preferences.edit().putInt("reader_brightness", progress).apply() } override fun onStartTrackingTouch(bar: SeekBar) { // Nothing } override fun onStopTrackingTouch(bar: SeekBar) { // Nothing } }) // Speech speed val speechSeekBar = layout.TTSSpeechSpeed //Get the user settings value or set the progress bar to a neutral position (1 time speech speed). val speed = preferences.getInt("reader_TTS_speed", (2.75 * 3.toDouble() / 11.toDouble() * 100).toInt()) speechSeekBar.progress = speed speechSeekBar.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(bar: SeekBar, progress: Int, from_user: Boolean) { // Nothing } override fun onStartTrackingTouch(bar: SeekBar) { // Nothing } override fun onStopTrackingTouch(bar: SeekBar) { preferences.edit().putInt("reader_TTS_speed", bar.progress).apply() } }) return userSettingsPopup } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/epub/UserSettings.kt
2378335890
package com.sociallogin import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "SocialLogin" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
social_login/android/app/src/main/java/com/sociallogin/MainActivity.kt
1404469896
package com.sociallogin import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.flipper.ReactNativeFlipper import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List<ReactPackage> = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(this.applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, false) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager) } }
social_login/android/app/src/main/java/com/sociallogin/MainApplication.kt
1603675876
package com.aaa.myamplifyapp3 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.aaa.myamplifyapp3", appContext.packageName) } }
MyAmplifyApp3/app/src/androidTest/java/com/aaa/myamplifyapp3/ExampleInstrumentedTest.kt
3808022553
package com.aaa.myamplifyapp3 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MyAmplifyApp3/app/src/test/java/com/aaa/myamplifyapp3/ExampleUnitTest.kt
1911691643
package com.aaa.myamplifyapp3 import android.content.Context import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.amazonaws.mobile.client.AWSMobileClient import com.amazonaws.mobile.client.Callback import com.amazonaws.mobile.client.UserStateDetails import com.amazonaws.mobile.config.AWSConfiguration import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration import com.amazonaws.mobileconnectors.pinpoint.PinpointManager import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationDetails import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.RemoteMessage class MainActivity : AppCompatActivity() { companion object { const val TAG = "MyAmplifyApp3" } private lateinit var mPinpointManager: PinpointManager private fun getPinpointManager(applicationContext: Context): PinpointManager { if (!this::mPinpointManager.isInitialized) { // Initialize the AWS Mobile Client val awsConfig = AWSConfiguration(applicationContext) println("★★★ awsConfig $awsConfig") AWSMobileClient.getInstance() .initialize(applicationContext, awsConfig, object : Callback<UserStateDetails> { override fun onResult(userStateDetails: UserStateDetails) { Log.i("INIT", userStateDetails.userState.toString()) } override fun onError(e: Exception) { Log.e("INIT", "Initialization error.", e) } }) val pinpointConfig = PinpointConfiguration( applicationContext, AWSMobileClient.getInstance(), awsConfig ) println("★★★ pinpointConfig $pinpointConfig") mPinpointManager = PinpointManager(pinpointConfig) } return mPinpointManager } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onStart() { super.onStart() // FCMトークン取得 FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast val msg = getString(R.string.msg_token_fmt, token) Log.d(TAG, msg) Toast.makeText(baseContext, msg, Toast.LENGTH_LONG).show() }) try { // https://qiita.com/Idenon/items/a77f2da4de78dd0db74d mPinpointManager = getPinpointManager(applicationContext) mPinpointManager.sessionClient.startSession() println("★★★ pinpointManager $mPinpointManager") println("★★★ pinpointManager complete") // プッシュ通知からアプリを開いた場合intentにデータが入っている val campaignId = intent.getStringExtra("campaignId") val treatmentId = intent.getStringExtra("treatmentId") val campaignActivityId = intent.getStringExtra("campaignActivityId") val title = intent.getStringExtra("title") val body = intent.getStringExtra("body") if(campaignId != null && treatmentId != null && campaignActivityId != null && title != null && body != null){ notificationOpenedEvent(campaignId, treatmentId, campaignActivityId, title, body) } }catch (e: Exception){ e.printStackTrace() } val button: Button = findViewById<Button>(R.id.button2) button.setOnClickListener { // submitEvent() } } override fun onStop() { super.onStop() mPinpointManager.sessionClient.stopSession() mPinpointManager.analyticsClient.submitEvents() } private fun submitEvent(){ mPinpointManager.analyticsClient?.submitEvents() println("★★★ submitEvent pinpointManager.analyticsClient ${mPinpointManager.analyticsClient}") println("★★★ submitEvent pinpointManager.analyticsClient.allEvents ${mPinpointManager.analyticsClient.allEvents}") } private fun notificationOpenedEvent(campaignId: String, treatmentId: String, campaignActivityId: String, title: String, body: String){ println("★★★ notificationOpenedEvent") val event: AnalyticsEvent? = mPinpointManager.analyticsClient.createEvent("_campaign.opened_notification") .withAttribute("_campaign_id", campaignId) .withAttribute("treatment_id", treatmentId) .withAttribute("campaign_activity_id", campaignActivityId) .withAttribute("notification_title", title) .withAttribute("notification_body", body) .withMetric("Opened", 1.0) println("★★★ notificationOpenedEvent event $event") mPinpointManager.analyticsClient?.recordEvent(event) submitEvent() } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MainActivity.kt
3836325986
package com.aaa.myamplifyapp3 import android.app.Application class MyAmplifyApp3: Application() { override fun onCreate() { super.onCreate() // try { // Amplify.addPlugin(AWSCognitoAuthPlugin()) // Amplify.addPlugin(AWSPinpointPushNotificationsPlugin()) // Amplify.addPlugin(AWSPinpointAnalyticsPlugin()) // // 分析で使用する // Amplify.addPlugin(AWSDataStorePlugin()) // Amplify.configure(applicationContext) // Log.i("MyAmplifyApp", "Initialized Amplify") // // val event = AnalyticsEvent.builder() // .name("PasswordReset") // .addProperty("Channel", "SMS") // .addProperty("Successful", true) // .addProperty("ProcessDuration", 792) // .addProperty("UserAge", 120.3) // .build() // Amplify.Analytics.recordEvent(event) // } catch (error: AmplifyException) { // Log.e("MyAmplifyApp", "Could not initialize Amplify", error) // } } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MyAmplifyApp3.kt
3945365821
package com.aaa.myamplifyapp3 import android.Manifest import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity class AuthorityRequestActivity : AppCompatActivity() { private val mIsGrantedMap: MutableMap<String, Boolean> = mutableMapOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 権限要求 requestPermission() } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> permissions.entries.forEach { val permissionName = it.key val isGranted = it.value mIsGrantedMap[permissionName] = isGranted } // 権限がすべて許可されていた場合は待機画面に遷移する。 if (checkAllPermissionsGranted()) { showStandbyScreenActivity() } else { Toast.makeText( this, "権限を許可してください。", Toast.LENGTH_LONG ).show() finish() } } private fun checkAllPermissionsGranted(): Boolean { // すべての値がtrueかどうかを確認 return mIsGrantedMap.values.all { it } } private fun requestPermission() { requestPermissionLauncher.launch( arrayOf( // 通知 Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.ACCESS_NETWORK_STATE, ) ) } private fun showStandbyScreenActivity() { startActivity(Intent(this, MainActivity::class.java)) finish() } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/AuthorityRequestActivity.kt
3563982986
package com.aaa.myamplifyapp3 import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent //import com.amplifyframework.core.Amplify //import com.amplifyframework.notifications.pushnotifications.NotificationContentProvider //import com.amplifyframework.notifications.pushnotifications.NotificationPayload import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class MyFirebaseMessagingService: FirebaseMessagingService() { companion object { private const val TAG = "MyFirebaseMsgService" // var notificationPayload: NotificationPayload? = null } private data class MessageFCM( var messageTitle: String = "", var messageBody: String = "", ) // [START receive_message] override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) println("★★★ remoteMessage: $remoteMessage") // メッセージが届いていない場合は、こちらを参照してください: https://goo.gl/39bRNJ Log.d(TAG, "From: ${remoteMessage.from}") // メッセージがデータペイロードを含んでいるか確認します。 if (remoteMessage.data.isNotEmpty()) { // データが長時間実行されるジョブによって処理される必要があるか確認します // if (needsToBeScheduled()) { // // 長時間実行されるタスク(10秒以上)の場合は WorkManager を使用します。 //// scheduleJob() // } else { // // 10秒以内にメッセージを処理します // handleNow() // } handleNow() } // 通知の生成 sendNotification(remoteMessage) } // [END receive_message] private fun needsToBeScheduled() = true // [START on_new_token] /** * Called if the FCM registration token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the * FCM registration token is initially generated so this is where you would retrieve the token. */ override fun onNewToken(token: String) { Log.d(TAG, "Refreshed token: $token") // Register device with Pinpoint // Amplify.Notifications.Push.registerDevice(token, // { Log.i(TAG, "Successfully registered device") }, // { error -> Log.e(TAG, "Error registering device", error) } // ) sendRegistrationToServer(token) } private fun handleNow() { Log.d(TAG, "Short lived task is done.") } private fun sendRegistrationToServer(token: String?) { // TODO: Implement this method to send token to your app server. Log.d(TAG, "sendRegistrationTokenToServer($token)") } private fun sendNotification(remoteMessage: RemoteMessage) { // RemoteMessage を NoticePayload に変換する // val notificationPayload = NotificationPayload(NotificationContentProvider.FCM(remoteMessage.data)) // Pinpoint から送信された通知を Amplify で処理する必要がある // val isAmplifyMessage = Amplify.Notifications.Push.shouldHandleNotification(notificationPayload!!) // if (isAmplifyMessage) { // // Record notification received with Amplify // Amplify.Notifications.Push.recordNotificationReceived(notificationPayload, // { Log.i(TAG, "Successfully recorded a notification received") }, // { error -> Log.e(TAG, "Error recording notification received", error) } // ) // } var campaignId: String = "" var treatmentId: String = "" var campaignActivityId: String = "" var title: String = "" var body: String = "" try { // PinPointからのメッセージ取得 campaignId = remoteMessage.data.getValue("pinpoint.campaign.campaign_id") ?: "" treatmentId = remoteMessage.data.getValue("pinpoint.campaign.treatment_id") ?: "" campaignActivityId = remoteMessage.data.getValue("pinpoint.campaign.campaign_activity_id") ?: "" title = remoteMessage.data.getValue("pinpoint.notification.title") ?: "" body = remoteMessage.data.getValue("pinpoint.notification.body") ?: "" }catch (e: NoSuchElementException){ e.printStackTrace() } try { // PinPointからのメッセージ取得 title = remoteMessage.data.getValue("pinpoint.notification.title") ?: "" body = remoteMessage.data.getValue("pinpoint.notification.body") ?: "" }catch (e: NoSuchElementException){ e.printStackTrace() } val messageFCM = MessageFCM() messageFCM.messageTitle = title messageFCM.messageBody = body println("★★★ remoteMessage.data: ${remoteMessage.data}") val notificationId = System.currentTimeMillis().toInt() // val intent = Intent(this, MainActivity::class.java) // intent.putExtra("notificationPayload", notificationPayload) // PinPointの情報をintentに設定(起動時にMainActivityで受け取る) val intent = Intent(this, MainActivity::class.java) intent.putExtra("campaignId", campaignId) intent.putExtra("treatmentId", treatmentId) intent.putExtra("campaignActivityId", campaignActivityId) intent.putExtra("title", title) intent.putExtra("body", body) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val requestCode = 100 val pendingIntent = PendingIntent.getActivity( this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // intentを保持するために必要。(notificationPayloadの受け渡しのため) // PendingIntent.FLAG_IMMUTABLE, // これは既存のインテントが保持されない。 ) val channelId = "fcm_default_channel" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(messageFCM.messageTitle) .setContentText(messageFCM.messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 通知の優先度 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Since android Oreo notification channel is needed. val channel = NotificationChannel( channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT, ) notificationManager.createNotificationChannel(channel) // val notificationId = System.currentTimeMillis().toInt() notificationManager.notify(notificationId, notificationBuilder.build()) } // internal class MyWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { // override fun doWork(): Result { // // TODO(developer): add long running task here. // return Result.success() // } // } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MyFirebaseMessagingService.kt
1461722042
package com.thezayin.chatbottesting import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.thezayin.chatbottesting", appContext.packageName) } }
Brainshop-chatbot-app/app/src/androidTest/java/com/thezayin/chatbottesting/ExampleInstrumentedTest.kt
1044688423
package com.thezayin.chatbottesting import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Brainshop-chatbot-app/app/src/test/java/com/thezayin/chatbottesting/ExampleUnitTest.kt
107884769
package com.thezayin.chatbottesting.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Color.kt
3709419459
package com.thezayin.chatbottesting.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ChatbottestingTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Theme.kt
2662248087
package com.thezayin.chatbottesting.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Type.kt
3369376514
package com.thezayin.chatbottesting import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresExtension import androidx.hilt.navigation.compose.hiltViewModel import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.presentation.ChatScreen import com.thezayin.chatbottesting.presentation.ChatViewModel import com.thezayin.chatbottesting.ui.theme.ChatbottestingTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ChatbottestingTheme { ChatScreen() } } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/MainActivity.kt
2411475134
package com.thezayin.chatbottesting.di import com.thezayin.chatbottesting.data.BotRepositoryImpl import com.thezayin.chatbottesting.data.botapi.BotApi import com.thezayin.chatbottesting.domain.repo.BotRepository import com.thezayin.chatbottesting.domain.usecase.BotUseCase import com.thezayin.chatbottesting.domain.usecase.MessageUseCases import com.thezayin.chatbottesting.utils.Constants.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideBotApi(): BotApi { return Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()).build() .create(BotApi::class.java) } @Provides @Singleton fun provideBotRepository(botApi: BotApi): BotRepository { return BotRepositoryImpl(botApi) } @Provides @Singleton fun provideUseCase(repository: BotRepository) = MessageUseCases(botUseCase = BotUseCase(repository)) }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/di/AppModule.kt
2472087001
package com.thezayin.chatbottesting.utils import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class Application:Application() { }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/utils/Application.kt
686880067
package com.thezayin.chatbottesting.utils sealed class Response<out T> { object Loading : Response<Nothing>() data class Failure(val e: String) : Response<Nothing>() data class Success<out T>(val data: T) : Response<T>() }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/utils/Response.kt
1943579850
package com.thezayin.chatbottesting.utils object Constants { val BASE_URL = "http://api.brainshop.ai/" }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/utils/Constants.kt
1369258272
package com.thezayin.chatbottesting.data.botapi import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.utils.Response import retrofit2.http.GET import retrofit2.http.Query interface BotApi { @GET("/get?bid=180701&key=HNALinzc2atw9sWA&uid=[uid]") suspend fun sendMessage(@Query("msg") msg: String): Message }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/data/botapi/BotApi.kt
3659504589
package com.thezayin.chatbottesting.data import com.thezayin.chatbottesting.data.botapi.BotApi import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.domain.repo.BotRepository import javax.inject.Inject class BotRepositoryImpl @Inject constructor(private val botApi: BotApi) : BotRepository { override suspend fun sendMessage(string: String): Message { return botApi.sendMessage(string) } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/data/BotRepositoryImpl.kt
3901104756
package com.thezayin.chatbottesting.domain.model data class Message( val sender:String?, val cnt: String )
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/domain/model/Message.kt
2705761382
package com.thezayin.chatbottesting.domain.usecase import android.net.http.HttpException import android.os.Build import android.util.Log import androidx.annotation.RequiresExtension import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.domain.repo.BotRepository import com.thezayin.chatbottesting.utils.Response import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import java.io.IOException import javax.inject.Inject class BotUseCase @Inject constructor( private val botRepository: BotRepository ) { @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) operator fun invoke(message: String): Flow<Response<Message>> = flow { try { emit(Response.Loading) val response = botRepository.sendMessage(message) emit(Response.Success(response)) } catch (e: HttpException) { emit(Response.Failure(e.localizedMessage ?: "Unexpected Error")) } catch (e: IOException) { emit(Response.Failure(e.localizedMessage ?: "Unexpected Error")) } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/domain/usecase/BotUseCase.kt
3418155207
package com.thezayin.chatbottesting.domain.usecase data class MessageUseCases( val botUseCase: BotUseCase )
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/domain/usecase/MessageUseCases.kt
3108555749
package com.thezayin.chatbottesting.domain.repo import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.utils.Response import kotlinx.coroutines.flow.Flow interface BotRepository { suspend fun sendMessage(string: String): Message }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/domain/repo/BotRepository.kt
1963273717
package com.thezayin.chatbottesting.presentation.component import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.thezayin.chatbottesting.R @Composable fun TopBar(modifier: Modifier, title: String, callBack: () -> Unit) { Box( modifier = modifier .background(colorResource(id = R.color.white)) .fillMaxWidth() .padding(20.dp) ) { Image(painter = painterResource(id = R.drawable.ic_back), contentDescription = "", modifier = Modifier .size(22.dp) .fillMaxHeight() .align(Alignment.CenterStart) .clickable { callBack() }) Text( text = title, fontSize = 24.sp, color = colorResource(id = R.color.text_color), fontWeight = FontWeight.Medium, // fontFamily = FontFamily(Font(R.font.nunito_extrabold)), modifier = Modifier .align(alignment = Alignment.Center) ) } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/presentation/component/TopBar.kt
3220865893
package com.thezayin.chatbottesting.presentation.component import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.thezayin.chatbottesting.R import com.thezayin.chatbottesting.domain.model.Message @Composable fun MessageBody(message: Message) { Box( modifier = Modifier.fillMaxWidth() ) { Card( colors = CardDefaults.cardColors( if (message.sender.equals("bot")) colorResource(id = R.color.ed_background) else colorResource( id = R.color.primary ), ), modifier = Modifier .padding(10.dp) .wrapContentWidth() .widthIn(min = 50.dp, max = 300.dp) .align(if (message.sender.equals("bot")) Alignment.CenterStart else Alignment.CenterEnd), shape = RoundedCornerShape( topStart = if (message.sender.equals("bot")) 0.dp else 24.dp, topEnd = 24.dp, bottomEnd = if (message.sender.equals("bot")) 24.dp else 0.dp, bottomStart = 24.dp, ), elevation = CardDefaults.cardElevation(1.dp) ) { Box( modifier = Modifier, contentAlignment = Alignment.Center ) { Text( text = message.cnt, textAlign = TextAlign.Center, color = if (message.sender.equals("bot")) Color.Black else Color.White, modifier = Modifier .padding(horizontal = 20.dp, vertical = 10.dp) .wrapContentHeight(Alignment.CenterVertically) ) } } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/presentation/component/MessageBody.kt
1003092203
package com.thezayin.chatbottesting.presentation.component import android.os.Build import androidx.annotation.RequiresExtension import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.thezayin.chatbottesting.R import com.thezayin.chatbottesting.presentation.ChatViewModel import kotlinx.coroutines.launch @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) @Composable fun ChatBox(modifier: Modifier, chatViewModel: ChatViewModel, listState: LazyListState) { var chatBoxValue by remember { mutableStateOf(TextFieldValue("")) } val coroutineScope = rememberCoroutineScope() Row( modifier = modifier .fillMaxWidth() .background(color = Color.White) .padding(horizontal = 10.dp) .padding(bottom = 15.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.Bottom ) { OutlinedTextField( value = chatBoxValue, onValueChange = { newText -> chatBoxValue = newText }, placeholder = { Text( text = "Type a message...", color = colorResource(id = R.color.grey), fontSize = 16.sp, modifier = Modifier.padding(horizontal = 5.dp) ) }, modifier = Modifier .heightIn(45.dp) .fillMaxWidth(0.8f) .padding(0.dp, 10.dp, 0.dp, 0.dp), shape = RoundedCornerShape(48.dp), colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = colorResource(id = R.color.primary), focusedTextColor = colorResource(id = R.color.black), unfocusedTextColor = colorResource(id = R.color.black), unfocusedBorderColor = colorResource(id = R.color.primary), ), ) IconButton( modifier = Modifier .size(55.dp), colors = IconButtonDefaults.iconButtonColors( containerColor = colorResource(id = R.color.btn_primary), contentColor = Color.White ), onClick = { chatViewModel.sendMessage(message = chatBoxValue.text, user = "user") chatBoxValue = TextFieldValue("") coroutineScope.launch { listState.animateScrollToItem(index = 30) } } ) { Icon( painter = painterResource(id = R.drawable.ic_send), contentDescription = null, modifier = Modifier.size(25.dp) ) } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/presentation/component/ChatBox.kt
2632215884
package com.thezayin.chatbottesting.presentation import android.os.Build import androidx.annotation.RequiresExtension import androidx.compose.foundation.background import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.hilt.navigation.compose.hiltViewModel import com.thezayin.chatbottesting.R import com.thezayin.chatbottesting.presentation.component.ChatBox import com.thezayin.chatbottesting.presentation.component.MessageBody import com.thezayin.chatbottesting.presentation.component.TopBar @OptIn(ExperimentalComposeUiApi::class) @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) @Composable fun ChatScreen() { val chatViewModel: ChatViewModel = hiltViewModel() val listState = rememberLazyListState() Scaffold(modifier = Modifier .fillMaxSize(), containerColor = colorResource(id = R.color.white), topBar = { TopBar(modifier = Modifier, title = "Chat Bot") {} }, bottomBar = { ChatBox( modifier = Modifier, chatViewModel = chatViewModel, listState = listState ) } ) { padding -> LazyColumn( modifier = Modifier .fillMaxWidth() .background(color = colorResource(id = R.color.white)) .padding(padding), contentPadding = PaddingValues(), state = listState ) { items(chatViewModel._messageState.size) { message -> MessageBody(message = chatViewModel._messageState[message]) } } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/presentation/ChatScreen.kt
2748391254
package com.thezayin.chatbottesting.presentation import android.os.Build import android.util.Log import androidx.annotation.RequiresExtension import androidx.compose.runtime.mutableStateListOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.domain.usecase.MessageUseCases import com.thezayin.chatbottesting.utils.Response import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ChatViewModel @Inject constructor( private val useCase: MessageUseCases ) : ViewModel() { var _messageState = mutableStateListOf<Message>() private set @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) fun sendMessage(message: String, user: String) { _messageState.add(Message(sender = user, cnt = message)) viewModelScope.launch { useCase.botUseCase(message).collect { response -> when (response) { is Response.Success -> { _messageState.add( response.data.copy( sender = "bot", cnt = response.data.cnt ) ) Log.d("ChatViewModel", "sendMessage: ${_messageState}") } is Response.Failure -> { Log.d("ChatViewModel", "sendMessage: ${response.e}") } is Response.Loading -> { Log.d("ChatViewModel", "sendMessage: ${response}") } } } } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/presentation/ChatViewModel.kt
2744056827
package com.au.demoformtu import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.au.demoformtu", appContext.packageName) } }
DemoFoMtu/app/src/androidTest/java/com/au/demoformtu/ExampleInstrumentedTest.kt
3323810277
package com.au.demoformtu import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
DemoFoMtu/app/src/test/java/com/au/demoformtu/ExampleUnitTest.kt
1279184186
package com.au.demoformtu import android.annotation.SuppressLint import android.bluetooth.BluetoothManager import android.content.Context import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.au.demoformtu.BlePermissionHelp.blePermissions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.Locale class MainActivity : AppCompatActivity() { companion object { const val TAG = "DemoMtu" var logChangeCallback:IShowTextCallback? = null private val logs = mutableListOf<String>() fun updateLog(log:String, clearLog:Boolean = false) { val sb = StringBuilder() synchronized(logs) { if (clearLog) { logs.clear() } logs.add(log) logs.forEach { sb.append(it).append("\n\n") } } logChangeCallback?.onText(sb.toString()) } var inputAddress:String? = null } lateinit var bluetoothManager: BluetoothManager private val blePermissionHelper = multiplePermissionsForResult() val activityHelper = activityForResult() private val scanDevice = ScanBluetoothDevice(this) private lateinit var showText:TextView private lateinit var editText:EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager setContentView(R.layout.activity_main) showText = findViewById(R.id.showText) editText = findViewById(R.id.edit) findViewById<Button>(R.id.sureBtn).setOnClickListener { val address = editText.text.toString().uppercase(Locale.ROOT) inputAddress = address saveAddressToSp(address) checkPermission(true) } logChangeCallback = object : IShowTextCallback { override fun onText(str: String) { lifecycleScope.launch { showText.text = str } } } } private var isResumeCount = 0 override fun onResume() { super.onResume() if (isResumeCount == 0) { val address = readAddressFromSp()?.uppercase(Locale.ROOT) if (!address.isNullOrEmpty()) { editText.setText(address) inputAddress = address } checkPermission(true) } isResumeCount++ } private fun checkPermission(jumpToApp:Boolean) { if (BlePermissionHelp.isPermissionGrant(this)) { showText.text = "Has Permission, start ble Scan..." startBleScan() } else { val canShow = BlePermissionHelp.canShowRequestDialogUi(this) Log.w(TAG, "request permission!!! canShowDialog $canShow") showText.text = "request permission!!! canShowDialog $canShow" if (!canShow) { showText.text = "no permission!!!It will jump to appDetail in 5s..." Toast.makeText(this, "$TAG Please give the bluetooth permission!", Toast.LENGTH_LONG).show() if (jumpToApp) { lifecycleScope.launch { delay(5000) activityHelper.jumpToAppDetail(this@MainActivity) { checkPermission(false) } } } } else { BlePermissionHelp.requestPermission2(blePermissionHelper, blePermissions) { Log.w(TAG, "request permission... $it") if (it) { startBleScan() } } } } } @SuppressLint("MissingPermission") private fun startBleScan() { Log.w(TAG, "start ble Scan! $inputAddress") lifecycleScope.launch(Dispatchers.IO) { delay(3000) val isSuc = scanDevice.scan(bluetoothManager) if (isSuc) { updateLog("start ble Scan! $inputAddress", true) } else { updateLog("start ble Scan! no inputAddress.", true) } } } private fun saveAddressToSp(address:String) { val sp = this.getSharedPreferences("save_address", Context.MODE_PRIVATE) sp.edit().putString("address", address).apply() } private fun readAddressFromSp(): String? { val sp = this.getSharedPreferences("save_address", Context.MODE_PRIVATE) return sp.getString("address", "") } }
DemoFoMtu/app/src/main/java/com/au/demoformtu/MainActivity.kt
3332445558
package com.au.demoformtu import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.provider.Settings import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultCallback import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityOptionsCompat import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner fun LifecycleOwner.multiplePermissionsForResult() = activityResultHelper(lifecycle, ActivityResultContracts.RequestMultiplePermissions()) fun LifecycleOwner.permissionForResult() = activityResultHelper(lifecycle, ActivityResultContracts.RequestPermission()) fun LifecycleOwner.activityForResult() = activityResultHelper(lifecycle, ActivityResultContracts.StartActivityForResult()) fun <I, O> activityResultHelper( lifecycle: Lifecycle, resultContract: ActivityResultContract<I, O> ) = ActivityResultHelper(resultContract).also { lifecycle.addObserver(it) } open class ActivityResultHelper<I, O>(val resultContract: ActivityResultContract<I, O>) : DefaultLifecycleObserver, ActivityResultCallback<O> { private var launcher: ActivityResultLauncher<I>? = null val resultLauncher get() = launcher private var onResult: ((O) -> Unit)? = null override fun onCreate(owner: LifecycleOwner) { super.onCreate(owner) launcher = when (owner) { is AppCompatActivity -> { owner.registerForActivityResult(resultContract, this) } is Fragment -> { owner.registerForActivityResult(resultContract, this) } else -> { null } } } override fun onDestroy(owner: LifecycleOwner) { super.onDestroy(owner) onResult = null launcher?.unregister() launcher = null } override fun onActivityResult(result: O) { onResult?.invoke(result) } fun launch( intent: I, option: ActivityOptionsCompat? = null, block: (O) -> Unit ) { this.onResult = block launcher?.launch(intent, option) } } fun String.hasPermission(context: Context): Boolean { return ContextCompat.checkSelfPermission( context.applicationContext, this ) == PackageManager.PERMISSION_GRANTED } fun List<String>.checkPermission(context: Context): MutableList<String> { val noPermission = mutableListOf<String>() forEach { if (!it.hasPermission(context)) { noPermission.add(it) } } return noPermission } fun List<String>.hasPermission(context: Context): Boolean { return checkPermission(context).isEmpty() } fun Array<String>.checkPermission(context: Context): MutableList<String> { val noPermission = mutableListOf<String>() forEach { if (!it.hasPermission(context)) { noPermission.add(it) } } return noPermission } fun Array<String>.hasPermission(context: Context): Boolean { return checkPermission(context).isEmpty() } fun ActivityResultHelper<Intent, ActivityResult>.jumpToAppDetail(appContext: Context, afterBackAppBlock:((ActivityResult)->Unit)? = null) { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.fromParts("package", appContext.packageName, null) launch(intent) { afterBackAppBlock?.invoke(it) } }
DemoFoMtu/app/src/main/java/com/au/demoformtu/ActivityResultUtil.kt
2991354304
package com.au.demoformtu import android.annotation.SuppressLint import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothProfile import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch import java.util.UUID import android.util.Log import com.au.demoformtu.MainActivity.Companion.updateLog class GattCallback(val activity: AppCompatActivity) : BluetoothGattCallback() { val UUID_WRITE_CHARACTERISTIC = UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb") val UUID_NOTIFICATION_CHARACTERISTIC = UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb") val UUID_SERVICE = UUID.fromString("0000ffff-0000-1000-8000-00805f9b34fb") @SuppressLint("MissingPermission") override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) { super.onConnectionStateChange(gatt, status, newState) val isSuc = status == BluetoothGatt.GATT_SUCCESS updateLog("onConnectionStateChange() status $status, GATT_SUCCESS $isSuc, newState $newState") if (isSuc) { if (newState == BluetoothProfile.STATE_CONNECTED) { gatt!!.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH) gatt.discoverServices() } } } @SuppressLint("MissingPermission") override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) { super.onServicesDiscovered(gatt, status) var service: BluetoothGattService? = null var writeChar: BluetoothGattCharacteristic? = null var notifyChar: BluetoothGattCharacteristic? = null val isSuc = status == BluetoothGatt.GATT_SUCCESS updateLog("onServicesDiscovered() status $status success:$isSuc") if (isSuc) { service = gatt!!.getService(UUID_SERVICE) if (service != null) { writeChar = service.getCharacteristic(UUID_WRITE_CHARACTERISTIC) notifyChar = service.getCharacteristic(UUID_NOTIFICATION_CHARACTERISTIC) if (notifyChar != null) { gatt.setCharacteristicNotification(notifyChar, true) } } activity.lifecycleScope.launch { val mtu: Int = 251 updateLog("requestMtu() $mtu") Log.w(MainActivity.TAG, "try to requestMtu >>> try to requestMtu") val requestMtu = gatt!!.requestMtu(mtu) updateLog("requestMtu() isSuccess $requestMtu") Log.w(MainActivity.TAG, "requestMtu() isSuccess $requestMtu") } } } override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) { super.onMtuChanged(gatt, mtu, status) Log.w(MainActivity.TAG, "onMtuChanged() status=$status, mtu= $mtu") updateLog("onMtuChanged() status=$status, mtu= $mtu") } }
DemoFoMtu/app/src/main/java/com/au/demoformtu/GattCallback.kt
299486664
package com.au.demoformtu import android.Manifest import android.content.Context import android.os.Build import androidx.core.app.ActivityCompat import androidx.fragment.app.FragmentActivity object BlePermissionHelp { val blePermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) arrayOf( Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT,) else arrayOf( Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION,) fun canShowRequestDialogUi(activity: FragmentActivity) : Boolean{ for (permission in blePermissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { return true } } return false } inline fun safeRun( helper: ActivityResultHelper<Array<String>, Map<String, @JvmSuppressWildcards Boolean>>, crossinline block: () -> Unit ) { requestPermission(helper, permissionList = blePermissions) { block.invoke() } } fun isPermissionGrant(context: Context): Boolean { return blePermissions.hasPermission(context) } fun requestPermission( permission: ActivityResultHelper<Array<String>, Map<String, @JvmSuppressWildcards Boolean>>, permissionList: Array<String>, block: () -> Unit ) { permission.launch(permissionList) { var hasPermission = false for (entry in it) { if (!entry.value) { hasPermission = false break } else { hasPermission = true } } if (hasPermission) block.invoke() } } fun requestPermission2( permission: ActivityResultHelper<Array<String>, Map<String, @JvmSuppressWildcards Boolean>>, permissionList: Array<String>, block: (Boolean) -> Unit ) { permission.launch(permissionList) { var hasPermission = false for (entry in it) { if (!entry.value) { hasPermission = false break } else { hasPermission = true } } block.invoke(hasPermission) } } }
DemoFoMtu/app/src/main/java/com/au/demoformtu/BlePermissionHelp.kt
1319149393
package com.au.demoformtu import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.os.Build import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.au.demoformtu.MainActivity.Companion.updateLog import kotlinx.coroutines.delay import java.util.Locale class ScanBluetoothDevice(private val activity: AppCompatActivity) { @SuppressLint("MissingPermission") suspend fun scan(bluetoothManager: BluetoothManager) : Boolean{ var address = MainActivity.inputAddress ?: return false address = address.uppercase(Locale.ROOT) val bluetoothDevice = getBluetoothDevice(bluetoothManager, address, true) Log.d(MainActivity.TAG, "bluetoothDevice $address device:${bluetoothDevice?.address}") updateLog("bluetoothDevice $address device:${bluetoothDevice?.address}") val gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { bluetoothDevice?.connectGatt(activity, false, GattCallback(activity), BluetoothDevice.TRANSPORT_LE) } else { bluetoothDevice?.connectGatt(activity, false, GattCallback(activity)) } return true } @SuppressLint("MissingPermission") private suspend fun getBluetoothDevice(bluetoothManager: BluetoothManager, address: String, isNeedDiscover: Boolean = true): BluetoothDevice? { val adapter = bluetoothManager.adapter if (!adapter.isEnabled) return null if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return null if (isNeedDiscover) { try { if (!adapter.isDiscovering) { adapter.startDiscovery() delay(2000L) //adapter.cancelDiscovery() adapter.getRemoteDevice(address) }else{ adapter.getRemoteDevice(address) } } catch (e:Exception) { e.printStackTrace() } } return adapter.getRemoteDevice(address) } }
DemoFoMtu/app/src/main/java/com/au/demoformtu/ScanBluetoothDevice.kt
1020709130
package com.au.demoformtu interface IShowTextCallback { fun onText(str:String) }
DemoFoMtu/app/src/main/java/com/au/demoformtu/IShowTextCallback.kt
2602215615
package org.redsxi.bool class Bool(private val bool: Boolean) { companion object { @JvmField val TRUE = Bool(true) @JvmField val FALSE = Bool(false) } fun get(): Boolean = bool }
ctplus/src/main/kotlin/org/redsxi/bool/Bool.kt
451293648
package org.redsxi.mc.ctplus.mapping import net.minecraft.network.chat.Component import org.redsxi.mc.ctplus.modId object Text { const val BLOCK = "block" const val CARD = "card" const val GUI = "gui" const val TOOLTIP = "tooltip" const val ITEM_GROUP = "itemGroup" @JvmStatic fun translatable(type: String, modId: String, name: String, vararg objects: Any): Component = Component.translatable("$type.$modId.$name", *objects) @JvmStatic fun literal(str: String): Component = Component.literal(str) @JvmStatic fun translatable(type: String, name: String, vararg objects: Any): Component = translatable(type, modId, name, *objects) @JvmStatic fun empty(): Component = literal("") }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/mapping/Text.kt
1187837734
package org.redsxi.mc.ctplus.mapping import net.fabricmc.fabric.impl.itemgroup.ItemGroupHelper import net.minecraft.core.Registry import net.minecraft.core.registries.BuiltInRegistries import net.minecraft.resources.ResourceLocation import net.minecraft.world.item.CreativeModeTab import net.minecraft.world.item.Item import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.entity.BlockEntityType object RegistryMapper { private fun getBlockRegistry(): Registry<Block> = BuiltInRegistries.BLOCK private fun getBlockEntityTypeRegistry(): Registry<BlockEntityType<*>> = BuiltInRegistries.BLOCK_ENTITY_TYPE private fun getItemRegistry(): Registry<Item> = BuiltInRegistries.ITEM private fun <T> register(registry: Registry<T>, location: ResourceLocation, item: T & Any): T = Registry.register(registry, location, item) fun registerBlock(location: ResourceLocation, item: Block): Block = register(getBlockRegistry(), location, item) fun registerBlockEntityType(location: ResourceLocation, item: BlockEntityType<*>): BlockEntityType<*> = register( getBlockEntityTypeRegistry(), location, item) fun registerItem(location: ResourceLocation, item: Item): Item = register(getItemRegistry(), location, item) fun registerItemGroup(location: ResourceLocation, item: CreativeModeTab) = ItemGroupHelper.appendItemGroup(item) }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/mapping/RegistryMapper.kt
3306639060
package org.redsxi.mc.ctplus.mapping import net.minecraft.core.BlockPos import net.minecraft.server.level.ServerLevel import net.minecraft.util.RandomSource import net.minecraft.world.level.block.HorizontalDirectionalBlock import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.level.material.Material import net.minecraft.world.level.material.MaterialColor abstract class BarrierBlockMapper : HorizontalDirectionalBlock(Properties.of(Material.METAL, MaterialColor.COLOR_GRAY).requiresCorrectToolForDrops().strength(2.0F)) { override fun tick( blockState: BlockState, serverLevel: ServerLevel, blockPos: BlockPos, randomSource: RandomSource ) { tick(blockState, serverLevel, blockPos) } open fun tick(state: BlockState, level: ServerLevel, pos: BlockPos) = Unit }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/mapping/BarrierBlockMapper.kt
2402693264
package org.redsxi.mc.ctplus.mapping import net.minecraft.world.item.CreativeModeTab import net.minecraft.world.item.Item import net.minecraft.world.item.ItemStack import org.redsxi.mc.ctplus.mapping.Text.ITEM_GROUP object ItemGroupMapper { @JvmStatic fun builder(id: String, icon: Item, items: (CreativeModeTab.Output) -> Unit): CreativeModeTab.Builder { return CreativeModeTab.builder(CreativeModeTab.Row.TOP, 0) .title(Text.translatable(ITEM_GROUP, id)) .icon{ItemStack(icon)} .displayItems{_, output -> items(output) } } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/mapping/ItemGroupMapper.kt
1217504112
package org.redsxi.mc.ctplus.card import net.minecraft.network.chat.Component import net.minecraft.resources.ResourceLocation import net.minecraft.world.item.ItemStack import org.redsxi.mc.ctplus.CTPlusRegistries import org.redsxi.mc.ctplus.data.CardContext import org.redsxi.mc.ctplus.data.CardData import org.redsxi.mc.ctplus.idOf import org.redsxi.mc.ctplus.item.ItemCard import org.redsxi.mc.ctplus.mapping.Text import org.redsxi.mc.ctplus.mapping.Text.TOOLTIP import org.redsxi.mc.ctplus.util.MTRTranslation @Suppress("UNCHECKED_CAST") abstract class Card<CardDataT : CardData, CardT : Card<CardDataT, CardT>> { private var itemOpt: ItemCard<CardT, CardDataT>? = null val item: ItemCard<CardT, CardDataT> get() { return itemOpt ?: throw NullPointerException("Item of card wasn't initialized") } fun initItem() { if(itemOpt != null) return itemOpt = ItemCard(this as CardT) } val id: ResourceLocation get() = CTPlusRegistries.CARD.getItemID(this) open fun getCardItemTextureLocation(): ResourceLocation = idOf("item/card/white") fun getCardFrontTextureLocation(): ResourceLocation = idOf("item/card/white_f") fun getCardBackTextureLocation(): ResourceLocation = idOf("item/card/white_b") abstract fun balance(data: CardDataT): Int open fun discountFactor(): Float = 1F abstract fun payImpl(data: CardDataT, price: Int): Boolean abstract fun rechargeImpl(data: CardDataT, amount: Int): Boolean /** * Tips 已确认是否有足够的余额/是否可预支 */ fun pay(data: CardDataT, price: Int): Boolean { val actualPrice = (price * discountFactor()).toInt() return if(actualPrice <= balance(data) || (canOverdraft(data) && balance(data) >= 0)) { payImpl(data, actualPrice) } else false } fun recharge(data: CardDataT, amount: Int): Boolean { if(canRecharge(data)) { return rechargeImpl(data, amount) } return false } abstract fun canOverdraft(data: CardDataT): Boolean abstract fun canRecharge(data: CardDataT): Boolean abstract fun isValid(data: CardDataT): Boolean open fun appendCardInformation(data: CardDataT, list: MutableList<Component>) { if(data.isEntered) { list.add( Text.translatable( TOOLTIP, "enter_at_station", MTRTranslation.getTranslation(data.entryStationName) as Any ) ) } } override fun toString(): String { return javaClass.simpleName } fun context(stack: ItemStack): CardContext<CardDataT, CardT> = CardData.deserialize(stack) }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/card/Card.kt
3281981209
package org.redsxi.mc.ctplus.card import org.redsxi.mc.ctplus.data.CardData class WhiteCard : Card<CardData, WhiteCard>() { override fun balance(data: CardData): Int = 0 override fun payImpl(data: CardData, price: Int): Boolean = false override fun rechargeImpl(data: CardData, amount: Int): Boolean = false override fun canOverdraft(data: CardData): Boolean = false override fun canRecharge(data: CardData): Boolean = false override fun isValid(data: CardData): Boolean = false }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/card/WhiteCard.kt
2960364933
package org.redsxi.mc.ctplus.card import net.minecraft.network.chat.Component import net.minecraft.resources.ResourceLocation import org.redsxi.mc.ctplus.data.PrepaidCardData import org.redsxi.mc.ctplus.idOf import org.redsxi.mc.ctplus.mapping.Text import org.redsxi.mc.ctplus.mapping.Text.TOOLTIP import org.redsxi.mc.ctplus.util.Date import org.redsxi.mc.ctplus.util.Time class PrepaidCard : Card<PrepaidCardData, PrepaidCard>() { /* DEPRECATED CODE 2024-3-4 private val valid: Boolean get() { return Time.millis < lastRechargeTime + EXPIRE_TIME } override fun appendCardInformation(list: MutableList<Component>) { super.appendCardInformation(list) list.add(Text.translatable(TOOLTIP, "card_balance", balance)) list.add(Text.translatable(TOOLTIP, "card_last_recharge_time", Date[lastRechargeTime] as Any)) if(!valid) { list.add(Text.translatable(TOOLTIP, "card_invalid")) } } */ override fun getCardItemTextureLocation(): ResourceLocation { return idOf("item/card/prepaid") } override fun isValid(data: PrepaidCardData) = Time.millis < data.lastRechargeTime + EXPIRE_TIME override fun canRecharge(data: PrepaidCardData) = isValid(data) override fun canOverdraft(data: PrepaidCardData) = isValid(data) override fun rechargeImpl(data: PrepaidCardData, amount: Int): Boolean { val b = data.balance data.balance += amount return b < data.balance } override fun payImpl(data: PrepaidCardData, price: Int): Boolean { val b = data.balance data.balance -= price return b >= data.balance } override fun balance(data: PrepaidCardData) = data.balance override fun appendCardInformation(data: PrepaidCardData, list: MutableList<Component>) { super.appendCardInformation(data, list) list.add(Text.translatable(TOOLTIP, "card_balance", data.balance)) list.add(Text.translatable(TOOLTIP, "card_last_recharge_time", Date[data.lastRechargeTime] as Any)) if(!isValid(data)) list.add(Text.translatable(TOOLTIP, "card_invalid")) } companion object { const val EXPIRE_TIME: Long = 0x134FD9000 } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/card/PrepaidCard.kt
339665699
package org.redsxi.mc.ctplus.card import net.minecraft.network.chat.Component import net.minecraft.resources.ResourceLocation import org.redsxi.mc.ctplus.data.SingleJourneyCardData import org.redsxi.mc.ctplus.idOf import org.redsxi.mc.ctplus.mapping.Text class SingleJourneyCard : Card<SingleJourneyCardData, SingleJourneyCard>() { /* DEPRECATED CODE AT 2024-3-3 -CTPLUS var price: Int = 2 private var isUsed = true override fun balance(): Int = if(isUsed) { 0 } else { price } override fun payImpl(price: Int): Boolean { if(isUsed) return false isUsed = true return true } override fun rechargeImpl(amount: Int) = false override fun canOverdraft() = false override fun canRecharge() = false override fun isValid() = !isUsed override fun getCardItemTextureLocation(): ResourceLocation { return idOf("item/card/single_journey") } override fun loadData(nbt: CompoundTag) { price = nbt.getInt("Price") isUsed = nbt.getBoolean("IsUsed") } override fun saveData(nbt: CompoundTag): CompoundTag { nbt.putInt("Price", price) nbt.putBoolean("IsUsed", isUsed) return nbt } override fun appendCardInformation(list: MutableList<Component>) { super.appendCardInformation(list) list.add(Text.translatable(Text.TOOLTIP, "price", price)) if(isUsed) { list.add(Text.translatable(Text.TOOLTIP, "card_is_used")) } } */ override fun balance(data: SingleJourneyCardData): Int = if(data.isUsed) 0 else data.price override fun payImpl(data: SingleJourneyCardData, price: Int): Boolean { data.isUsed = true return true } override fun rechargeImpl(data: SingleJourneyCardData, amount: Int): Boolean = false override fun canOverdraft(data: SingleJourneyCardData): Boolean = false override fun canRecharge(data: SingleJourneyCardData): Boolean = false override fun isValid(data: SingleJourneyCardData): Boolean = !data.isUsed override fun appendCardInformation(data: SingleJourneyCardData, list: MutableList<Component>) { super.appendCardInformation(data, list) list.add(Text.translatable(Text.TOOLTIP, "price", data.price)) if(data.isUsed) { list.add(Text.translatable(Text.TOOLTIP, "card_is_used")) } } override fun getCardItemTextureLocation(): ResourceLocation { return idOf("item/card/single_journey") } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/card/SingleJourneyCard.kt
574419092
package org.redsxi.mc.ctplus.core import net.minecraft.core.BlockPos import net.minecraft.sounds.SoundEvent import net.minecraft.sounds.SoundSource import net.minecraft.world.entity.player.Player import net.minecraft.world.level.Level import net.minecraft.world.scores.Score import net.minecraft.world.scores.criteria.ObjectiveCriteria import org.redsxi.mc.ctplus.blockentity.BlockEntityTicketBarrierPayDirect import org.redsxi.mc.ctplus.mapping.Text object PassManager { fun onEntityPass(pos: BlockPos, level: Level, player: Player, passSound: SoundEvent): Boolean { addObjective(level) val be = level.getBlockEntity(pos) if(be is BlockEntityTicketBarrierPayDirect) { val price = be.price val balanceScore = getScore(level, player) if(balanceScore.score < price) { player.displayClientMessage( Text.translatable( Text.GUI, "mtr", "insufficient_balance", balanceScore.score ), true ) return false } balanceScore.add((0 - price)) player.displayClientMessage( Text.translatable(Text.GUI, "enter_barrier", price), true ) level.playSound(player, pos, passSound, SoundSource.BLOCKS) return true } return false } private fun addObjective(level: Level) { try { level.scoreboard.addObjective( "mtr_balance", ObjectiveCriteria.DUMMY, Text.literal("\ufefa Balance 余额 \ufefa"), ObjectiveCriteria.RenderType.INTEGER ) } catch (_: Exception) { } } private fun getScore(level: Level, player: Player): Score { val objective = level.scoreboard.getObjective("mtr_balance") ?: throw RuntimeException("WTF") return level.scoreboard.getOrCreatePlayerScore(player.gameProfile.name,objective) } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/core/PassManager.kt
2058764905
package org.redsxi.mc.ctplus.core import net.minecraft.core.BlockPos import net.minecraft.sounds.SoundEvent import net.minecraft.sounds.SoundSource import net.minecraft.world.entity.player.Player import net.minecraft.world.item.ItemStack import net.minecraft.world.level.Level import org.redsxi.bool.Bool import org.redsxi.mc.ctplus.blockentity.BlockEntityTicketBarrierPayDirect import org.redsxi.mc.ctplus.card.Card import org.redsxi.mc.ctplus.core.TransitPlus.PassType.* import org.redsxi.mc.ctplus.data.CardContext import org.redsxi.mc.ctplus.data.CardData import org.redsxi.mc.ctplus.item.ItemCard import org.redsxi.mc.ctplus.mapping.Text import org.redsxi.mc.ctplus.mapping.Text.GUI import org.redsxi.mc.ctplus.util.MTROptionalData import org.redsxi.mc.ctplus.util.MTRTranslation import kotlin.math.abs object TransitPlus { private const val PRICE_RADIX = 2 private fun encodeZone(zone: Int): Float = Float.fromBits(zone) private fun decodeZone(zone: Float): Int = zone.toBits() private fun price(entryZone: Int, exitZone: Int): Int { return abs(entryZone - exitZone) * PRICE_RADIX } /*/** * @see pass */ @Deprecated("Use another one") fun pass(player: Player, price: Int, position: BlockPos, currentLevel: Level, passSound: SoundEvent): Boolean { val itemStack = player.mainHandItem if(itemStack == ItemStack.EMPTY) { player.displayClientMessage(Text.translatable(GUI, "hold_card_to_pass"), true) return false } val item = itemStack.item if (item is ItemCard) { val card = item.card var compound = itemStack.tag if(compound == null) { compound = card.createData() } card.loadData(compound) return if(card.isValid()) { if(card.pay(price)) { player.displayClientMessage(card.getPassMessage(), true) itemStack.tag = card.createData() currentLevel.playSound(player, position, passSound, SoundSource.BLOCKS) true } else { player.displayClientMessage(Text.translatable(GUI, "insufficient_balance", card.balance()), true) false } } else { player.displayClientMessage(Text.translatable(GUI, "card_invalid"), true) false } } else { player.displayClientMessage(Text.translatable(GUI, "hold_card_to_pass"), true) return false } }*/ enum class PassType { PAY_DIRECT, ENTRY, EXIT } private fun <CDT: CardData, CT: Card<CDT, CT>> pass(cardCtx: CardContext<CDT, CT>, price: Int, player: Player, passFunc: () -> Unit): Bool = if(cardCtx.card.pay(cardCtx.data, price)) { player.displayClientMessage(Text.translatable(GUI, "gui.cgcem.enter_barrier", price), true) passFunc() Bool.TRUE } else { player.displayClientMessage(Text.translatable(GUI, "insufficient_balance", cardCtx.card.balance(cardCtx.data)), true) Bool.FALSE } private fun <CDT: CardData, CT: Card<CDT, CT>> enter(cardCtx: CardContext<CDT, CT>, zone: Int, stationName: String, stationNameTranslated: String, player: Player, passFunc: () -> Unit): Bool { if(cardCtx.card.balance(cardCtx.data) < 0 && !cardCtx.card.canOverdraft(cardCtx.data)) { player.displayClientMessage(Text.translatable(GUI, "insufficient_balance", cardCtx.card.balance(cardCtx.data)), true) return Bool.FALSE } if(cardCtx.data.isEntered) { player.displayClientMessage(Text.translatable(GUI, "card_invalid"), true) return Bool.FALSE } cardCtx.data.entryZoneEncoded = encodeZone(zone) cardCtx.data.entryStationName = stationName cardCtx.data.isEntered = true player.displayClientMessage(Text.translatable(GUI, "entered_station", stationNameTranslated as Any, cardCtx.card.balance(cardCtx.data)), true) passFunc() return Bool.TRUE } private fun <CDT: CardData, CT: Card<CDT, CT>> exit(cardCtx: CardContext<CDT, CT>, zone: Int, stationNameTranslated: String, player: Player, passFunc: () -> Unit): Bool { if(!cardCtx.data.isEntered) { player.displayClientMessage(Text.translatable(GUI, "card_invalid"), true) return Bool.FALSE } val price = price(decodeZone(cardCtx.data.entryZoneEncoded), zone) return if(cardCtx.card.pay(cardCtx.data, price)) { cardCtx.data.isEntered = false player.displayClientMessage(Text.translatable(GUI, "exited_station", stationNameTranslated as Any, price, cardCtx.card.balance(cardCtx.data)), true) passFunc() Bool.TRUE } else { player.displayClientMessage(Text.translatable(GUI, "insufficient_balance", cardCtx.card.balance(cardCtx.data)), true) Bool.FALSE } } fun pass(player: Player, position: BlockPos, world: Level, passSound: SoundEvent, passType: PassType): Bool { val playSoundFunc = { world.playSound(player, position, passSound, SoundSource.BLOCKS) } val stack = player.mainHandItem if (stack == ItemStack.EMPTY) { player.displayClientMessage(Text.translatable(GUI, "hold_card_to_pass"), true) return Bool.FALSE } val item = stack.item if (item is ItemCard<*, *>) { val card = item.card val context = card.context(stack) if(context.isValid()) { val result = when (passType) { PAY_DIRECT -> { val bEntity = world.getBlockEntity(position) if (bEntity is BlockEntityTicketBarrierPayDirect) { val price = bEntity.price pass(context, price, player, playSoundFunc) } else Bool.FALSE // If I forgot to register the block entity } else -> { val stationOptional = MTROptionalData.getStation( MTROptionalData.getRailwayData(world), position ) if(!stationOptional.isPresent) { player.displayClientMessage(Text.translatable(GUI, "barrier_not_inside_the_station"), true) return Bool.FALSE } val station = stationOptional.get() val zone = station.zone when (passType) { ENTRY -> { enter(context, zone, station.name, MTRTranslation.getTranslation(station.name), player, playSoundFunc) //Bool.FALSE } EXIT -> { exit(context, zone, MTRTranslation.getTranslation(station.name), player, playSoundFunc) //Bool.FALSE } else -> Bool.FALSE // Impossible but kotlin tell me to do this } } } context.update() return result } else { context.update() player.displayClientMessage(Text.translatable(GUI, "card_invalid"), true) return Bool.FALSE } } else { player.displayClientMessage(Text.translatable(GUI, "hold_card_to_pass"), true) return Bool.FALSE } } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/core/TransitPlus.kt
3029151641
package org.redsxi.mc.ctplus.util import net.minecraft.resources.ResourceLocation object ResourceLocationUtil { @JvmStatic fun addPrefix(id: ResourceLocation, prefix: String) = ResourceLocation(id.namespace, "$prefix${id.path}") }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/ResourceLocationUtil.kt
349919946
package org.redsxi.mc.ctplus.util import java.text.SimpleDateFormat import java.util.Date object Date { @JvmStatic operator fun get(time: Long): String { val dateFormat = SimpleDateFormat("yyyy:MM:dd HH:mm:ss") val date = Date(time) return dateFormat.format(date) } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/Date.kt
3714716089
package org.redsxi.mc.ctplus.util import net.minecraft.core.BlockPos import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState @SuppressWarnings("any") object BlockEntityTypeUtil { private fun <T : BlockEntity> create(block: Block, blockEntitySupplier: (BlockPos, BlockState) -> T): BlockEntityType<T> { val builder = BlockEntityType.Builder.of(blockEntitySupplier, block) return builder.build(null) } fun <T : BlockEntity> create(block: Block, blockEntityClass: Class<T>, vararg arguments: Any): BlockEntityType<T> { val classArray = ArrayList<Class<out Any>>() classArray.add(BlockPos::class.java) classArray.add(BlockState::class.java) arguments.forEach { classArray.add(it::class.java) } val array = Array<Class<out Any>>(0) {BlockEntityTypeUtil::class.java} val constructor = blockEntityClass.getConstructor(*classArray.toArray(array)) return create( block ) { pos, state -> constructor.newInstance(pos, state, *arguments) } } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/BlockEntityTypeUtil.kt
2539288318
package org.redsxi.mc.ctplus.util import mtr.data.RailwayData import mtr.data.Station import net.minecraft.core.BlockPos import net.minecraft.world.level.Level import java.util.Optional object MTROptionalData { @JvmStatic fun getRailwayData(level: Level): Optional<RailwayData> { val data = RailwayData.getInstance(level) ?: return Optional.empty() return Optional.of(data) } @JvmStatic fun getStation(railwayData: Optional<RailwayData>, position: BlockPos): Optional<Station> { if (!railwayData.isPresent) return Optional.empty() val data = railwayData.get() val station = RailwayData.getStation(data.stations, data.dataCache, position) ?: return Optional.empty() return Optional.of(station) } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/MTROptionalData.kt
1529818448
package org.redsxi.mc.ctplus.util import net.minecraft.core.Direction import net.minecraft.world.level.block.Block import net.minecraft.world.phys.shapes.Shapes import net.minecraft.world.phys.shapes.VoxelShape object FacingUtil { fun getVoxelShapeByDirection( x1: Double, y1: Double, z1: Double, x2: Double, y2: Double, z2: Double, facing: Direction ): VoxelShape { return when (facing) { Direction.NORTH -> Block.box(x1, y1, z1, x2, y2, z2) Direction.EAST -> Block.box(16.0 - z2, y1, x1, 16.0 - z1, y2, x2) Direction.SOUTH -> Block.box(16.0 - x2, y1, 16.0 - z2, 16.0 - x1, y2, 16.0 - z1) Direction.WEST -> Block.box(z1, y1, 16.0 - x2, z2, y2, 16.0 - x1) else -> Shapes.block() } } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/FacingUtil.kt
2875379587
package org.redsxi.mc.ctplus.util interface Time { val millis: Long val seconds: Long companion object : Time { override val millis: Long get() = System.currentTimeMillis() override val seconds: Long get() = millis / 1000 } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/Time.kt
2295816557
package org.redsxi.mc.ctplus.util import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import org.redsxi.mc.ctplus.Variables @Environment(EnvType.CLIENT) object MTRTranslation { @JvmStatic fun getTranslation(name: String): String { val nameArray = name.split("|") if(nameArray.size == 1) return name return nameArray[Variables.translationIndex, 0] } private operator fun List<String>.get(index: Int, defaultIndex: Int): String { if(size <= index) return this[defaultIndex] return this[index] } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/util/MTRTranslation.kt
3667838933
package org.redsxi.mc.ctplus.network import net.fabricmc.fabric.api.networking.v1.FabricPacket import net.fabricmc.fabric.api.networking.v1.PacketType import net.minecraft.network.FriendlyByteBuf import org.redsxi.mc.ctplus.setTranslationIndex class SetTranslationIndexS2CPacket(val index: Int) : FabricPacket { constructor(buf: FriendlyByteBuf) : this(buf.readInt()) override fun write(buf: FriendlyByteBuf) { buf.writeInt(index) } override fun getType(): PacketType<*> = TYPE companion object { @JvmField val TYPE: PacketType<SetTranslationIndexS2CPacket> = PacketType.create(setTranslationIndex){SetTranslationIndexS2CPacket(it)} } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/network/SetTranslationIndexS2CPacket.kt
3082844032
package org.redsxi.mc.ctplus.blockentity import net.minecraft.core.BlockPos import net.minecraft.nbt.CompoundTag import net.minecraft.network.protocol.Packet import net.minecraft.network.protocol.game.ClientGamePacketListener import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.state.BlockState import org.redsxi.bool.Bool import org.redsxi.mc.ctplus.Collections open class BlockEntityTicketBarrierPayDirect(pos: BlockPos, state: BlockState, isTransitPlus: Bool) : BlockEntity( if(isTransitPlus.get()) Collections.BlockEntities.TICKET_BARRIER_PAY_DIRECT_TP else Collections.BlockEntities.TICKET_BARRIER_PAY_DIRECT, pos, state ) { var price: Int = 2 override fun saveAdditional(nbt: CompoundTag) { nbt.putInt("Price", price) super.saveAdditional(nbt) } override fun load(nbt: CompoundTag) { price = nbt.getInt("Price") super.load(nbt) } override fun getUpdatePacket(): Packet<ClientGamePacketListener> { return ClientboundBlockEntityDataPacket.create(this) } override fun getUpdateTag(): CompoundTag { return saveWithoutMetadata() } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/blockentity/BlockEntityTicketBarrierPayDirect.kt
1675384277
package org.redsxi.mc.ctplus import net.minecraft.resources.ResourceLocation const val modId: String = "ctplus" fun idOf(name: String): ResourceLocation = ResourceLocation(modId, name) val ticketBarrierPayDirect = idOf("ticket_barrier_pay_direct") val card = idOf("card") val whiteCard = idOf("white") val singleJourneyCard = idOf("single_journey") val prepaidCard = idOf("prepaid") val ctPlus = idOf("ct_plus") val ticketBarrierEntranceTp = idOf("ticket_barrier_entrance_tp") val ticketBarrierExitTp = idOf("ticket_barrier_exit_tp") val ticketBarrierPayDirectTp = idOf("ticket_barrier_pay_direct_tp") val main = idOf("main") val setTranslationIndex = idOf("set_translation_index")
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/ID.kt
415631013
package org.redsxi.mc.ctplus.item import net.minecraft.network.chat.Component import net.minecraft.world.item.Item import net.minecraft.world.item.ItemStack import net.minecraft.world.item.TooltipFlag import net.minecraft.world.level.Level import org.redsxi.mc.ctplus.CTPlusRegistries import org.redsxi.mc.ctplus.card.Card import org.redsxi.mc.ctplus.data.CardData import org.redsxi.mc.ctplus.mapping.Text import org.redsxi.mc.ctplus.mapping.Text.CARD import org.redsxi.mc.ctplus.mapping.Text.TOOLTIP class ItemCard<CardT : Card<CardDataT, CardT>, CardDataT : CardData>(val card: CardT) : Item(Properties().stacksTo(1)) { override fun appendHoverText( itemStack: ItemStack, level: Level?, list: MutableList<Component>, tooltipFlag: TooltipFlag ) { list.add(Text.translatable(TOOLTIP, "transit_plus_part")) val item = itemStack.item if(item is ItemCard<*, *>) { val card = item.card val context = card.context(itemStack) list.add(Text.empty()) list.add(Text.translatable(TOOLTIP, "card_information")) context.appendCardInformation(list) } } override fun getName(itemStack: ItemStack): Component { val id = CTPlusRegistries.CARD.getItemID(card) return Text.translatable(CARD, id.namespace, id.path) } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/item/ItemCard.kt
1689302913
package org.redsxi.mc.ctplus.model import net.minecraft.resources.ResourceLocation import org.slf4j.LoggerFactory object CardItemModelGenerator { private val LOGGER = LoggerFactory.getLogger("CardItemModelGen") fun generate(icon: ResourceLocation): String { val str = """ { "parent": "item/generated", "textures": { "layer0": "${icon.namespace}:${icon.path}" } } """.trimIndent() LOGGER.debug("Model: $str") return str } }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/model/CardItemModelGenerator.kt
2652541988
package org.redsxi.mc.ctplus.command object CommandContexts { }
ctplus/src/main/kotlin/org/redsxi/mc/ctplus/command/CommandContexts.kt
3148703106