Yokan / rebuild
Course 1 8624561

PlatformWebView.desktop.kt

composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/PlatformWebView.desktop.kt

implementation358 lines
1package eu.friedcutlet.yokan.ui.screens.webview23import androidx.compose.foundation.layout.Arrangement4import androidx.compose.foundation.layout.Box5import androidx.compose.foundation.layout.Column6import androidx.compose.foundation.layout.fillMaxSize7import androidx.compose.foundation.layout.padding8import androidx.compose.material.icons.Icons9import androidx.compose.material.icons.filled.OpenInBrowser10import androidx.compose.material3.Button11import androidx.compose.material3.Icon12import androidx.compose.material3.MaterialTheme13import androidx.compose.material3.Text14import androidx.compose.runtime.Composable15import androidx.compose.runtime.DisposableEffect16import androidx.compose.runtime.LaunchedEffect17import androidx.compose.runtime.getValue18import androidx.compose.runtime.mutableStateOf19import androidx.compose.runtime.remember20import androidx.compose.runtime.setValue21import androidx.compose.ui.Alignment22import androidx.compose.ui.Modifier23import androidx.compose.ui.awt.SwingPanel24import androidx.compose.ui.text.style.TextAlign25import androidx.compose.ui.text.style.TextOverflow26import androidx.compose.ui.unit.dp27import eu.friedcutlet.yokan.domain.ProfileId28import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService29import eu.friedcutlet.yokan.services.http.isCloudflareChallengePageTitle30import eu.friedcutlet.yokan.services.http.cookies.CookieJar31import eu.friedcutlet.yokan.services.system.openSystemBrowser32import java.awt.BorderLayout33import java.io.File34import java.net.CookieHandler35import java.net.CookieManager36import java.net.CookiePolicy37import java.net.HttpCookie38import java.net.URI39import javafx.application.Platform40import javafx.concurrent.Worker41import javafx.embed.swing.JFXPanel42import javafx.scene.Scene43import javafx.scene.web.WebView44import javax.swing.JPanel45import javax.swing.SwingUtilities4647@Composable48internal actual fun RenderPlatformWebView(49    url: String,50    cookieJar: CookieJar,51    modifier: Modifier,52    userAgent: String?,53    isObscuredByOverlay: Boolean,54    onNavigated: (String) -> Unit,55    onLoadingProgress: (Float) -> Unit,56    // Unused: JavaFX follows redirects without exposing them, so loopback callbacks are served for real57    // (mangayomiOAuthRedirectUri) and reported through onNavigated once they finish loading.58    @Suppress("UNUSED_PARAMETER") interceptUrlPrefix: String?,59    onVerificationRequired: (String) -> Unit,60) {61    var errorMessage by remember { mutableStateOf<String?>(null) }62    val message = errorMessage63    if (message != null) {64        DesktopWebViewStatus(65            url = url,66            message = message,67            modifier = modifier,68            onLoadingProgress = onLoadingProgress,69            onOpenBrowser = { if (cookieJar.canUseBrowserStorage) openSystemBrowser(url) },70        )71        return72    }73    if (isObscuredByOverlay) {74        Box(modifier = modifier.fillMaxSize())75        return76    }7778    // Owned by this SwingPanel's slot: leaving composition (screen closed or an79    // overlay hiding the heavyweight panel) must shut the JavaFX engine down.80    val panelRef = remember { java.util.concurrent.atomic.AtomicReference<JavaFxWebViewPanel?>(null) }81    DisposableEffect(panelRef) {82        onDispose { panelRef.getAndSet(null)?.dispose() }83    }84    SwingPanel(85        modifier = modifier.fillMaxSize(),86        factory = {87            runCatching {88                JavaFxWebViewPanel(89                    url = url,90                    cookieJar = cookieJar,91                    userAgent = userAgent,92                    onNavigated = onNavigated,93                    onLoadingProgress = onLoadingProgress,94                    onVerificationRequired = onVerificationRequired,95                ).also(panelRef::set)96            }.getOrElse { error ->97                val cause = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }98                errorMessage = "Desktop WebView failed to start: $cause"99                fallbackPanel()100            }101        },102        update = { component ->103            (component as? JavaFxWebViewPanel)?.update(104                url = url,105                userAgent = userAgent,106                onNavigated = onNavigated,107                onLoadingProgress = onLoadingProgress,108                onVerificationRequired = onVerificationRequired,109            )110        },111    )112}113114private class JavaFxWebViewPanel(115    url: String,116    private val cookieJar: CookieJar,117    userAgent: String?,118    onNavigated: (String) -> Unit,119    onLoadingProgress: (Float) -> Unit,120    onVerificationRequired: (String) -> Unit,121) : JPanel(BorderLayout()) {122    private val jfxPanel = JFXPanel()123    private var webView: WebView? = null124    private var requestedUrl: String? = null125    private var requestedUserAgent: String? = null126    private var onNavigatedCallback: (String) -> Unit = onNavigated127    private var onLoadingProgressCallback: (Float) -> Unit = onLoadingProgress128    private var onVerificationRequiredCallback: (String) -> Unit = onVerificationRequired129    @Volatile private var disposed = false130    private var reportedChallengeUrl: String? = null131132    init {133        // JavaFX's default loader is the JDK HTTP/2 client, which sends `Upgrade: h2c` on plain http; Node134        // servers (mangayomi-sync-server on a LAN http:// URL) drop such requests, so every load fails with135        // "Unknown error". The HTTP/1.1 loader works everywhere. Read once, before the first engine loads.136        System.setProperty("com.sun.webkit.useHTTP2Loader", "false")137        add(jfxPanel, BorderLayout.CENTER)138        ensureCookieManager(cookieJar.profileId)139        Platform.setImplicitExit(false)140        Platform.runLater {141            if (disposed || !cookieJar.canUseBrowserStorage) return@runLater142            val view = WebView()143            webView = view144            val engine = view.engine145            // Extras keep localStorage/IndexedDB/cache in their own app-owned root; Default keeps JavaFX's default.146            if (cookieJar.profileId != ProfileId.Default) {147                engine.userDataDirectory = File(createPlatformLocalFileService(cookieJar.profileId).cacheRoot, "webview")148            }149            engine.isJavaScriptEnabled = true150            engine.titleProperty().addListener { _, _, _ -> reportChallenge() }151            engine.loadWorker.progressProperty().addListener { _, _, value ->152                val progress = value.toDouble().takeIf { it.isFinite() && it >= 0.0 }?.toFloat() ?: 0.05f153                dispatchProgress(progress.coerceIn(0f, 1f))154            }155            engine.loadWorker.stateProperty().addListener { _, _, state ->156                when (state) {157                    Worker.State.SUCCEEDED -> {158                        if (reportChallenge()) return@addListener159                        val current = engine.location.orEmpty().ifBlank { requestedUrl.orEmpty() }160                        harvestJavaFxCookies(current, cookieJar)161                        dispatchProgress(1f)162                        dispatchNavigated(current)163                    }164165                    Worker.State.FAILED,166                    Worker.State.CANCELLED,167                    -> dispatchProgress(1f)168169                    else -> Unit170                }171            }172            jfxPanel.scene = Scene(view)173            update(url, userAgent, onNavigated, onLoadingProgress, onVerificationRequired)174        }175    }176177    fun update(178        url: String,179        userAgent: String?,180        onNavigated: (String) -> Unit,181        onLoadingProgress: (Float) -> Unit,182        onVerificationRequired: (String) -> Unit,183    ) {184        onNavigatedCallback = onNavigated185        onLoadingProgressCallback = onLoadingProgress186        onVerificationRequiredCallback = onVerificationRequired187        Platform.runLater {188            if (disposed || !cookieJar.canUseBrowserStorage) return@runLater189            val engine = webView?.engine ?: return@runLater190            val nextUserAgent = userAgent?.takeIf { it.isNotBlank() }191            if (nextUserAgent != requestedUserAgent) {192                requestedUserAgent = nextUserAgent193                if (nextUserAgent != null) {194                    engine.userAgent = nextUserAgent195                }196            }197            if (url.isNotBlank() && url != requestedUrl) {198                requestedUrl = url199                dispatchProgress(0.05f)200                seedJavaFxCookies(url, cookieJar)201                engine.load(url)202            }203        }204    }205206    /** Blanks the page (stopping its scripts and network) and drops the engine. */207    fun dispose() {208        disposed = true209        Platform.runLater {210            webView?.engine?.load(null)211            webView = null212            jfxPanel.scene = null213        }214    }215216    /** JavaFX cannot reliably run modern challenge pages; let the screen offer the browser resolver. */217    private fun reportChallenge(): Boolean {218        if (disposed || !cookieJar.canUseBrowserStorage) return false219        val engine = webView?.engine ?: return false220        val url = engine.location?.takeIf { it.startsWith("https://") || it.startsWith("http://") } ?: return false221        val hasChallengeMarkup = runCatching {222            engine.executeScript("Boolean(window._cf_chl_opt || document.getElementById('challenge-form') || document.getElementById('cf-browser-verification'))") == true223        }.getOrDefault(false)224        if (!desktopPageNeedsBrowserVerification(engine.title.orEmpty(), hasChallengeMarkup)) return false225        if (reportedChallengeUrl != url) {226            reportedChallengeUrl = url227            SwingUtilities.invokeLater {228                if (!disposed && cookieJar.canUseBrowserStorage) onVerificationRequiredCallback(url)229            }230        }231        return true232    }233234    private fun dispatchNavigated(url: String) {235        if (url.isBlank()) return236        SwingUtilities.invokeLater { if (!disposed && cookieJar.canUseBrowserStorage) onNavigatedCallback(url) }237    }238239    private fun dispatchProgress(progress: Float) {240        SwingUtilities.invokeLater { if (!disposed && cookieJar.canUseBrowserStorage) onLoadingProgressCallback(progress) }241    }242}243244// JavaFX reads the JVM-wide CookieHandler. Panels are built on the EDT; a different profile gets a fresh245// in-memory store so one profile's cookies never reach another (its CookieJar reseeds before each load).246private var cookieHandlerOwner: ProfileId? = null247248internal fun ensureCookieManager(profileId: ProfileId) {249    if (cookieHandlerOwner == profileId && CookieHandler.getDefault() != null) return250    CookieHandler.setDefault(CookieManager(null, CookiePolicy.ACCEPT_ALL))251    cookieHandlerOwner = profileId252}253254private fun harvestJavaFxCookies(url: String, cookieJar: CookieJar) {255    if (!cookieJar.canUseBrowserStorage) return256    val manager = CookieHandler.getDefault() as? CookieManager ?: return257    val uri = runCatching { URI(url) }.getOrNull() ?: return258    val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return259    val cookies = manager.cookieStore.get(uri)260    val header = cookies261        .filter { it.name.isNotBlank() && it.value.isNotBlank() }262        .joinToString("; ") { "${it.name}=${it.value}" }263        .takeIf { it.isNotBlank() }264        ?: return265    val setCookies = cookies.mapNotNull { it.toSetCookieHeader() }266    if (setCookies.isNotEmpty()) {267        cookieJar.setFromResponse(url, setCookies)268    } else {269        cookieJar.put(host, header)270    }271}272273private fun seedJavaFxCookies(url: String, cookieJar: CookieJar) {274    if (!cookieJar.canUseBrowserStorage) return275    val manager = CookieHandler.getDefault() as? CookieManager ?: return276    val uri = runCatching { URI(url) }.getOrNull() ?: return277    val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return278    val header = cookieJar.cookieHeader(url)279        ?: cookieJar.rawCookieFor(host)280        ?: return281    val secure = uri.scheme.equals("https", ignoreCase = true)282    header.split(';').forEach { entry ->283        val trimmed = entry.trim()284        val eq = trimmed.indexOf('=')285        if (eq <= 0) return@forEach286        val name = trimmed.substring(0, eq).trim()287        val value = trimmed.substring(eq + 1).trim()288        if (name.isBlank() || value.isBlank()) return@forEach289        runCatching {290            val cookie = HttpCookie(name, value).apply {291                domain = host292                path = "/"293                this.secure = secure294            }295            manager.cookieStore.add(uri, cookie)296        }297    }298}299300private fun HttpCookie.toSetCookieHeader(): String? {301    val cookieName = name.trim().takeIf { it.isNotBlank() } ?: return null302    val cookieValue = value.trim().takeIf { it.isNotBlank() } ?: return null303    val attributes = mutableListOf("$cookieName=$cookieValue")304    domain?.trim()?.takeIf { it.isNotBlank() }?.let { attributes += "Domain=$it" }305    attributes += "Path=${path?.takeIf { it.isNotBlank() } ?: "/"}"306    if (maxAge >= 0) attributes += "Max-Age=$maxAge"307    if (secure) attributes += "Secure"308    if (isHttpOnly) attributes += "HttpOnly"309    return attributes.joinToString("; ")310}311312@Composable313private fun DesktopWebViewStatus(314    url: String,315    message: String,316    modifier: Modifier,317    onLoadingProgress: (Float) -> Unit,318    onOpenBrowser: () -> Unit,319) {320    LaunchedEffect(Unit) {321        onLoadingProgress(1f)322    }323    Box(324        modifier = modifier.fillMaxSize().padding(24.dp),325        contentAlignment = Alignment.Center,326    ) {327        Column(328            horizontalAlignment = Alignment.CenterHorizontally,329            verticalArrangement = Arrangement.spacedBy(16.dp),330        ) {331            Text(332                text = "WebView unavailable",333                style = MaterialTheme.typography.titleMedium,334                textAlign = TextAlign.Center,335            )336            Text(337                text = message,338                style = MaterialTheme.typography.bodySmall,339                color = MaterialTheme.colorScheme.onSurfaceVariant,340                textAlign = TextAlign.Center,341                maxLines = 4,342                overflow = TextOverflow.Ellipsis,343            )344            Button(onClick = onOpenBrowser) {345                Icon(Icons.Filled.OpenInBrowser, contentDescription = null)346                Text("Open in browser")347            }348        }349    }350}351352private fun fallbackPanel(): JPanel =353    JPanel(BorderLayout())354355internal actual val platformWebViewReportsNavigation: Boolean = true356357internal fun desktopPageNeedsBrowserVerification(title: String, hasChallengeMarkup: Boolean): Boolean =358    isCloudflareChallengePageTitle(title) || hasChallengeMarkup359

Search chapters, reference and source filenames.