Buran/app/src/main/java/corewala/buran/OmniTerm.kt

117 lines
3.0 KiB
Kotlin
Raw Normal View History

2021-12-02 18:11:34 +00:00
package corewala.buran
import android.net.Uri
import java.util.*
const val GEM_SCHEME = "gemini://"
class OmniTerm(private val listener: Listener) {
val history = ArrayList<OppenURI>()
var uri = OppenURI()
var penultimate = OppenURI()
/**
* User input to the 'omni bar' - could be an address or a search term
* @param term - User-inputted term
*/
2022-04-20 19:28:11 +00:00
fun input(term: String, searchbase: String?){
2021-12-02 18:11:34 +00:00
when {
term.contains(" ") -> {
val encoded = Uri.encode(term)
listener.request("$searchbase$encoded")
}
2021-12-02 18:11:34 +00:00
term.startsWith(GEM_SCHEME) && term != GEM_SCHEME -> {
listener.request(term)
return
}
term.contains(".") -> {
listener.request("gemini://${term}")
}
else -> {
val encoded = Uri.encode(term)
2022-04-20 19:28:11 +00:00
listener.request("$searchbase$encoded")
2021-12-02 18:11:34 +00:00
}
}
}
2022-04-20 19:28:11 +00:00
fun search(term: String, searchbase: String?){
2021-12-02 18:11:34 +00:00
val encoded = Uri.encode(term)
2022-04-20 19:28:11 +00:00
listener.request("$searchbase$encoded")
2021-12-02 18:11:34 +00:00
}
fun navigation(link: String) {
navigation(link, true)
}
fun imageAddress(link: String){
navigation(link, false)
}
/**
* A clicked link, could be absolute or relative
* @param link - a Gemtext link
*/
private fun navigation(link: String, invokeListener: Boolean) {
when {
link.startsWith(GEM_SCHEME) -> uri.set(link)
link.startsWith("//") -> uri.set("gemini:$link")
link.startsWith("http://") or link.startsWith("https://") -> {
uri.set(link)
}
link.contains(":") -> listener.openExternal(link)
else -> uri.resolve(link)
2021-12-02 18:11:34 +00:00
}
val address = uri.toString().replace("//", "/").replace(":/", "://")
2021-12-02 18:11:34 +00:00
if(invokeListener) listener.request(address)
println("OmniTerm resolved address: $address")
2021-12-02 18:11:34 +00:00
}
2022-07-29 19:47:33 +00:00
fun getGlobalUri(reference: String): String {
return when {
reference.contains(":") -> reference
reference.startsWith("//") -> "gemini:$reference"
else -> uri.resolve(reference, false)
2022-07-29 19:47:33 +00:00
}
}
2021-12-02 18:11:34 +00:00
fun reset(){
uri = penultimate.copy()
}
fun set(address: String) {
penultimate.set(address)
uri.set(address)
if (history.isEmpty() || history.last().toString() != address) {
history.add(uri.copy())
}
}
fun getCurrent(): String {
return if(history.size > 0){
history.last().toString()
}else{
""
}
2021-12-02 18:11:34 +00:00
}
fun canGoBack(): Boolean {
return history.size > 1
}
fun goBack(): String {
history.removeLast()
return history.last().toString()
}
fun clearCache() {
history.clear()
}
2021-12-02 18:11:34 +00:00
interface Listener{
fun request(address: String)
fun openExternal(address: String)
2021-12-02 18:11:34 +00:00
}
}