feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
@@ -0,0 +1,137 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.MediaPlayer
|
||||
import android.media.PlaybackParams
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Surface
|
||||
import android.view.TextureView
|
||||
import org.json.JSONObject
|
||||
|
||||
private class PlayerView(context: Context, val id: Long, args: JSONObject) : TextureView(context), TextureView.SurfaceTextureListener {
|
||||
val player = MediaPlayer()
|
||||
var ready = false
|
||||
var ended = false
|
||||
var error = ""
|
||||
private val auto = args.optBoolean("autoPlay")
|
||||
private val ticks = Handler(Looper.getMainLooper())
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (ready && player.isPlaying) send()
|
||||
ticks.postDelayed(this, 250)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
surfaceTextureListener = this
|
||||
player.isLooping = args.optBoolean("loop")
|
||||
if (args.optBoolean("muted")) player.setVolume(0f, 0f)
|
||||
val source = args.optString("source")
|
||||
try {
|
||||
if (source.contains("://")) player.setDataSource(context, Uri.parse(source)) else player.setDataSource(source)
|
||||
} catch (e: Exception) {
|
||||
error = e.toString()
|
||||
}
|
||||
player.setOnPreparedListener {
|
||||
ready = true
|
||||
if (auto) it.start()
|
||||
send()
|
||||
}
|
||||
player.setOnCompletionListener {
|
||||
ended = true
|
||||
send()
|
||||
}
|
||||
player.setOnVideoSizeChangedListener { _, _, _ ->
|
||||
fit()
|
||||
send()
|
||||
}
|
||||
addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fit() }
|
||||
player.setOnErrorListener { _, what, extra ->
|
||||
error = "MediaPlayer error $what/$extra"
|
||||
send()
|
||||
true
|
||||
}
|
||||
ticks.post(tick)
|
||||
}
|
||||
|
||||
/** Shows the video whole in the view, keeping its shape: a texture fills the view. */
|
||||
private fun fit() {
|
||||
val vw = player.videoWidth.toFloat()
|
||||
val vh = player.videoHeight.toFloat()
|
||||
if (vw <= 0 || vh <= 0 || width == 0 || height == 0) return
|
||||
val k = minOf(width / vw, height / vh)
|
||||
val sx = vw * k / width
|
||||
val sy = vh * k / height
|
||||
val m = android.graphics.Matrix()
|
||||
m.setScale(sx, sy, width / 2f, height / 2f)
|
||||
setTransform(m)
|
||||
}
|
||||
|
||||
fun send() {
|
||||
PluginHost.emit("videoplayer", "state", JSONObject().put("id", id).put("ready", ready).put("ended", ended)
|
||||
.put("playing", ready && player.isPlaying)
|
||||
.put("positionMs", if (ready) player.currentPosition else 0).put("durationMs", if (ready) player.duration else 0)
|
||||
.put("width", player.videoWidth).put("height", player.videoHeight).put("error", error))
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
ticks.removeCallbacks(tick)
|
||||
player.release()
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureAvailable(t: SurfaceTexture, w: Int, h: Int) {
|
||||
player.setSurface(Surface(t))
|
||||
if (error.isEmpty() && !ready) runCatching { player.prepareAsync() }.onFailure { error = it.toString(); send() }
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(t: SurfaceTexture, w: Int, h: Int) {}
|
||||
override fun onSurfaceTextureDestroyed(t: SurfaceTexture) = true
|
||||
override fun onSurfaceTextureUpdated(t: SurfaceTexture) {}
|
||||
}
|
||||
|
||||
class VideoPlayerPlugin : MyGoPlugin {
|
||||
private val views = HashMap<Long, PlayerView>()
|
||||
|
||||
init {
|
||||
PluginHost.registerView("videoplayer") { context, id, args ->
|
||||
PlayerView(context, id, args).also { views[id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
val v = views[args.optLong("id")]
|
||||
if (v == null) {
|
||||
reply.failure(PluginFailure("NoView"))
|
||||
return
|
||||
}
|
||||
when (method) {
|
||||
"play" -> {
|
||||
v.ended = false
|
||||
if (v.ready) v.player.start()
|
||||
v.send()
|
||||
}
|
||||
"pause" -> {
|
||||
if (v.ready) v.player.pause()
|
||||
v.send()
|
||||
}
|
||||
"seek" -> {
|
||||
v.ended = false
|
||||
if (v.ready) v.player.seekTo(args.optLong("ms"), MediaPlayer.SEEK_CLOSEST)
|
||||
}
|
||||
"volume" -> v.player.setVolume(args.optDouble("volume", 1.0).toFloat(), args.optDouble("volume", 1.0).toFloat())
|
||||
"rate" -> if (v.ready) v.player.playbackParams = PlaybackParams().setSpeed(args.optDouble("rate", 1.0).toFloat())
|
||||
"dispose" -> {
|
||||
v.dispose()
|
||||
views.remove(args.optLong("id"))
|
||||
}
|
||||
else -> {
|
||||
reply.failure(PluginFailure("NoMethod", method))
|
||||
return
|
||||
}
|
||||
}
|
||||
reply.success(null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import AVFoundation
|
||||
import UIKit
|
||||
|
||||
private final class PlayerView: UIView {
|
||||
override class var layerClass: AnyClass { AVPlayerLayer.self }
|
||||
let player = AVPlayer()
|
||||
var loop = false
|
||||
var id = 0
|
||||
var observers: [NSKeyValueObservation] = []
|
||||
var timeObserver: Any?
|
||||
var ended = false
|
||||
|
||||
func send() {
|
||||
let item = player.currentItem
|
||||
let dur = item?.duration.seconds ?? 0
|
||||
let size = item?.presentationSize ?? .zero
|
||||
PluginHost.emit("videoplayer", "state", [
|
||||
"id": id, "ready": item?.status == .readyToPlay, "playing": player.rate != 0, "ended": ended,
|
||||
"positionMs": max(0, player.currentTime().seconds * 1000), "durationMs": dur.isFinite ? dur * 1000 : 0,
|
||||
"width": Int(size.width), "height": Int(size.height), "error": item?.error?.localizedDescription ?? "",
|
||||
] as [String: Any])
|
||||
}
|
||||
}
|
||||
|
||||
final class VideoPlayerPlugin: NSObject, MyGoPlugin {
|
||||
private var views: [Int: PlayerView] = [:]
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
PluginHost.registerView("videoplayer") { [weak self] id, args in
|
||||
let v = PlayerView()
|
||||
v.id = id
|
||||
(v.layer as! AVPlayerLayer).player = v.player
|
||||
self?.views[id] = v
|
||||
self?.start(v, args)
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
private func start(_ v: PlayerView, _ args: [String: Any]) {
|
||||
let source = args["source"] as? String ?? ""
|
||||
let url = source.contains("://") ? URL(string: source) : URL(fileURLWithPath: source)
|
||||
guard let url else { return }
|
||||
let item = AVPlayerItem(url: url)
|
||||
v.loop = args["loop"] as? Bool ?? false
|
||||
v.player.isMuted = args["muted"] as? Bool ?? false
|
||||
v.player.replaceCurrentItem(with: item)
|
||||
// Plays with the sound on, whatever the side switch says.
|
||||
try? AVAudioSession.sharedInstance().setCategory(.playback)
|
||||
try? AVAudioSession.sharedInstance().setActive(true)
|
||||
v.observers = [
|
||||
item.observe(\.status) { [weak v] _, _ in v?.send() },
|
||||
v.player.observe(\.rate) { [weak v] _, _ in v?.send() },
|
||||
]
|
||||
v.timeObserver = v.player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 4), queue: .main) { [weak v] _ in v?.send() }
|
||||
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main) { [weak v] _ in
|
||||
guard let v else { return }
|
||||
if v.loop {
|
||||
v.player.seek(to: .zero)
|
||||
v.player.play()
|
||||
} else {
|
||||
v.ended = true
|
||||
v.send()
|
||||
}
|
||||
}
|
||||
if args["autoPlay"] as? Bool ?? false { v.player.play() }
|
||||
}
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
guard let id = args["id"] as? Int, let v = views[id] else {
|
||||
reply(.failure(PluginFailure("NoView")))
|
||||
return
|
||||
}
|
||||
switch method {
|
||||
case "play":
|
||||
v.ended = false
|
||||
v.player.play()
|
||||
case "pause": v.player.pause()
|
||||
case "seek":
|
||||
v.ended = false
|
||||
let ms = args["ms"] as? Double ?? Double(args["ms"] as? Int ?? 0)
|
||||
v.player.seek(to: CMTime(seconds: ms / 1000, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero)
|
||||
case "volume": v.player.volume = Float(args["volume"] as? Double ?? 1)
|
||||
case "rate": v.player.rate = Float(args["rate"] as? Double ?? 1)
|
||||
case "dispose":
|
||||
v.player.pause()
|
||||
if let t = v.timeObserver { v.player.removeTimeObserver(t) }
|
||||
v.observers = []
|
||||
views[id] = nil
|
||||
default:
|
||||
reply(.failure(PluginFailure("NoMethod", method)))
|
||||
return
|
||||
}
|
||||
reply(.success(nil))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "videoplayer",
|
||||
"ios": {"sources": ["ios/*.swift"], "class": "VideoPlayerPlugin", "frameworks": ["AVFoundation"]},
|
||||
"android": {"sources": ["android/*.kt"], "class": "VideoPlayerPlugin"}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// Package videoplayer plays videos and their sound in a window's native UI, on
|
||||
// phones and tablets, with the system's decoders: AVPlayer on iOS, MediaPlayer
|
||||
// on Android, from a file or a URL they can read, HLS among them.
|
||||
//
|
||||
// p, err := videoplayer.New(win, "https://example.com/film.m3u8", videoplayer.Options{AutoPlay: true})
|
||||
// ...
|
||||
// ui.WebView(c, p).Fill() // in the window's view; what it draws after shows over the video
|
||||
//
|
||||
// The view shows under the content, as a web view does. On desktops and in
|
||||
// browsers New reports errors.ErrUnsupported.
|
||||
package videoplayer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/surface"
|
||||
)
|
||||
|
||||
const pluginID = "videoplayer"
|
||||
|
||||
// Options are how a Player starts.
|
||||
type Options struct {
|
||||
// AutoPlay plays it as soon as it can.
|
||||
AutoPlay bool
|
||||
// Loop plays it again from the start as it ends.
|
||||
Loop bool
|
||||
// Muted plays it without sound.
|
||||
Muted bool
|
||||
}
|
||||
|
||||
// State is what a Player tells of its video.
|
||||
type State struct {
|
||||
// Ready says it can play: Duration and the size are known.
|
||||
Ready bool
|
||||
// Playing says it plays now, and Ended that it got to the end.
|
||||
Playing, Ended bool
|
||||
// Position is where it is, and Duration how long the video is.
|
||||
Position, Duration time.Duration
|
||||
// Width and Height are the video's size in pixels.
|
||||
Width, Height int
|
||||
// Error says why it cannot play, if so.
|
||||
Error string
|
||||
}
|
||||
|
||||
type wireState struct {
|
||||
ID int `json:"id"`
|
||||
Ready bool `json:"ready"`
|
||||
Playing bool `json:"playing"`
|
||||
Ended bool `json:"ended"`
|
||||
PositionMS float64 `json:"positionMs"`
|
||||
DurationMS float64 `json:"durationMs"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// Player plays a video. Show it with ui.WebView.
|
||||
type Player struct {
|
||||
view *mygo.PluginView
|
||||
|
||||
mu sync.Mutex
|
||||
state State
|
||||
onState []func(State)
|
||||
off func()
|
||||
}
|
||||
|
||||
// New makes a player of a file's path or a URL, in a window showing native UI.
|
||||
func New(w *mygo.Window, source string, o Options) (*Player, error) {
|
||||
v, err := mygo.NewPluginView(w, "videoplayer", map[string]any{
|
||||
"source": source, "autoPlay": o.AutoPlay, "loop": o.Loop, "muted": o.Muted,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := &Player{view: v}
|
||||
p.off = mygo.Native(pluginID).On("state", func(data []byte) {
|
||||
var s wireState
|
||||
if json.Unmarshal(data, &s) != nil || s.ID != v.ID {
|
||||
return
|
||||
}
|
||||
st := State{s.Ready, s.Playing, s.Ended, time.Duration(s.PositionMS) * time.Millisecond,
|
||||
time.Duration(s.DurationMS) * time.Millisecond, s.Width, s.Height, s.Error}
|
||||
p.mu.Lock()
|
||||
p.state = st
|
||||
list := append([]func(State){}, p.onState...)
|
||||
p.mu.Unlock()
|
||||
for _, fn := range list {
|
||||
fn(st)
|
||||
}
|
||||
})
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// SurfaceWebView gives package ui the view to show.
|
||||
func (p *Player) SurfaceWebView(conn *surface.Conn) platform.WebView {
|
||||
return p.view.SurfaceWebView(conn)
|
||||
}
|
||||
|
||||
// State tells what the player last told of its video.
|
||||
func (p *Player) State() State {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.state
|
||||
}
|
||||
|
||||
// OnState calls fn on the main thread as the state changes, and a few times a
|
||||
// second as it plays.
|
||||
func (p *Player) OnState(fn func(State)) {
|
||||
p.mu.Lock()
|
||||
p.onState = append(p.onState, fn)
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *Player) call(method string, args map[string]any) {
|
||||
if args == nil {
|
||||
args = map[string]any{}
|
||||
}
|
||||
args["id"] = p.view.ID
|
||||
go mygo.Native(pluginID).Call(context.Background(), method, args, nil)
|
||||
}
|
||||
|
||||
// Play plays it from where it is.
|
||||
func (p *Player) Play() { p.call("play", nil) }
|
||||
|
||||
// Pause stops it where it is.
|
||||
func (p *Player) Pause() { p.call("pause", nil) }
|
||||
|
||||
// Seek goes to a position.
|
||||
func (p *Player) Seek(to time.Duration) { p.call("seek", map[string]any{"ms": to.Milliseconds()}) }
|
||||
|
||||
// SetVolume sets how loud it plays, from 0 to 1.
|
||||
func (p *Player) SetVolume(v float64) { p.call("volume", map[string]any{"volume": v}) }
|
||||
|
||||
// SetRate sets how fast it plays: 1 is normal speed.
|
||||
func (p *Player) SetRate(r float64) { p.call("rate", map[string]any{"rate": r}) }
|
||||
|
||||
// Destroy stops it and takes its view away.
|
||||
func (p *Player) Destroy() {
|
||||
p.off()
|
||||
p.call("dispose", nil)
|
||||
p.view.Destroy()
|
||||
}
|
||||
Reference in new issue
Block a user