Skip to content

Commit

Permalink
Merge pull request #24 from Infomaniak/support-parallele-html-export
Browse files Browse the repository at this point in the history
Support parallele html export
  • Loading branch information
sirambd authored Jul 9, 2024
2 parents a7d4550 + a1aeb35 commit cf3d88e
Showing 1 changed file with 30 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,15 @@ import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector.CodeInjectio
import com.infomaniak.lib.richhtmleditor.executor.StateSubscriber
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.roundToInt

/**
Expand Down Expand Up @@ -88,6 +95,9 @@ class RichHtmlEditorWebView @JvmOverloads constructor(
updateWebViewHeight = ::updateWebViewHeight,
)

@OptIn(DelicateCoroutinesApi::class)
private val htmlExportCoroutineScope = CoroutineScope(newSingleThreadContext("HtmlExportCoroutine"))

/**
* Flow that is notified everytime a subscribed [EditorStatuses] is updated.
*
Expand All @@ -98,7 +108,9 @@ class RichHtmlEditorWebView @JvmOverloads constructor(
*/
val editorStatusesFlow: Flow<EditorStatuses> by jsBridge::editorStatusesFlow

private var htmlExportCallback: ((html: String) -> Unit)? = null
private var htmlExportCallback: MutableList<((html: String) -> Unit)> = mutableListOf()

private val htmlExportMutex = Mutex()

init {
@SuppressLint("SetJavaScriptEnabled")
Expand Down Expand Up @@ -190,8 +202,15 @@ class RichHtmlEditorWebView @JvmOverloads constructor(
}

fun exportHtml(resultCallback: (html: String) -> Unit) {
htmlExportCallback = resultCallback
jsExecutor.executeWhenDomIsLoaded(JsExecutableMethod("exportHtml"))
htmlExportCoroutineScope.launch {
htmlExportMutex.withLock {
val notYetRunning = htmlExportCallback.isEmpty()
htmlExportCallback.add(resultCallback)
Dispatchers.Main {
if (notYetRunning) jsExecutor.executeWhenDomIsLoaded(JsExecutableMethod("exportHtml"))
}
}
}
}

override fun onSaveInstanceState(): Parcelable {
Expand Down Expand Up @@ -224,8 +243,14 @@ class RichHtmlEditorWebView @JvmOverloads constructor(
}

private fun notifyExportedHtml(html: String) {
htmlExportCallback?.invoke(html)
htmlExportCallback = null
htmlExportCoroutineScope.launch {
htmlExportMutex.withLock {
Dispatchers.Main {
htmlExportCallback.forEach { it.invoke(html) }
}
htmlExportCallback.clear()
}
}
}

private fun requestRectangleOnScreen(left: Int, top: Int, right: Int, bottom: Int) {
Expand Down

0 comments on commit cf3d88e

Please sign in to comment.