mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-11 19:04:08 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89bd3f3af0 | ||
|
|
89dfbe4c45 |
No files matched your search
@@ -134,6 +134,9 @@ jobs:
|
|||||||
if: runner.os == 'macOS'
|
if: runner.os == 'macOS'
|
||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
|
- name: Test Windows FFmpeg memory and stream lifecycle
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
run: go test -v -count=1 -timeout 180s ./pkg/download/engine/ffmpeg ./pkg/download/engine/inject/stream ./pkg/download/engine
|
||||||
- name: Install Linux WebView dependencies
|
- name: Install Linux WebView dependencies
|
||||||
if: runner.os == 'Linux'
|
if: runner.os == 'Linux'
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ type Uploader interface {
|
|||||||
WaitUpload() error
|
WaitUpload() error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DownloadCounter interface {
|
||||||
|
ReceivedBytes() int64
|
||||||
|
}
|
||||||
|
|
||||||
// FetcherMeta defines the meta information of a fetcher.
|
// FetcherMeta defines the meta information of a fetcher.
|
||||||
type FetcherMeta struct {
|
type FetcherMeta struct {
|
||||||
Req *base.Request `json:"req"`
|
Req *base.Request `json:"req"`
|
||||||
|
|||||||
@@ -290,6 +290,82 @@ func TestBTDownloadSelectedFiles(t *testing.T) {
|
|||||||
if f.Meta().Res.Size != 48*1024 {
|
if f.Meta().Res.Size != 48*1024 {
|
||||||
t.Fatal("selected resource size is incorrect")
|
t.Fatal("selected resource size is incorrect")
|
||||||
}
|
}
|
||||||
|
if downloaded := f.Progress().TotalDownloaded(); downloaded != 48*1024 || f.ReceivedBytes() <= downloaded {
|
||||||
|
t.Fatalf("selected progress = %d, received traffic = %d; want 48 KiB of progress and traffic across the shared piece", downloaded, f.ReceivedBytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBTProgressOnlyCountsVerifiedFileBytes(t *testing.T) {
|
||||||
|
const fileSize = 56 * 1024
|
||||||
|
fixture := makeBTFixtureWithPieceSize(t, map[string][]byte{
|
||||||
|
"a.bin": btPayload(fileSize, "verified-a"),
|
||||||
|
"b.bin": btPayload(fileSize, "verified-b"),
|
||||||
|
}, 16*1024, false, true, 64*1024)
|
||||||
|
f := btDownloadFetcher(t, nil)
|
||||||
|
btResolve(t, f, fixture.Magnet)
|
||||||
|
dir := t.TempDir()
|
||||||
|
f.Meta().Opts = &base.Options{Path: dir}
|
||||||
|
btStart(t, f)
|
||||||
|
deadline := time.Now().Add(8 * time.Second)
|
||||||
|
for f.torrent.Files()[0].BytesCompleted() == 0 && time.Now().Before(deadline) {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
btPause(t, f)
|
||||||
|
if f.torrent.Files()[0].BytesCompleted() == 0 || f.torrent.Piece(0).State().Complete {
|
||||||
|
t.Fatal("expected some received bytes in a piece that is still incomplete")
|
||||||
|
}
|
||||||
|
if f.ReceivedBytes() == 0 {
|
||||||
|
t.Fatal("received traffic must be visible before a piece is verified")
|
||||||
|
}
|
||||||
|
if progress := f.Progress(); len(progress) != 2 || progress[0] != 0 {
|
||||||
|
t.Errorf("progress before the first file's piece is verified = %v, want zero for the first file", progress)
|
||||||
|
}
|
||||||
|
fixture.Limiter.SetLimit(rate.Inf)
|
||||||
|
btStart(t, f)
|
||||||
|
btAwaitDone(t, f)
|
||||||
|
fixture.AssertFiles(t, dir)
|
||||||
|
progress := f.Progress()
|
||||||
|
if len(progress) != 2 || progress[0] != fileSize || progress[1] != fileSize {
|
||||||
|
t.Fatalf("verified progress at completion = %v, want %d for each file", progress, fileSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBTUploadedBytesSamplesLiveTraffic(t *testing.T) {
|
||||||
|
payload := btPayload(48*1024, "upload-counter")
|
||||||
|
fixture := newBTFixture(t, map[string][]byte{"": payload}, 0)
|
||||||
|
const saved = 1024
|
||||||
|
f := &Fetcher{
|
||||||
|
torrent: fixture.Torrent,
|
||||||
|
data: &fetcherData{SeedBytes: saved},
|
||||||
|
seedBaseBytes: saved,
|
||||||
|
}
|
||||||
|
f.torrentReady.Store(true)
|
||||||
|
f.torrentUpload.Store(true)
|
||||||
|
|
||||||
|
cfg := torrent.TestingConfig(t)
|
||||||
|
cfg.DataDir = t.TempDir()
|
||||||
|
cfg.DisableTrackers = true
|
||||||
|
cfg.DisableUTP = true
|
||||||
|
cfg.DisableIPv6 = true
|
||||||
|
peer, err := torrent.NewClient(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { peer.Close() })
|
||||||
|
download, _, err := peer.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(fixture.MetaInfo))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
download.AddPeers([]torrent.PeerInfo{{Addr: fixture.Seeder.ListenAddrs()[0]}})
|
||||||
|
download.DownloadAll()
|
||||||
|
select {
|
||||||
|
case <-download.Complete().On():
|
||||||
|
case <-time.After(10 * time.Second):
|
||||||
|
t.Fatal("loopback peer did not complete")
|
||||||
|
}
|
||||||
|
if got, want := f.UploadedBytes(), int64(saved+len(payload)); got != want {
|
||||||
|
t.Fatalf("uploaded bytes = %d, want %d including the saved bytes", got, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBTPauseAndResume(t *testing.T) {
|
func TestBTPauseAndResume(t *testing.T) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -45,6 +46,7 @@ type Fetcher struct {
|
|||||||
torrent *torrent.Torrent
|
torrent *torrent.Torrent
|
||||||
meta *fetcher.FetcherMeta
|
meta *fetcher.FetcherMeta
|
||||||
data *fetcherData
|
data *fetcherData
|
||||||
|
seedBaseBytes int64
|
||||||
|
|
||||||
torrentReady atomic.Bool
|
torrentReady atomic.Bool
|
||||||
torrentUpload atomic.Bool
|
torrentUpload atomic.Bool
|
||||||
@@ -463,14 +465,46 @@ func (f *Fetcher) Progress() fetcher.Progress {
|
|||||||
if !f.torrentReady.Load() {
|
if !f.torrentReady.Load() {
|
||||||
return append(fetcher.Progress(nil), f.data.Progress...)
|
return append(fetcher.Progress(nil), f.data.Progress...)
|
||||||
}
|
}
|
||||||
|
pieceSize := f.torrent.Info().PieceLength
|
||||||
|
var offset int64
|
||||||
|
var verified []verifiedByteRange
|
||||||
|
for _, run := range f.torrent.PieceStateRuns() {
|
||||||
|
end := offset + int64(run.Length)*pieceSize
|
||||||
|
if pieceVerified(run.PieceState) {
|
||||||
|
verified = append(verified, verifiedByteRange{start: offset, end: end})
|
||||||
|
}
|
||||||
|
offset = end
|
||||||
|
}
|
||||||
|
files := f.torrent.Files()
|
||||||
for i := range f.data.Progress {
|
for i := range f.data.Progress {
|
||||||
selectIndex := f.meta.Opts.SelectFiles[i]
|
selectIndex := f.meta.Opts.SelectFiles[i]
|
||||||
file := f.torrent.Files()[selectIndex]
|
file := files[selectIndex]
|
||||||
f.data.Progress[i] = file.BytesCompleted()
|
f.data.Progress[i] = verifiedFileBytes(verified, file.Offset(), file.Length())
|
||||||
}
|
}
|
||||||
return append(fetcher.Progress(nil), f.data.Progress...)
|
return append(fetcher.Progress(nil), f.data.Progress...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type verifiedByteRange struct {
|
||||||
|
start, end int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifiedFileBytes(verified []verifiedByteRange, offset, length int64) int64 {
|
||||||
|
first := sort.Search(len(verified), func(i int) bool { return verified[i].end > offset })
|
||||||
|
fileEnd := offset + length
|
||||||
|
var completed int64
|
||||||
|
for _, run := range verified[first:] {
|
||||||
|
if run.start >= fileEnd {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
completed += min(fileEnd, run.end) - max(offset, run.start)
|
||||||
|
}
|
||||||
|
return completed
|
||||||
|
}
|
||||||
|
|
||||||
|
func pieceVerified(state torrent.PieceState) bool {
|
||||||
|
return state.Ok && state.Complete && !state.Hashing && !state.QueuedForHash
|
||||||
|
}
|
||||||
|
|
||||||
func (f *Fetcher) Wait() error {
|
func (f *Fetcher) Wait() error {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
var closed <-chan struct{}
|
var closed <-chan struct{}
|
||||||
@@ -587,7 +621,7 @@ func (f *Fetcher) isDoneLocked() bool {
|
|||||||
file := f.torrent.Files()[index]
|
file := f.torrent.Files()[index]
|
||||||
for i := file.BeginPieceIndex(); i < file.EndPieceIndex(); i++ {
|
for i := file.BeginPieceIndex(); i < file.EndPieceIndex(); i++ {
|
||||||
state := f.torrent.Piece(i).State()
|
state := f.torrent.Piece(i).State()
|
||||||
if !state.Ok || !state.Complete || state.Hashing || state.QueuedForHash {
|
if !pieceVerified(state) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -685,11 +719,13 @@ func (f *Fetcher) Upload() (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher) doUpload(fromUpload bool) {
|
func (f *Fetcher) doUpload(fromUpload bool) {
|
||||||
|
f.mu.Lock()
|
||||||
if !f.torrentUpload.CompareAndSwap(false, true) {
|
if !f.torrentUpload.CompareAndSwap(false, true) {
|
||||||
|
f.mu.Unlock()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
f.mu.Lock()
|
f.seedBaseBytes = f.data.SeedBytes
|
||||||
initialBytes, initialTime := f.data.SeedBytes, f.data.SeedTime
|
initialTime := f.data.SeedTime
|
||||||
torrentClosed := f.torrent.Closed()
|
torrentClosed := f.torrent.Closed()
|
||||||
f.mu.Unlock()
|
f.mu.Unlock()
|
||||||
var doneTime int64
|
var doneTime int64
|
||||||
@@ -707,8 +743,7 @@ func (f *Fetcher) doUpload(fromUpload bool) {
|
|||||||
f.mu.Unlock()
|
f.mu.Unlock()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
stats := f.torrentStats()
|
f.refreshSeedBytesLocked()
|
||||||
f.data.SeedBytes = initialBytes + stats.BytesWrittenData.Int64()
|
|
||||||
if !fromUpload && !f.isDoneLocked() {
|
if !fromUpload && !f.isDoneLocked() {
|
||||||
f.mu.Unlock()
|
f.mu.Unlock()
|
||||||
continue
|
continue
|
||||||
@@ -741,9 +776,27 @@ func (f *Fetcher) torrentStats() torrent.TorrentStats {
|
|||||||
func (f *Fetcher) UploadedBytes() int64 {
|
func (f *Fetcher) UploadedBytes() int64 {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
|
if f.torrentReady.Load() && f.torrentUpload.Load() {
|
||||||
|
f.refreshSeedBytesLocked()
|
||||||
|
}
|
||||||
return f.data.SeedBytes
|
return f.data.SeedBytes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher) refreshSeedBytesLocked() {
|
||||||
|
stats := f.torrentStats()
|
||||||
|
f.data.SeedBytes = max(f.data.SeedBytes, f.seedBaseBytes+stats.BytesWrittenData.Int64())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fetcher) ReceivedBytes() int64 {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if !f.torrentReady.Load() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
stats := f.torrentStats()
|
||||||
|
return stats.BytesReadUsefulData.Int64()
|
||||||
|
}
|
||||||
|
|
||||||
func (f *Fetcher) WaitUpload() (err error) {
|
func (f *Fetcher) WaitUpload() (err error) {
|
||||||
<-f.uploadDoneCh
|
<-f.uploadDoneCh
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -46,6 +46,11 @@ func newBTHybridFixture(t testing.TB, payload []byte) *btFixture {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func makeBTFixture(t testing.TB, files map[string][]byte, bytesPerSecond int, v2, private bool) *btFixture {
|
func makeBTFixture(t testing.TB, files map[string][]byte, bytesPerSecond int, v2, private bool) *btFixture {
|
||||||
|
t.Helper()
|
||||||
|
return makeBTFixtureWithPieceSize(t, files, bytesPerSecond, v2, private, 16*1024)
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeBTFixtureWithPieceSize(t testing.TB, files map[string][]byte, bytesPerSecond int, v2, private bool, pieceSize int64) *btFixture {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
source := t.TempDir()
|
source := t.TempDir()
|
||||||
name := "payload.bin"
|
name := "payload.bin"
|
||||||
@@ -64,7 +69,7 @@ func makeBTFixture(t testing.TB, files map[string][]byte, bytesPerSecond int, v2
|
|||||||
}
|
}
|
||||||
expected[filepath.Join(name, filepath.FromSlash(path))] = append([]byte(nil), data...)
|
expected[filepath.Join(name, filepath.FromSlash(path))] = append([]byte(nil), data...)
|
||||||
}
|
}
|
||||||
info := metainfo.Info{PieceLength: 16 * 1024}
|
info := metainfo.Info{PieceLength: pieceSize}
|
||||||
if err := info.BuildFromFilePath(root); err != nil {
|
if err := info.BuildFromFilePath(root); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package download
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime/debug"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLogPanicPreservesPreviousCrash(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
path := filepath.Join(dir, "crash.log")
|
||||||
|
const previous = "previous crash traceback\n"
|
||||||
|
if err := os.WriteFile(path, []byte(previous), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
logPanic(dir)
|
||||||
|
t.Cleanup(func() { _ = debug.SetCrashOutput(nil, debug.CrashOptions{}) })
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(data) != previous {
|
||||||
|
t.Fatalf("previous crash was overwritten: %q", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -345,7 +345,12 @@ func (d *Downloader) Setup() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
current := task.fetcher.Progress().TotalDownloaded()
|
current := task.fetcher.Progress().TotalDownloaded()
|
||||||
delta := current - task.Progress.Downloaded
|
delta := max(0, current-task.Progress.Downloaded)
|
||||||
|
if counter, ok := task.fetcher.(fetcher.DownloadCounter); ok && task.Status == base.DownloadStatusRunning {
|
||||||
|
received := counter.ReceivedBytes()
|
||||||
|
delta = received - task.receivedBytes
|
||||||
|
task.receivedBytes = received
|
||||||
|
}
|
||||||
if task.Meta != nil && task.Meta.Req != nil {
|
if task.Meta != nil && task.Meta.Req != nil {
|
||||||
if producer := d.blob.Production(task.Meta.Req.URL); producer != nil {
|
if producer := d.blob.Production(task.Meta.Req.URL); producer != nil {
|
||||||
downloaded, received := producer.Progress()
|
downloaded, received := producer.Progress()
|
||||||
@@ -353,19 +358,20 @@ func (d *Downloader) Setup() error {
|
|||||||
task.producer = producer
|
task.producer = producer
|
||||||
task.producerReceived = 0
|
task.producerReceived = 0
|
||||||
task.speedArr = nil
|
task.speedArr = nil
|
||||||
|
task.downloadSampledAt = time.Time{}
|
||||||
}
|
}
|
||||||
current = downloaded
|
current = downloaded
|
||||||
delta = max(0, received-task.producerReceived)
|
delta = max(0, received-task.producerReceived)
|
||||||
task.producerReceived = received
|
task.producerReceived = received
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tick := float64(d.cfg.RefreshInterval) / 1000
|
|
||||||
downloadDataChanged := false
|
downloadDataChanged := false
|
||||||
uploading := task.Uploading
|
uploading := task.Uploading
|
||||||
if task.Status == base.DownloadStatusRunning {
|
if task.Status == base.DownloadStatusRunning {
|
||||||
downloadDataChanged = current != task.Progress.Downloaded
|
downloadDataChanged = current != task.Progress.Downloaded
|
||||||
task.Progress.Used = task.timer.Used()
|
task.Progress.Used = task.timer.Used()
|
||||||
task.Progress.Speed = task.updateSpeed(max(0, delta), tick)
|
elapsed := sampleSeconds(&task.downloadSampledAt, time.Now())
|
||||||
|
task.Progress.Speed = task.updateSpeed(delta, elapsed)
|
||||||
task.Progress.Downloaded = current
|
task.Progress.Downloaded = current
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,7 +380,8 @@ func (d *Downloader) Setup() error {
|
|||||||
uploader := task.fetcher.(fetcher.Uploader)
|
uploader := task.fetcher.(fetcher.Uploader)
|
||||||
currentUploaded := uploader.UploadedBytes()
|
currentUploaded := uploader.UploadedBytes()
|
||||||
uploadDataChanged = currentUploaded != task.Progress.Uploaded
|
uploadDataChanged = currentUploaded != task.Progress.Uploaded
|
||||||
task.Progress.UploadSpeed = task.updateUploadSpeed(currentUploaded-task.Progress.Uploaded, tick)
|
elapsed := sampleSeconds(&task.uploadSampledAt, time.Now())
|
||||||
|
task.Progress.UploadSpeed = task.updateUploadSpeed(currentUploaded-task.Progress.Uploaded, elapsed)
|
||||||
task.Progress.Uploaded = currentUploaded
|
task.Progress.Uploaded = currentUploaded
|
||||||
}
|
}
|
||||||
task.statusLock.Unlock()
|
task.statusLock.Unlock()
|
||||||
@@ -2453,6 +2460,8 @@ func (d *Downloader) doStart(task *Task) (err error) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
task.Progress.Speed = 0
|
task.Progress.Speed = 0
|
||||||
|
task.speedArr = nil
|
||||||
|
task.downloadSampledAt = time.Time{}
|
||||||
task.timer.Start()
|
task.timer.Start()
|
||||||
task.statusLock.Unlock()
|
task.statusLock.Unlock()
|
||||||
if err := task.fetcher.Start(); err != nil {
|
if err := task.fetcher.Start(); err != nil {
|
||||||
@@ -2650,11 +2659,12 @@ func logPanic(logDir string) {
|
|||||||
if err := util.CreateDirIfNotExist(logDir); err != nil {
|
if err := util.CreateDirIfNotExist(logDir); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
f, err := os.Create(filepath.Join(logDir, "crash.log"))
|
f, err := os.OpenFile(filepath.Join(logDir, "crash.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
debug.SetCrashOutput(f, debug.CrashOptions{})
|
defer f.Close() // SetCrashOutput duplicates the descriptor.
|
||||||
|
_ = debug.SetCrashOutput(f, debug.CrashOptions{})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Downloader) assignFetcherManager(task *Task) error {
|
func (d *Downloader) assignFetcherManager(task *Task) error {
|
||||||
@@ -3061,8 +3071,10 @@ func initTask(task *Task) {
|
|||||||
task.lock = &sync.Mutex{}
|
task.lock = &sync.Mutex{}
|
||||||
task.statsLock = &sync.Mutex{}
|
task.statsLock = &sync.Mutex{}
|
||||||
task.blobRefLock = &sync.Mutex{}
|
task.blobRefLock = &sync.Mutex{}
|
||||||
task.speedArr = make([]int64, 0)
|
task.speedArr = nil
|
||||||
task.uploadSpeedArr = make([]int64, 0)
|
task.uploadSpeedArr = nil
|
||||||
|
task.downloadSampledAt = time.Time{}
|
||||||
|
task.uploadSampledAt = time.Time{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Downloader) releaseBlobTask(task *Task) {
|
func (d *Downloader) releaseBlobTask(task *Task) {
|
||||||
|
|||||||
@@ -174,3 +174,12 @@ compilation memory, host buffers and JS allocations are additional to the
|
|||||||
linear-memory limit. Playback support depends on the selected codecs, not just
|
linear-memory limit. Playback support depends on the selected codecs, not just
|
||||||
the `.mp4` suffix. Platform execution and performance must be tested on target
|
the `.mp4` suffix. Platform execution and performance must be tested on target
|
||||||
devices, especially mobile/32-bit devices.
|
devices, especially mobile/32-bit devices.
|
||||||
|
|
||||||
|
On 64-bit Windows, instance linear memory uses a reserved virtual address range with
|
||||||
|
pages committed as it grows. Module completion, errors and cancellation release
|
||||||
|
this range directly through `VirtualFree`, rather than waiting for Go's garbage
|
||||||
|
collector to reclaim large buffers. Growing an instance preserves its address
|
||||||
|
without copying the previous buffer. The 512 MiB limit is unchanged; reservation
|
||||||
|
does not commit that entire amount. Shared compilation remains resident after
|
||||||
|
the first merge, so process memory is not expected to return exactly to the
|
||||||
|
pre-FFmpeg baseline. This does not diagnose unrelated idle memory growth.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package ffmpeg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/tetratelabs/wazero/experimental"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The runtime does not always invoke Free when a module's start function traps.
|
||||||
|
// Keep host ownership until execution returns, including failed instantiation.
|
||||||
|
func withOwnedMemory(ctx context.Context, allocator experimental.MemoryAllocator) (context.Context, func()) {
|
||||||
|
var memories []*ownedLinearMemory
|
||||||
|
ctx = experimental.WithMemoryAllocator(ctx, experimental.MemoryAllocatorFunc(
|
||||||
|
func(cap, max uint64) experimental.LinearMemory {
|
||||||
|
memory := &ownedLinearMemory{LinearMemory: allocator.Allocate(cap, max)}
|
||||||
|
memories = append(memories, memory)
|
||||||
|
return memory
|
||||||
|
}))
|
||||||
|
return ctx, func() {
|
||||||
|
for _, memory := range memories {
|
||||||
|
memory.Free()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ownedLinearMemory struct {
|
||||||
|
experimental.LinearMemory
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *ownedLinearMemory) Free() { m.once.Do(m.LinearMemory.Free) }
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !windows || (!amd64 && !arm64)
|
||||||
|
|
||||||
|
package ffmpeg
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
func withLinearMemory(ctx context.Context) (context.Context, func()) { return ctx, func() {} }
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package ffmpeg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/hex"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tetratelabs/wazero"
|
||||||
|
"github.com/tetratelabs/wazero/experimental"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Verify the pinned runtime's allocator lifecycle on every development host:
|
||||||
|
// host-owned buffers must not be released before execution ends, or retained
|
||||||
|
// after failed instantiation, traps or cancellation.
|
||||||
|
func TestLinearMemoryModuleLifecycle(t *testing.T) {
|
||||||
|
testLinearMemoryModuleLifecycle(t, func(_, _ uint64) experimental.LinearMemory {
|
||||||
|
return &testLinearMemory{}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type testLinearMemory struct{ buffer []byte }
|
||||||
|
|
||||||
|
func (m *testLinearMemory) Reallocate(size uint64) []byte {
|
||||||
|
m.buffer = append(m.buffer, make([]byte, int(size)-len(m.buffer))...)
|
||||||
|
return m.buffer
|
||||||
|
}
|
||||||
|
func (m *testLinearMemory) Free() { m.buffer = nil }
|
||||||
|
|
||||||
|
type trackedLinearMemory struct {
|
||||||
|
experimental.LinearMemory
|
||||||
|
freeCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *trackedLinearMemory) Free() {
|
||||||
|
m.freeCount++
|
||||||
|
m.LinearMemory.Free()
|
||||||
|
}
|
||||||
|
|
||||||
|
func testLinearMemoryModuleLifecycle(t *testing.T, allocate experimental.MemoryAllocatorFunc) {
|
||||||
|
t.Helper()
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
// A module with one memory (min=1/max=2 pages), optionally a start
|
||||||
|
// function that traps or loops until its context is cancelled.
|
||||||
|
wasm string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"close", "0061736d01000000050401010102", false},
|
||||||
|
{"trap", "0061736d01000000010401600000030201000504010101020801000a05010300000b", true},
|
||||||
|
{"cancel", "0061736d01000000010401600000030201000504010101020801000a0901070003400c000b0b", true},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var memory *trackedLinearMemory
|
||||||
|
ctx, release := withOwnedMemory(ctx, experimental.MemoryAllocatorFunc(
|
||||||
|
func(_, max uint64) experimental.LinearMemory {
|
||||||
|
memory = &trackedLinearMemory{LinearMemory: allocate(0, max)}
|
||||||
|
return memory
|
||||||
|
}))
|
||||||
|
defer release()
|
||||||
|
rt := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCloseOnContextDone(true))
|
||||||
|
defer rt.Close(context.Background())
|
||||||
|
binary, err := hex.DecodeString(tt.wasm)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module, err := rt.Instantiate(ctx, binary)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Fatalf("instantiate: %v", err)
|
||||||
|
}
|
||||||
|
if !tt.wantErr {
|
||||||
|
if memory == nil || memory.freeCount != 0 {
|
||||||
|
t.Fatal("module did not allocate native memory")
|
||||||
|
}
|
||||||
|
if err := module.Close(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
release()
|
||||||
|
if memory == nil || memory.freeCount != 1 {
|
||||||
|
t.Fatal("host did not release memory exactly once")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
//go:build windows && (amd64 || arm64)
|
||||||
|
|
||||||
|
package ffmpeg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/tetratelabs/wazero/experimental"
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Keep large, short-lived WASM buffers out of the Go heap. Closing a module
|
||||||
|
// releases its committed pages immediately, without waiting for GC/scavenging.
|
||||||
|
func withLinearMemory(ctx context.Context) (context.Context, func()) {
|
||||||
|
return withOwnedMemory(ctx, experimental.MemoryAllocatorFunc(
|
||||||
|
func(_, max uint64) experimental.LinearMemory {
|
||||||
|
return &windowsLinearMemory{max: max}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reserve the address range once, committing zero-filled pages on demand. This
|
||||||
|
// avoids both copying the previous buffer and temporarily retaining two large
|
||||||
|
// Go allocations when memory.grow runs. The backing address never changes.
|
||||||
|
type windowsLinearMemory struct {
|
||||||
|
address uintptr
|
||||||
|
max uint64
|
||||||
|
size uint64
|
||||||
|
freed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *windowsLinearMemory) Reallocate(size uint64) []byte {
|
||||||
|
if m.freed || size > m.max || m.max > uint64(^uint(0)>>1) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if size == 0 {
|
||||||
|
return []byte{}
|
||||||
|
}
|
||||||
|
if m.address == 0 {
|
||||||
|
address, err := windows.VirtualAlloc(0, uintptr(m.max), windows.MEM_RESERVE, windows.PAGE_READWRITE)
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Errorf("ffmpeg: reserve WASM memory: %w", err))
|
||||||
|
}
|
||||||
|
m.address = address
|
||||||
|
}
|
||||||
|
if size > m.size {
|
||||||
|
_, err := windows.VirtualAlloc(m.address, uintptr(size), windows.MEM_COMMIT, windows.PAGE_READWRITE)
|
||||||
|
if err != nil {
|
||||||
|
if m.size == 0 {
|
||||||
|
// Instantiation cannot proceed without the minimum memory. Wazero
|
||||||
|
// has not taken ownership yet, so release the reservation here.
|
||||||
|
m.Free()
|
||||||
|
panic(fmt.Errorf("ffmpeg: commit WASM memory: %w", err))
|
||||||
|
}
|
||||||
|
return nil // memory.grow reports failure to the guest.
|
||||||
|
}
|
||||||
|
m.size = size
|
||||||
|
}
|
||||||
|
return unsafe.Slice((*byte)(unsafe.Pointer(m.address)), int(size))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *windowsLinearMemory) Free() {
|
||||||
|
if m.address != 0 {
|
||||||
|
_ = windows.VirtualFree(m.address, 0, windows.MEM_RELEASE)
|
||||||
|
m.address = 0
|
||||||
|
}
|
||||||
|
m.size = 0
|
||||||
|
m.freed = true
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
//go:build windows && (amd64 || arm64)
|
||||||
|
|
||||||
|
package ffmpeg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/tetratelabs/wazero/experimental"
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWindowsLinearMemoryGrowthAndRelease(t *testing.T) {
|
||||||
|
const page = 65536
|
||||||
|
m := &windowsLinearMemory{max: 4 * page}
|
||||||
|
defer m.Free()
|
||||||
|
first := m.Reallocate(page)
|
||||||
|
if len(first) != page {
|
||||||
|
t.Fatalf("initial allocation: %d", len(first))
|
||||||
|
}
|
||||||
|
first[0], first[page-1] = 17, 29
|
||||||
|
address := m.address
|
||||||
|
grown := m.Reallocate(3 * page)
|
||||||
|
if unsafe.SliceData(first) != unsafe.SliceData(grown) || grown[0] != 17 || grown[page-1] != 29 {
|
||||||
|
t.Fatal("growing memory moved or lost existing bytes")
|
||||||
|
}
|
||||||
|
for _, b := range grown[page:] {
|
||||||
|
if b != 0 {
|
||||||
|
t.Fatal("newly committed memory is not zero-filled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.Reallocate(5*page) != nil || m.address != address || m.size != 3*page {
|
||||||
|
t.Fatal("failed growth changed the existing allocation")
|
||||||
|
}
|
||||||
|
m.Free()
|
||||||
|
m.Free()
|
||||||
|
if m.address != 0 || m.Reallocate(page) != nil {
|
||||||
|
t.Fatal("freed memory can still be used")
|
||||||
|
}
|
||||||
|
var info windows.MemoryBasicInformation
|
||||||
|
if err := windows.VirtualQuery(address, &info, unsafe.Sizeof(info)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const memFree = 0x10000 // MEMORY_BASIC_INFORMATION.State: MEM_FREE.
|
||||||
|
if info.State != memFree {
|
||||||
|
t.Fatalf("pages remain reserved after Free: state=%x", info.State)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWindowsLinearMemoryModuleLifecycle(t *testing.T) {
|
||||||
|
testLinearMemoryModuleLifecycle(t, func(_, max uint64) experimental.LinearMemory {
|
||||||
|
return &windowsLinearMemory{max: max}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -151,7 +151,9 @@ func RunAcquired(ctx context.Context, video, audio Input, out io.Writer, format
|
|||||||
files := &inputFS{files: map[string]Input{"video": video, "audio": audio}}
|
files := &inputFS{files: map[string]Input{"video": video, "audio": audio}}
|
||||||
fsconfig := wazero.NewFSConfig().(sysfs.FSConfig).WithSysFSMount(files, "/inputs")
|
fsconfig := wazero.NewFSConfig().(sysfs.FSConfig).WithSysFSMount(files, "/inputs")
|
||||||
logs := &tailLog{}
|
logs := &tailLog{}
|
||||||
rc, err := wasm.Run(ctx, shared.runtime, shared.module, wasm.Args{
|
runCtx, freeMemory := withLinearMemory(ctx)
|
||||||
|
defer freeMemory()
|
||||||
|
rc, err := wasm.Run(runCtx, shared.runtime, shared.module, wasm.Args{
|
||||||
Name: "ffmpeg", Args: args, Stdout: out, Stderr: logs,
|
Name: "ffmpeg", Args: args, Stdout: out, Stderr: logs,
|
||||||
Config: func(c wazero.ModuleConfig) wazero.ModuleConfig { return c.WithFSConfig(fsconfig) },
|
Config: func(c wazero.ModuleConfig) wazero.ModuleConfig { return c.WithFSConfig(fsconfig) },
|
||||||
})
|
})
|
||||||
|
|||||||
+30
-13
@@ -87,8 +87,11 @@ type Task struct {
|
|||||||
blobRefLock *sync.Mutex
|
blobRefLock *sync.Mutex
|
||||||
blobURL string
|
blobURL string
|
||||||
runGeneration uint64
|
runGeneration uint64
|
||||||
speedArr []int64
|
speedArr []speedSample
|
||||||
uploadSpeedArr []int64
|
uploadSpeedArr []speedSample
|
||||||
|
downloadSampledAt time.Time
|
||||||
|
uploadSampledAt time.Time
|
||||||
|
receivedBytes int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// TaskRuntimeStatus is the lightweight, frequently refreshed view of a task.
|
// TaskRuntimeStatus is the lightweight, frequently refreshed view of a task.
|
||||||
@@ -195,7 +198,21 @@ func (t *Task) updateUploadSpeed(downloaded int64, usedTime float64) int64 {
|
|||||||
return calcSpeed(&t.uploadSpeedArr, downloaded, usedTime)
|
return calcSpeed(&t.uploadSpeedArr, downloaded, usedTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
func calcSpeed(speedArr *[]int64, downloaded int64, usedTime float64) int64 {
|
type speedSample struct {
|
||||||
|
bytes int64
|
||||||
|
seconds float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func sampleSeconds(lastSample *time.Time, now time.Time) float64 {
|
||||||
|
previous := *lastSample
|
||||||
|
*lastSample = now
|
||||||
|
if previous.IsZero() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return now.Sub(previous).Seconds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func calcSpeed(speedArr *[]speedSample, downloaded int64, usedTime float64) int64 {
|
||||||
if usedTime <= 0 {
|
if usedTime <= 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@@ -204,18 +221,18 @@ func calcSpeed(speedArr *[]int64, downloaded int64, usedTime float64) int64 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
*speedArr = append(*speedArr, downloaded)
|
*speedArr = append(*speedArr, speedSample{bytes: downloaded, seconds: usedTime})
|
||||||
// Record last 5 seconds of download speed to calculate the average speed
|
|
||||||
if len(*speedArr) > int(5.0/usedTime) {
|
|
||||||
*speedArr = (*speedArr)[1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
for _, v := range *speedArr {
|
var elapsed float64
|
||||||
total += v
|
first := len(*speedArr)
|
||||||
|
for first > 0 && elapsed < 5 {
|
||||||
|
first--
|
||||||
|
sample := (*speedArr)[first]
|
||||||
|
total += sample.bytes
|
||||||
|
elapsed += sample.seconds
|
||||||
}
|
}
|
||||||
|
*speedArr = (*speedArr)[first:]
|
||||||
return int64(float64(total) / float64(len(*speedArr)) / usedTime)
|
return int64(float64(total) / elapsed)
|
||||||
}
|
}
|
||||||
|
|
||||||
type TaskFilter struct {
|
type TaskFilter struct {
|
||||||
|
|||||||
@@ -1,9 +1,32 @@
|
|||||||
package download
|
package download
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTransferSpeedWithUnevenSamples(t *testing.T) {
|
||||||
|
var task Task
|
||||||
|
for _, sample := range []struct {
|
||||||
|
bytes int64
|
||||||
|
seconds float64
|
||||||
|
}{
|
||||||
|
{1000, 1},
|
||||||
|
{2000, 2},
|
||||||
|
{4000, 4},
|
||||||
|
{6000, 6},
|
||||||
|
} {
|
||||||
|
if got := task.updateSpeed(sample.bytes, sample.seconds); got != 1000 {
|
||||||
|
t.Errorf("download speed after %v seconds = %d, want 1000", sample.seconds, got)
|
||||||
|
}
|
||||||
|
if got := task.updateUploadSpeed(sample.bytes, sample.seconds); got != 1000 {
|
||||||
|
t.Errorf("upload speed after %v seconds = %d, want 1000", sample.seconds, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCalcSpeedResetOnRollback(t *testing.T) {
|
func TestCalcSpeedResetOnRollback(t *testing.T) {
|
||||||
speedArr := []int64{1024, 2048, 4096}
|
speedArr := []speedSample{{1024, 1}, {2048, 1}, {4096, 1}}
|
||||||
|
|
||||||
if got := calcSpeed(&speedArr, -512, 1); got != 0 {
|
if got := calcSpeed(&speedArr, -512, 1); got != 0 {
|
||||||
t.Fatalf("calcSpeed() = %d, want 0 after rollback", got)
|
t.Fatalf("calcSpeed() = %d, want 0 after rollback", got)
|
||||||
@@ -16,3 +39,17 @@ func TestCalcSpeedResetOnRollback(t *testing.T) {
|
|||||||
t.Fatalf("calcSpeed() = %d, want 1024 after reset", got)
|
t.Fatalf("calcSpeed() = %d, want 1024 after reset", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSampleSecondsUsesThePreviousSuccessfulSample(t *testing.T) {
|
||||||
|
start := time.Now()
|
||||||
|
var last time.Time
|
||||||
|
if got := sampleSeconds(&last, start); got != 0 {
|
||||||
|
t.Fatalf("first sample elapsed = %v, want 0", got)
|
||||||
|
}
|
||||||
|
if got := sampleSeconds(&last, start.Add(1500*time.Millisecond)); got != 1.5 {
|
||||||
|
t.Fatalf("elapsed after a delayed sample = %v, want 1.5", got)
|
||||||
|
}
|
||||||
|
if got := sampleSeconds(&last, start.Add(2*time.Second)); got != 0.5 {
|
||||||
|
t.Fatalf("elapsed after the next sample = %v, want 0.5", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,12 +19,6 @@ class SettingsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class SettingsSaveResult {
|
|
||||||
const SettingsSaveResult({required this.btRestartRequired});
|
|
||||||
|
|
||||||
final bool btRestartRequired;
|
|
||||||
}
|
|
||||||
|
|
||||||
class SettingsController extends AsyncNotifier<SettingsState> {
|
class SettingsController extends AsyncNotifier<SettingsState> {
|
||||||
Future<void> _saveTail = Future<void>.value();
|
Future<void> _saveTail = Future<void>.value();
|
||||||
int _saveRevision = 0;
|
int _saveRevision = 0;
|
||||||
@@ -42,7 +36,7 @@ class SettingsController extends AsyncNotifier<SettingsState> {
|
|||||||
state = AsyncValue.data(SettingsState(config: config));
|
state = AsyncValue.data(SettingsState(config: config));
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<SettingsSaveResult> save(DownloaderConfig config) {
|
Future<void> save(DownloaderConfig config) {
|
||||||
final snapshot = DownloaderConfig.fromJson(config.toJson());
|
final snapshot = DownloaderConfig.fromJson(config.toJson());
|
||||||
final revision = ++_saveRevision;
|
final revision = ++_saveRevision;
|
||||||
state = AsyncValue.data(SettingsState(config: config, saving: true));
|
state = AsyncValue.data(SettingsState(config: config, saving: true));
|
||||||
@@ -53,15 +47,10 @@ class SettingsController extends AsyncNotifier<SettingsState> {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<SettingsSaveResult> _save(DownloaderConfig config, int revision) async {
|
Future<void> _save(DownloaderConfig config, int revision) async {
|
||||||
try {
|
try {
|
||||||
final service = ref.read(gopeedServiceProvider);
|
final service = ref.read(gopeedServiceProvider);
|
||||||
final latest = await service.getConfig();
|
final latest = await service.getConfig();
|
||||||
final previousBt = (
|
|
||||||
latest.protocolConfig.bt.listenPort,
|
|
||||||
latest.protocolConfig.bt.disableDht,
|
|
||||||
latest.protocolConfig.bt.disablePex,
|
|
||||||
);
|
|
||||||
config.extra
|
config.extra
|
||||||
..windowState = latest.extra.windowState
|
..windowState = latest.extra.windowState
|
||||||
..bookmarks = latest.extra.bookmarks
|
..bookmarks = latest.extra.bookmarks
|
||||||
@@ -75,12 +64,6 @@ class SettingsController extends AsyncNotifier<SettingsState> {
|
|||||||
ref.read(appRuntimeControllerProvider.notifier).replaceDownloaderConfig(saved);
|
ref.read(appRuntimeControllerProvider.notifier).replaceDownloaderConfig(saved);
|
||||||
if (revision == _saveRevision) state = AsyncValue.data(SettingsState(config: saved));
|
if (revision == _saveRevision) state = AsyncValue.data(SettingsState(config: saved));
|
||||||
}
|
}
|
||||||
final savedBt = (
|
|
||||||
saved.protocolConfig.bt.listenPort,
|
|
||||||
saved.protocolConfig.bt.disableDht,
|
|
||||||
saved.protocolConfig.bt.disablePex,
|
|
||||||
);
|
|
||||||
return SettingsSaveResult(btRestartRequired: previousBt != savedBt);
|
|
||||||
} finally {
|
} finally {
|
||||||
if (ref.mounted && revision == _saveRevision && state.value?.saving == true) {
|
if (ref.mounted && revision == _saveRevision && state.value?.saving == true) {
|
||||||
state = AsyncValue.data(state.requireValue.copyWith(saving: false));
|
state = AsyncValue.data(state.requireValue.copyWith(saving: false));
|
||||||
|
|||||||
@@ -625,6 +625,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
|
|||||||
),
|
),
|
||||||
SettingsItem(
|
SettingsItem(
|
||||||
title: context.l10n.enableDht,
|
title: context.l10n.enableDht,
|
||||||
|
subtitle: context.l10n.restartRequired,
|
||||||
child: shad.Switch(
|
child: shad.Switch(
|
||||||
value: !config.protocolConfig.bt.disableDht,
|
value: !config.protocolConfig.bt.disableDht,
|
||||||
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disableDht = !value),
|
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disableDht = !value),
|
||||||
@@ -632,6 +633,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
|
|||||||
),
|
),
|
||||||
SettingsItem(
|
SettingsItem(
|
||||||
title: context.l10n.enablePex,
|
title: context.l10n.enablePex,
|
||||||
|
subtitle: context.l10n.restartRequired,
|
||||||
child: shad.Switch(
|
child: shad.Switch(
|
||||||
value: !config.protocolConfig.bt.disablePex,
|
value: !config.protocolConfig.bt.disablePex,
|
||||||
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disablePex = !value),
|
onChanged: (value) => _mutateConfig((next) => next.protocolConfig.bt.disablePex = !value),
|
||||||
@@ -1202,10 +1204,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
|
|||||||
final snapshot = DownloaderConfig.fromJson(config.toJson());
|
final snapshot = DownloaderConfig.fromJson(config.toJson());
|
||||||
_loadedSignature = _signature(snapshot);
|
_loadedSignature = _signature(snapshot);
|
||||||
try {
|
try {
|
||||||
final result = await ref.read(settingsControllerProvider.notifier).save(snapshot);
|
await ref.read(settingsControllerProvider.notifier).save(snapshot);
|
||||||
if (mounted && result.btRestartRequired) {
|
|
||||||
_toast(context.l10n.restartRequired, type: AppToastType.info);
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (mounted) _toast(error.toString());
|
if (mounted) _toast(error.toString());
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import '../../application/pending_download.dart';
|
|||||||
import '../../application/task_list_navigation.dart';
|
import '../../application/task_list_navigation.dart';
|
||||||
import '../widgets/history_search_field.dart';
|
import '../widgets/history_search_field.dart';
|
||||||
import '../widgets/create_task_action_buttons.dart';
|
import '../widgets/create_task_action_buttons.dart';
|
||||||
import '../widgets/create_task_advanced_toggle.dart';
|
|
||||||
import '../widgets/resolve_download_dialog.dart';
|
import '../widgets/resolve_download_dialog.dart';
|
||||||
|
|
||||||
class CreateTaskWindowPage extends ConsumerStatefulWidget {
|
class CreateTaskWindowPage extends ConsumerStatefulWidget {
|
||||||
@@ -561,11 +560,20 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
Align(
|
Align(
|
||||||
alignment: AlignmentDirectional.centerStart,
|
alignment: Alignment.centerLeft,
|
||||||
child: CreateTaskAdvancedToggle(
|
child: GestureDetector(
|
||||||
key: const ValueKey('create-task-advanced-toggle'),
|
onTap: _toggleAdvanced,
|
||||||
expanded: _showAdvanced,
|
child: Row(
|
||||||
onPressed: _toggleAdvanced,
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
context.l10n.advanced,
|
||||||
|
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
_TripleChevronIcon(expanded: _showAdvanced, color: palette.textSecondary),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
AnimatedCrossFade(
|
AnimatedCrossFade(
|
||||||
@@ -1925,6 +1933,30 @@ class _MiniInputAction extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _TripleChevronIcon extends StatelessWidget {
|
||||||
|
const _TripleChevronIcon({required this.expanded, required this.color});
|
||||||
|
|
||||||
|
final bool expanded;
|
||||||
|
final Color color;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final icon = expanded ? Icons.expand_less : Icons.expand_more;
|
||||||
|
return SizedBox(
|
||||||
|
width: 14,
|
||||||
|
height: 18,
|
||||||
|
child: Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Positioned(top: 0, left: 0, child: Icon(icon, size: 14, color: color)),
|
||||||
|
Positioned(top: 4, left: 0, child: Icon(icon, size: 14, color: color)),
|
||||||
|
Positioned(top: 8, left: 0, child: Icon(icon, size: 14, color: color)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class _SegmentButton extends StatelessWidget {
|
class _SegmentButton extends StatelessWidget {
|
||||||
const _SegmentButton({required this.label, required this.active, required this.onTap});
|
const _SegmentButton({required this.label, required this.active, required this.onTap});
|
||||||
|
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
|
||||||
|
|
||||||
import '../../../../l10n/l10n.dart';
|
|
||||||
import '../../../../shared/theme/app_design_tokens.dart';
|
|
||||||
import '../../../../shared/theme/app_palette.dart';
|
|
||||||
|
|
||||||
/// A quiet disclosure control with the same keyboard behavior as other buttons.
|
|
||||||
class CreateTaskAdvancedToggle extends StatelessWidget {
|
|
||||||
const CreateTaskAdvancedToggle({super.key, required this.expanded, required this.onPressed});
|
|
||||||
|
|
||||||
final bool expanded;
|
|
||||||
final VoidCallback onPressed;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final palette = AppPalette.of(context);
|
|
||||||
final reduceMotion = MediaQuery.disableAnimationsOf(context);
|
|
||||||
return Semantics(
|
|
||||||
expanded: expanded,
|
|
||||||
child: ButtonStyleOverride.inherit(
|
|
||||||
padding: (context, states, value) => const EdgeInsets.symmetric(vertical: AppDesignTokens.space12),
|
|
||||||
child: GhostButton(
|
|
||||||
onPressed: onPressed,
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(minHeight: 20),
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
|
||||||
context.l10n.advanced,
|
|
||||||
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w600),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: AppDesignTokens.space8),
|
|
||||||
AnimatedRotation(
|
|
||||||
turns: expanded ? 0.5 : 0,
|
|
||||||
duration: reduceMotion ? Duration.zero : const Duration(milliseconds: 180),
|
|
||||||
curve: Curves.easeOutCubic,
|
|
||||||
child: Icon(Icons.keyboard_arrow_down, size: 16, color: palette.textSecondary),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "اسم الفئة",
|
"categoryName": "اسم الفئة",
|
||||||
"categoryPath": "مسار الفئة",
|
"categoryPath": "مسار الفئة",
|
||||||
"autoCategorizeByExtension": "تصنيف تلقائي حسب نوع الملف",
|
"autoCategorizeByExtension": "تصنيف تلقائي حسب نوع الملف",
|
||||||
"autoCategorizeByExtensionDescription": "توجيه التنزيلات إلى مجلد الفئة تلقائيًا حسب امتداد الملف عند الحفظ في مجلد التنزيل الافتراضي",
|
"autoCategorizeByExtensionDescription": "توجيه التنزيلات إلى مجلد الفئة تلقائيًا حسب امتداد الملف عند الحفظ في مجلد التنزيل الافتراضي.",
|
||||||
"categoryExtensions": "امتدادات الملفات",
|
"categoryExtensions": "امتدادات الملفات",
|
||||||
"categoryExtensionsUsageHint": "افصل الامتدادات بفواصل أو مسافات ثم اضغط Enter.",
|
"categoryExtensionsUsageHint": "افصل الامتدادات بفواصل أو مسافات ثم اضغط Enter.",
|
||||||
"categoryExtensionsEmptyHint": "بدون الامتدادات، لن تُحفظ الملفات في هذا التصنيف تلقائيًا.",
|
"categoryExtensionsEmptyHint": "بدون الامتدادات، لن تُحفظ الملفات في هذا التصنيف تلقائيًا.",
|
||||||
|
|||||||
@@ -215,7 +215,7 @@
|
|||||||
"categoryName": "Kateqoriyanın Adı",
|
"categoryName": "Kateqoriyanın Adı",
|
||||||
"categoryPath": "Kateqoriyanın Yolu",
|
"categoryPath": "Kateqoriyanın Yolu",
|
||||||
"autoCategorizeByExtension": "Fayl tipinə görə avtomatik kateqoriyalaşdırma",
|
"autoCategorizeByExtension": "Fayl tipinə görə avtomatik kateqoriyalaşdırma",
|
||||||
"autoCategorizeByExtensionDescription": "Standart yükləmə qovluğuna yadda saxlanarkən yükləmələr fayl uzantısına görə avtomatik olaraq kateqoriya qovluğuna yönləndirilir",
|
"autoCategorizeByExtensionDescription": "Standart yükləmə qovluğuna yadda saxlanarkən yükləmələr fayl uzantısına görə avtomatik olaraq kateqoriya qovluğuna yönləndirilir.",
|
||||||
"categoryExtensions": "Fayl uzantıları",
|
"categoryExtensions": "Fayl uzantıları",
|
||||||
"categoryExtensionsUsageHint": "Uzantıları vergül və ya boşluqla ayırın, sonra Enter-a basın.",
|
"categoryExtensionsUsageHint": "Uzantıları vergül və ya boşluqla ayırın, sonra Enter-a basın.",
|
||||||
"categoryExtensionsEmptyHint": "Uzantı yoxdursa, fayllar bu kateqoriyaya avtomatik olaraq saxlanmır.",
|
"categoryExtensionsEmptyHint": "Uzantı yoxdursa, fayllar bu kateqoriyaya avtomatik olaraq saxlanmır.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nom de la categoria",
|
"categoryName": "Nom de la categoria",
|
||||||
"categoryPath": "Ruta de la categoria",
|
"categoryPath": "Ruta de la categoria",
|
||||||
"autoCategorizeByExtension": "Categoritza automàticament segons el tipus de fitxer",
|
"autoCategorizeByExtension": "Categoritza automàticament segons el tipus de fitxer",
|
||||||
"autoCategorizeByExtensionDescription": "Les baixades es desen a la carpeta de categoria segons l'extensió del fitxer en utilitzar la carpeta de baixades predeterminada",
|
"autoCategorizeByExtensionDescription": "Les baixades es desen a la carpeta de categoria segons l'extensió del fitxer en utilitzar la carpeta de baixades predeterminada.",
|
||||||
"categoryExtensions": "Extensions de fitxer",
|
"categoryExtensions": "Extensions de fitxer",
|
||||||
"categoryExtensionsUsageHint": "Separa les extensions amb comes o espais i prem Retorn.",
|
"categoryExtensionsUsageHint": "Separa les extensions amb comes o espais i prem Retorn.",
|
||||||
"categoryExtensionsEmptyHint": "Sense extensions, els fitxers no es desaran aquí automàticament.",
|
"categoryExtensionsEmptyHint": "Sense extensions, els fitxers no es desaran aquí automàticament.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Kategoriename",
|
"categoryName": "Kategoriename",
|
||||||
"categoryPath": "Kategoriepfad",
|
"categoryPath": "Kategoriepfad",
|
||||||
"autoCategorizeByExtension": "Nach Dateityp automatisch kategorisieren",
|
"autoCategorizeByExtension": "Nach Dateityp automatisch kategorisieren",
|
||||||
"autoCategorizeByExtensionDescription": "Downloads werden beim Speichern im Standard-Download-Ordner anhand der Dateiendung automatisch einem Kategorieordner zugeordnet",
|
"autoCategorizeByExtensionDescription": "Downloads werden beim Speichern im Standard-Download-Ordner anhand der Dateiendung automatisch einem Kategorieordner zugeordnet.",
|
||||||
"categoryExtensions": "Dateiendungen",
|
"categoryExtensions": "Dateiendungen",
|
||||||
"categoryExtensionsUsageHint": "Trenne Endungen mit Kommas oder Leerzeichen und drücke Enter.",
|
"categoryExtensionsUsageHint": "Trenne Endungen mit Kommas oder Leerzeichen und drücke Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Ohne Endungen werden Dateien nicht automatisch dieser Kategorie zugeordnet.",
|
"categoryExtensionsEmptyHint": "Ohne Endungen werden Dateien nicht automatisch dieser Kategorie zugeordnet.",
|
||||||
|
|||||||
@@ -222,7 +222,7 @@
|
|||||||
"categoryName": "Category Name",
|
"categoryName": "Category Name",
|
||||||
"categoryPath": "Category Path",
|
"categoryPath": "Category Path",
|
||||||
"autoCategorizeByExtension": "Auto-categorize by file type",
|
"autoCategorizeByExtension": "Auto-categorize by file type",
|
||||||
"autoCategorizeByExtensionDescription": "Automatically route downloads into a category folder based on the file name when saving to the default download folder",
|
"autoCategorizeByExtensionDescription": "Automatically route downloads into a category folder based on the file name when saving to the default download folder.",
|
||||||
"categoryExtensions": "Associated Extensions",
|
"categoryExtensions": "Associated Extensions",
|
||||||
"categoryExtensionsUsageHint": "Separate suffixes with commas or spaces, then press Enter.",
|
"categoryExtensionsUsageHint": "Separate suffixes with commas or spaces, then press Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Without extensions, files won't be saved into this category automatically.",
|
"categoryExtensionsEmptyHint": "Without extensions, files won't be saved into this category automatically.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nombre de categoría",
|
"categoryName": "Nombre de categoría",
|
||||||
"categoryPath": "Ruta de categoría",
|
"categoryPath": "Ruta de categoría",
|
||||||
"autoCategorizeByExtension": "Categorizar automáticamente por tipo de archivo",
|
"autoCategorizeByExtension": "Categorizar automáticamente por tipo de archivo",
|
||||||
"autoCategorizeByExtensionDescription": "Las descargas se guardan automáticamente en la carpeta de categoría según la extensión del archivo al usar la carpeta de descargas predeterminada",
|
"autoCategorizeByExtensionDescription": "Las descargas se guardan automáticamente en la carpeta de categoría según la extensión del archivo al usar la carpeta de descargas predeterminada.",
|
||||||
"categoryExtensions": "Extensiones de archivo",
|
"categoryExtensions": "Extensiones de archivo",
|
||||||
"categoryExtensionsUsageHint": "Separa las extensiones con comas o espacios y pulsa Intro.",
|
"categoryExtensionsUsageHint": "Separa las extensiones con comas o espacios y pulsa Intro.",
|
||||||
"categoryExtensionsEmptyHint": "Sin extensiones, los archivos no se guardarán automáticamente en esta categoría.",
|
"categoryExtensionsEmptyHint": "Sin extensiones, los archivos no se guardarán automáticamente en esta categoría.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "نام دستهبندی",
|
"categoryName": "نام دستهبندی",
|
||||||
"categoryPath": "مسیر دستهبندی",
|
"categoryPath": "مسیر دستهبندی",
|
||||||
"autoCategorizeByExtension": "دستهبندی خودکار بر اساس نوع فایل",
|
"autoCategorizeByExtension": "دستهبندی خودکار بر اساس نوع فایل",
|
||||||
"autoCategorizeByExtensionDescription": "هنگام ذخیره در پوشه پیشفرض دانلود، دانلودها بر اساس پسوند فایل به پوشه دسته مربوطه منتقل میشوند",
|
"autoCategorizeByExtensionDescription": "هنگام ذخیره در پوشه پیشفرض دانلود، دانلودها بر اساس پسوند فایل به پوشه دسته مربوطه منتقل میشوند.",
|
||||||
"categoryExtensions": "پسوندهای فایل",
|
"categoryExtensions": "پسوندهای فایل",
|
||||||
"categoryExtensionsUsageHint": "پسوندها را با ویرگول یا فاصله جدا کنید و Enter را بزنید.",
|
"categoryExtensionsUsageHint": "پسوندها را با ویرگول یا فاصله جدا کنید و Enter را بزنید.",
|
||||||
"categoryExtensionsEmptyHint": "بدون پسوندها، فایلها بهصورت خودکار در این دسته ذخیره نمیشوند.",
|
"categoryExtensionsEmptyHint": "بدون پسوندها، فایلها بهصورت خودکار در این دسته ذخیره نمیشوند.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nom de la catégorie",
|
"categoryName": "Nom de la catégorie",
|
||||||
"categoryPath": "Chemin de la catégorie",
|
"categoryPath": "Chemin de la catégorie",
|
||||||
"autoCategorizeByExtension": "Catégoriser automatiquement selon le type de fichier",
|
"autoCategorizeByExtension": "Catégoriser automatiquement selon le type de fichier",
|
||||||
"autoCategorizeByExtensionDescription": "Les téléchargements sont placés dans un dossier de catégorie selon l'extension du fichier lors de l'enregistrement dans le dossier de téléchargement par défaut",
|
"autoCategorizeByExtensionDescription": "Les téléchargements sont placés dans un dossier de catégorie selon l'extension du fichier lors de l'enregistrement dans le dossier de téléchargement par défaut.",
|
||||||
"categoryExtensions": "Extensions de fichier",
|
"categoryExtensions": "Extensions de fichier",
|
||||||
"categoryExtensionsUsageHint": "Séparez les extensions par virgules ou espaces, puis appuyez sur Entrée.",
|
"categoryExtensionsUsageHint": "Séparez les extensions par virgules ou espaces, puis appuyez sur Entrée.",
|
||||||
"categoryExtensionsEmptyHint": "Sans extensions, les fichiers ne seront pas enregistrés ici automatiquement.",
|
"categoryExtensionsEmptyHint": "Sans extensions, les fichiers ne seront pas enregistrés ici automatiquement.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Kategória neve",
|
"categoryName": "Kategória neve",
|
||||||
"categoryPath": "Kategória útvonala",
|
"categoryPath": "Kategória útvonala",
|
||||||
"autoCategorizeByExtension": "Automatikus kategorizálás fájltípus szerint",
|
"autoCategorizeByExtension": "Automatikus kategorizálás fájltípus szerint",
|
||||||
"autoCategorizeByExtensionDescription": "Az alapértelmezett letöltési mappa használatakor a letöltések a fájl kiterjesztése alapján automatikusan a kategória mappájába kerülnek",
|
"autoCategorizeByExtensionDescription": "Az alapértelmezett letöltési mappa használatakor a letöltések a fájl kiterjesztése alapján automatikusan a kategória mappájába kerülnek.",
|
||||||
"categoryExtensions": "Fájlkiterjesztések",
|
"categoryExtensions": "Fájlkiterjesztések",
|
||||||
"categoryExtensionsUsageHint": "A kiterjesztéseket vesszővel vagy szóközzel válaszd el, majd nyomd le az Enter billentyűt.",
|
"categoryExtensionsUsageHint": "A kiterjesztéseket vesszővel vagy szóközzel válaszd el, majd nyomd le az Enter billentyűt.",
|
||||||
"categoryExtensionsEmptyHint": "Kiterjesztések nélkül a fájlok nem kerülnek automatikusan ebbe a kategóriába.",
|
"categoryExtensionsEmptyHint": "Kiterjesztések nélkül a fájlok nem kerülnek automatikusan ebbe a kategóriába.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nama Kategori",
|
"categoryName": "Nama Kategori",
|
||||||
"categoryPath": "Path Kategori",
|
"categoryPath": "Path Kategori",
|
||||||
"autoCategorizeByExtension": "Kategorikan otomatis berdasarkan jenis file",
|
"autoCategorizeByExtension": "Kategorikan otomatis berdasarkan jenis file",
|
||||||
"autoCategorizeByExtensionDescription": "Unduhan dialihkan ke folder kategori berdasarkan ekstensi file saat disimpan ke folder unduhan bawaan",
|
"autoCategorizeByExtensionDescription": "Unduhan dialihkan ke folder kategori berdasarkan ekstensi file saat disimpan ke folder unduhan bawaan.",
|
||||||
"categoryExtensions": "Ekstensi file",
|
"categoryExtensions": "Ekstensi file",
|
||||||
"categoryExtensionsUsageHint": "Pisahkan ekstensi dengan koma atau spasi, lalu tekan Enter.",
|
"categoryExtensionsUsageHint": "Pisahkan ekstensi dengan koma atau spasi, lalu tekan Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Tanpa ekstensi, file tidak akan otomatis disimpan ke kategori ini.",
|
"categoryExtensionsEmptyHint": "Tanpa ekstensi, file tidak akan otomatis disimpan ke kategori ini.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nome categoria",
|
"categoryName": "Nome categoria",
|
||||||
"categoryPath": "Percorso categoria",
|
"categoryPath": "Percorso categoria",
|
||||||
"autoCategorizeByExtension": "Categorizza automaticamente per tipo di file",
|
"autoCategorizeByExtension": "Categorizza automaticamente per tipo di file",
|
||||||
"autoCategorizeByExtensionDescription": "Il download viene instradato automaticamente nella cartella della categoria in base all'estensione quando si salva nella cartella di download predefinita",
|
"autoCategorizeByExtensionDescription": "Il download viene instradato automaticamente nella cartella della categoria in base all'estensione quando si salva nella cartella di download predefinita.",
|
||||||
"categoryExtensions": "Estensioni file",
|
"categoryExtensions": "Estensioni file",
|
||||||
"categoryExtensionsUsageHint": "Separa le estensioni con virgole o spazi e premi Invio.",
|
"categoryExtensionsUsageHint": "Separa le estensioni con virgole o spazi e premi Invio.",
|
||||||
"categoryExtensionsEmptyHint": "Senza estensioni, i file non verranno salvati qui automaticamente.",
|
"categoryExtensionsEmptyHint": "Senza estensioni, i file non verranno salvati qui automaticamente.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "カテゴリ名",
|
"categoryName": "カテゴリ名",
|
||||||
"categoryPath": "カテゴリパス",
|
"categoryPath": "カテゴリパス",
|
||||||
"autoCategorizeByExtension": "ファイル種別で自動分類",
|
"autoCategorizeByExtension": "ファイル種別で自動分類",
|
||||||
"autoCategorizeByExtensionDescription": "既定のダウンロードフォルダーに保存する際、拡張子に基づいて分類フォルダーへ自動的に振り分けます",
|
"autoCategorizeByExtensionDescription": "既定のダウンロードフォルダーに保存する際、拡張子に基づいて分類フォルダーへ自動的に振り分けます。",
|
||||||
"categoryExtensions": "ファイル拡張子",
|
"categoryExtensions": "ファイル拡張子",
|
||||||
"categoryExtensionsUsageHint": "カンマやスペースで拡張子を区切り、Enterで追加します。",
|
"categoryExtensionsUsageHint": "カンマやスペースで拡張子を区切り、Enterで追加します。",
|
||||||
"categoryExtensionsEmptyHint": "拡張子が未設定の場合、ファイルは自動的にこの分類へ保存されません。",
|
"categoryExtensionsEmptyHint": "拡張子が未設定の場合、ファイルは自動的にこの分類へ保存されません。",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "카테고리 이름",
|
"categoryName": "카테고리 이름",
|
||||||
"categoryPath": "카테고리 경로",
|
"categoryPath": "카테고리 경로",
|
||||||
"autoCategorizeByExtension": "파일 형식별 자동 분류",
|
"autoCategorizeByExtension": "파일 형식별 자동 분류",
|
||||||
"autoCategorizeByExtensionDescription": "기본 다운로드 폴더에 저장할 때 확장자에 따라 분류 폴더로 자동 이동합니다",
|
"autoCategorizeByExtensionDescription": "기본 다운로드 폴더에 저장할 때 확장자에 따라 분류 폴더로 자동 이동합니다.",
|
||||||
"categoryExtensions": "파일 확장자",
|
"categoryExtensions": "파일 확장자",
|
||||||
"categoryExtensionsUsageHint": "쉼표나 공백으로 확장자를 구분하고 Enter를 눌러 추가하세요.",
|
"categoryExtensionsUsageHint": "쉼표나 공백으로 확장자를 구분하고 Enter를 눌러 추가하세요.",
|
||||||
"categoryExtensionsEmptyHint": "확장자가 없으면 파일이 이 분류로 자동 저장되지 않습니다.",
|
"categoryExtensionsEmptyHint": "확장자가 없으면 파일이 이 분류로 자동 저장되지 않습니다.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nazwa kategorii",
|
"categoryName": "Nazwa kategorii",
|
||||||
"categoryPath": "Ścieżka kategorii",
|
"categoryPath": "Ścieżka kategorii",
|
||||||
"autoCategorizeByExtension": "Automatyczna kategorizacja według typu pliku",
|
"autoCategorizeByExtension": "Automatyczna kategorizacja według typu pliku",
|
||||||
"autoCategorizeByExtensionDescription": "Pobierane pliki są automatycznie zapisywane w folderze kategorii na podstawie rozszerzenia, gdy używany jest domyślny folder pobierania",
|
"autoCategorizeByExtensionDescription": "Pobierane pliki są automatycznie zapisywane w folderze kategorii na podstawie rozszerzenia, gdy używany jest domyślny folder pobierania.",
|
||||||
"categoryExtensions": "Rozszerzenia plików",
|
"categoryExtensions": "Rozszerzenia plików",
|
||||||
"categoryExtensionsUsageHint": "Rozdzielaj rozszerzenia przecinkami lub spacjami i naciskaj Enter.",
|
"categoryExtensionsUsageHint": "Rozdzielaj rozszerzenia przecinkami lub spacjami i naciskaj Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Bez rozszerzeń pliki nie będą automatycznie zapisywane w tej kategorii.",
|
"categoryExtensionsEmptyHint": "Bez rozszerzeń pliki nie będą automatycznie zapisywane w tej kategorii.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Nome da Categoria",
|
"categoryName": "Nome da Categoria",
|
||||||
"categoryPath": "Caminho da Categoria",
|
"categoryPath": "Caminho da Categoria",
|
||||||
"autoCategorizeByExtension": "Categorizar automaticamente por tipo de arquivo",
|
"autoCategorizeByExtension": "Categorizar automaticamente por tipo de arquivo",
|
||||||
"autoCategorizeByExtensionDescription": "Envia os downloads para a pasta da categoria com base na extensão ao salvar na pasta de download padrão",
|
"autoCategorizeByExtensionDescription": "Envia os downloads para a pasta da categoria com base na extensão ao salvar na pasta de download padrão.",
|
||||||
"categoryExtensions": "Extensões de arquivo",
|
"categoryExtensions": "Extensões de arquivo",
|
||||||
"categoryExtensionsUsageHint": "Separe as extensões com vírgulas ou espaços e prima Enter.",
|
"categoryExtensionsUsageHint": "Separe as extensões com vírgulas ou espaços e prima Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Sem extensões, os ficheiros não serão guardados aqui automaticamente.",
|
"categoryExtensionsEmptyHint": "Sem extensões, os ficheiros não serão guardados aqui automaticamente.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Название категории",
|
"categoryName": "Название категории",
|
||||||
"categoryPath": "Путь категории",
|
"categoryPath": "Путь категории",
|
||||||
"autoCategorizeByExtension": "Автокатегоризация по типу файла",
|
"autoCategorizeByExtension": "Автокатегоризация по типу файла",
|
||||||
"autoCategorizeByExtensionDescription": "Загрузки автоматически сохраняются в папку категории по расширению файла, если выбрана папка загрузки по умолчанию",
|
"autoCategorizeByExtensionDescription": "Загрузки автоматически сохраняются в папку категории по расширению файла, если выбрана папка загрузки по умолчанию.",
|
||||||
"categoryExtensions": "Расширения файлов",
|
"categoryExtensions": "Расширения файлов",
|
||||||
"categoryExtensionsUsageHint": "Разделяйте расширения запятыми или пробелами и нажимайте Enter.",
|
"categoryExtensionsUsageHint": "Разделяйте расширения запятыми или пробелами и нажимайте Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Без расширений файлы не будут автоматически сохранены в эту категорию.",
|
"categoryExtensionsEmptyHint": "Без расширений файлы не будут автоматически сохранены в эту категорию.",
|
||||||
|
|||||||
@@ -222,7 +222,7 @@
|
|||||||
"categoryName": "Názov kategórie",
|
"categoryName": "Názov kategórie",
|
||||||
"categoryPath": "Cesta kategórie",
|
"categoryPath": "Cesta kategórie",
|
||||||
"autoCategorizeByExtension": "Automatická kategorizácia podľa typu súboru",
|
"autoCategorizeByExtension": "Automatická kategorizácia podľa typu súboru",
|
||||||
"autoCategorizeByExtensionDescription": "Sťahovania sa pri ukladaní do predvoleného priečinka sťahovania automaticky presúvajú do priečinka kategórie podľa prípony súboru",
|
"autoCategorizeByExtensionDescription": "Sťahovania sa pri ukladaní do predvoleného priečinka sťahovania automaticky presúvajú do priečinka kategórie podľa prípony súboru.",
|
||||||
"categoryExtensions": "Prípony súborov",
|
"categoryExtensions": "Prípony súborov",
|
||||||
"categoryExtensionsUsageHint": "Oddeľujte prípony čiarkami alebo medzerami a stlačte Enter.",
|
"categoryExtensionsUsageHint": "Oddeľujte prípony čiarkami alebo medzerami a stlačte Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Bez prípon sa súbory automaticky neuložia do tejto kategórie.",
|
"categoryExtensionsEmptyHint": "Bez prípon sa súbory automaticky neuložia do tejto kategórie.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "வகை பெயர்",
|
"categoryName": "வகை பெயர்",
|
||||||
"categoryPath": "வகை பாதை",
|
"categoryPath": "வகை பாதை",
|
||||||
"autoCategorizeByExtension": "கோப்பு வகை வாரியாக தானாக வகைப்படுத்து",
|
"autoCategorizeByExtension": "கோப்பு வகை வாரியாக தானாக வகைப்படுத்து",
|
||||||
"autoCategorizeByExtensionDescription": "இயல்புநிலை பதிவிறக்கக் கோப்புறையில் சேமிக்கும்போது, கோப்பு நீட்டிப்பின் அடிப்படையில் வகைக் கோப்புறைக்கு தானாக அனுப்பப்படும்",
|
"autoCategorizeByExtensionDescription": "இயல்புநிலை பதிவிறக்கக் கோப்புறையில் சேமிக்கும்போது, கோப்பு நீட்டிப்பின் அடிப்படையில் வகைக் கோப்புறைக்கு தானாக அனுப்பப்படும்.",
|
||||||
"categoryExtensions": "கோப்பு நீட்டிப்புகள்",
|
"categoryExtensions": "கோப்பு நீட்டிப்புகள்",
|
||||||
"categoryExtensionsUsageHint": "நீட்டிப்புகளை காற்புள்ளிகள் அல்லது இடைவெளிகளால் பிரித்து Enter அழுத்தவும்.",
|
"categoryExtensionsUsageHint": "நீட்டிப்புகளை காற்புள்ளிகள் அல்லது இடைவெளிகளால் பிரித்து Enter அழுத்தவும்.",
|
||||||
"categoryExtensionsEmptyHint": "நீட்டிப்புகள் இல்லாததால், கோப்புகள் இந்த வகைப்பாட்டில் தானாகச் சேமிக்கப்படாது.",
|
"categoryExtensionsEmptyHint": "நீட்டிப்புகள் இல்லாததால், கோப்புகள் இந்த வகைப்பாட்டில் தானாகச் சேமிக்கப்படாது.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Kategori Adı",
|
"categoryName": "Kategori Adı",
|
||||||
"categoryPath": "Kategori Yolu",
|
"categoryPath": "Kategori Yolu",
|
||||||
"autoCategorizeByExtension": "Dosya tipine göre otomatik sınıflandır",
|
"autoCategorizeByExtension": "Dosya tipine göre otomatik sınıflandır",
|
||||||
"autoCategorizeByExtensionDescription": "Varsayılan indirme klasörüne kaydedilirken dosya uzantısına göre ilgili klasöre otomatik yönlendirir",
|
"autoCategorizeByExtensionDescription": "Varsayılan indirme klasörüne kaydedilirken dosya uzantısına göre ilgili klasöre otomatik yönlendirir.",
|
||||||
"categoryExtensions": "Dosya uzantıları",
|
"categoryExtensions": "Dosya uzantıları",
|
||||||
"categoryExtensionsUsageHint": "Sonekleri virgül veya boşlukla ayırıp Enter'a basın.",
|
"categoryExtensionsUsageHint": "Sonekleri virgül veya boşlukla ayırıp Enter'a basın.",
|
||||||
"categoryExtensionsEmptyHint": "Uzantı yoksa dosyalar bu kategoriye otomatik olarak kaydedilmez.",
|
"categoryExtensionsEmptyHint": "Uzantı yoksa dosyalar bu kategoriye otomatik olarak kaydedilmez.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Назва категорії",
|
"categoryName": "Назва категорії",
|
||||||
"categoryPath": "Шлях категорії",
|
"categoryPath": "Шлях категорії",
|
||||||
"autoCategorizeByExtension": "Автокатегоризація за типом файлу",
|
"autoCategorizeByExtension": "Автокатегоризація за типом файлу",
|
||||||
"autoCategorizeByExtensionDescription": "Завантаження автоматично зберігаються в папку категорії за розширенням файлу, якщо вибрано папку завантаження за замовчуванням",
|
"autoCategorizeByExtensionDescription": "Завантаження автоматично зберігаються в папку категорії за розширенням файлу, якщо вибрано папку завантаження за замовчуванням.",
|
||||||
"categoryExtensions": "Розширення файлів",
|
"categoryExtensions": "Розширення файлів",
|
||||||
"categoryExtensionsUsageHint": "Розділяйте розширення комами або пробілами та натискайте Enter.",
|
"categoryExtensionsUsageHint": "Розділяйте розширення комами або пробілами та натискайте Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Без розширень файли не зберігатимуться в цю категорію автоматично.",
|
"categoryExtensionsEmptyHint": "Без розширень файли не зберігатимуться в цю категорію автоматично.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "Tên danh mục",
|
"categoryName": "Tên danh mục",
|
||||||
"categoryPath": "Đường dẫn danh mục",
|
"categoryPath": "Đường dẫn danh mục",
|
||||||
"autoCategorizeByExtension": "Tự động phân loại theo loại tệp",
|
"autoCategorizeByExtension": "Tự động phân loại theo loại tệp",
|
||||||
"autoCategorizeByExtensionDescription": "Tải xuống sẽ được chuyển vào thư mục danh mục dựa trên phần mở rộng tệp khi lưu vào thư mục tải xuống mặc định",
|
"autoCategorizeByExtensionDescription": "Tải xuống sẽ được chuyển vào thư mục danh mục dựa trên phần mở rộng tệp khi lưu vào thư mục tải xuống mặc định.",
|
||||||
"categoryExtensions": "Phần mở rộng tệp",
|
"categoryExtensions": "Phần mở rộng tệp",
|
||||||
"categoryExtensionsUsageHint": "Phân tách phần mở rộng bằng dấu phẩy hoặc khoảng trắng rồi nhấn Enter.",
|
"categoryExtensionsUsageHint": "Phân tách phần mở rộng bằng dấu phẩy hoặc khoảng trắng rồi nhấn Enter.",
|
||||||
"categoryExtensionsEmptyHint": "Không có phần mở rộng, tệp sẽ không tự động được lưu vào danh mục này.",
|
"categoryExtensionsEmptyHint": "Không có phần mở rộng, tệp sẽ không tự động được lưu vào danh mục này.",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "分类名称",
|
"categoryName": "分类名称",
|
||||||
"categoryPath": "分类路径",
|
"categoryPath": "分类路径",
|
||||||
"autoCategorizeByExtension": "按文件类型自动分类",
|
"autoCategorizeByExtension": "按文件类型自动分类",
|
||||||
"autoCategorizeByExtensionDescription": "保存到默认下载目录时,根据文件后缀自动归入对应分类文件夹",
|
"autoCategorizeByExtensionDescription": "保存到默认下载目录时,根据文件后缀自动归入对应分类文件夹。",
|
||||||
"categoryExtensions": "文件后缀关联",
|
"categoryExtensions": "文件后缀关联",
|
||||||
"categoryExtensionsUsageHint": "支持逗号/空格分隔后缀,按回车添加。",
|
"categoryExtensionsUsageHint": "支持逗号/空格分隔后缀,按回车添加。",
|
||||||
"categoryExtensionsEmptyHint": "未设置后缀,文件不会自动归入此分类。",
|
"categoryExtensionsEmptyHint": "未设置后缀,文件不会自动归入此分类。",
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
"categoryName": "分類名稱",
|
"categoryName": "分類名稱",
|
||||||
"categoryPath": "分類路徑",
|
"categoryPath": "分類路徑",
|
||||||
"autoCategorizeByExtension": "按檔案類型自動分類",
|
"autoCategorizeByExtension": "按檔案類型自動分類",
|
||||||
"autoCategorizeByExtensionDescription": "儲存至預設下載目錄時,根據檔案副檔名自動歸入對應分類資料夾",
|
"autoCategorizeByExtensionDescription": "儲存至預設下載目錄時,根據檔案副檔名自動歸入對應分類資料夾。",
|
||||||
"categoryExtensions": "檔案副檔名",
|
"categoryExtensions": "檔案副檔名",
|
||||||
"categoryExtensionsUsageHint": "支援逗號/空白分隔後綴,按回車新增。",
|
"categoryExtensionsUsageHint": "支援逗號/空白分隔後綴,按回車新增。",
|
||||||
"categoryExtensionsEmptyHint": "未設定後綴,檔案不會自動歸入此分類。",
|
"categoryExtensionsEmptyHint": "未設定後綴,檔案不會自動歸入此分類。",
|
||||||
|
|||||||
@@ -99,43 +99,6 @@ void main() {
|
|||||||
expect(saved.saving, isFalse);
|
expect(saved.saving, isFalse);
|
||||||
});
|
});
|
||||||
|
|
||||||
for (final field in ['port', 'DHT', 'PEX']) {
|
|
||||||
test('$field restart notice follows successful persisted changes only', () async {
|
|
||||||
var backend = DownloaderConfig();
|
|
||||||
var failNextSave = false;
|
|
||||||
final registry = CapabilityRegistry(createAppCapabilityCodecs())
|
|
||||||
..bind(GopeedMethods.getConfig, (_) => DownloaderConfig.fromJson(backend.toJson()))
|
|
||||||
..bind(GopeedMethods.putConfig, (config) {
|
|
||||||
if (failNextSave) {
|
|
||||||
failNextSave = false;
|
|
||||||
throw StateError('offline');
|
|
||||||
}
|
|
||||||
backend = DownloaderConfig.fromJson(config.toJson());
|
|
||||||
return const RpcUnit();
|
|
||||||
});
|
|
||||||
final container = _settingsContainer(registry);
|
|
||||||
addTearDown(container.dispose);
|
|
||||||
final initial = await container.read(settingsControllerProvider.future);
|
|
||||||
final controller = container.read(settingsControllerProvider.notifier);
|
|
||||||
final draft = DownloaderConfig.fromJson(initial.config.toJson());
|
|
||||||
switch (field) {
|
|
||||||
case 'port':
|
|
||||||
draft.protocolConfig.bt.listenPort = 6881;
|
|
||||||
case 'DHT':
|
|
||||||
draft.protocolConfig.bt.disableDht = true;
|
|
||||||
case 'PEX':
|
|
||||||
draft.protocolConfig.bt.disablePex = true;
|
|
||||||
}
|
|
||||||
failNextSave = true;
|
|
||||||
await expectLater(controller.save(draft), throwsStateError);
|
|
||||||
expect((await controller.save(draft)).btRestartRequired, isTrue);
|
|
||||||
expect((await controller.save(draft)).btRestartRequired, isFalse);
|
|
||||||
draft.protocolConfig.bt.seedRatio = 2;
|
|
||||||
expect((await controller.save(draft)).btRestartRequired, isFalse);
|
|
||||||
expect((await controller.save(initial.config)).btRestartRequired, isTrue);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('rapid full config saves run in order and keep the latest user edits', () async {
|
test('rapid full config saves run in order and keep the latest user edits', () async {
|
||||||
final backend = DownloaderConfig();
|
final backend = DownloaderConfig();
|
||||||
final entered = Completer<void>();
|
final entered = Completer<void>();
|
||||||
@@ -164,8 +127,7 @@ void main() {
|
|||||||
final savingSecond = controller.save(second);
|
final savingSecond = controller.save(second);
|
||||||
expect(puts.length, 1);
|
expect(puts.length, 1);
|
||||||
release.complete();
|
release.complete();
|
||||||
final results = await Future.wait([savingFirst, savingSecond]);
|
await Future.wait([savingFirst, savingSecond]);
|
||||||
expect(results.map((result) => result.btRestartRequired), [true, false]);
|
|
||||||
expect(puts, hasLength(2));
|
expect(puts, hasLength(2));
|
||||||
expect(puts[0].protocolConfig.bt.listenPort, 6881);
|
expect(puts[0].protocolConfig.bt.listenPort, 6881);
|
||||||
expect(puts[1].protocolConfig.bt.listenPort, 6881);
|
expect(puts[1].protocolConfig.bt.listenPort, 6881);
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter/widgets.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:gopeed/features/tasks/presentation/widgets/create_task_advanced_toggle.dart';
|
|
||||||
import 'package:gopeed/shared/theme/app_component_themes.dart';
|
|
||||||
import 'package:gopeed/shared/theme/app_theme.dart';
|
|
||||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
for (final width in [360.0, 768.0, 1024.0]) {
|
|
||||||
testWidgets('advanced disclosure supports keyboard and touch at width $width', (tester) async {
|
|
||||||
tester.view.physicalSize = Size(width, 768);
|
|
||||||
tester.view.devicePixelRatio = 1;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
var expanded = false;
|
|
||||||
await tester.pumpWidget(
|
|
||||||
shad.ShadcnApp(
|
|
||||||
theme: AppTheme.light(),
|
|
||||||
materialTheme: AppTheme.materialLight(),
|
|
||||||
home: AppComponentThemes(
|
|
||||||
child: StatefulBuilder(
|
|
||||||
builder: (context, setState) => Center(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: CreateTaskAdvancedToggle(
|
|
||||||
expanded: expanded,
|
|
||||||
onPressed: () => setState(() => expanded = !expanded),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(tester.getSize(find.byType(shad.GhostButton)).height, greaterThanOrEqualTo(44));
|
|
||||||
expect(
|
|
||||||
find.byWidgetPredicate((widget) => widget is Semantics && widget.properties.expanded == false),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(expanded, isTrue);
|
|
||||||
expect(
|
|
||||||
find.byWidgetPredicate((widget) => widget is Semantics && widget.properties.expanded == true),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Advanced'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(expanded, isFalse);
|
|
||||||
expect(tester.takeException(), isNull);
|
|
||||||
await tester.pumpWidget(const SizedBox.shrink());
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1636,46 +1636,6 @@ void main() {
|
|||||||
expect(tester.takeException(), isNull);
|
expect(tester.takeException(), isNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('BT settings show a restart message only after an affected auto-save', (tester) async {
|
|
||||||
await _setTestSize(tester, const Size(1024, 900));
|
|
||||||
final controller = FakeSettingsController()..btRestartRequired = true;
|
|
||||||
await tester.pumpWidget(
|
|
||||||
ProviderScope(
|
|
||||||
overrides: [
|
|
||||||
appRuntimeControllerProvider.overrideWith(FakeRuntimeController.new),
|
|
||||||
appPlatformControllerProvider.overrideWith(FakePlatformController.new),
|
|
||||||
settingsControllerProvider.overrideWith(() => controller),
|
|
||||||
],
|
|
||||||
child: const _SettingsTestApp(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Downloads'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
const message = 'This setting takes effect after restarting the app';
|
|
||||||
expect(find.text(message), findsNothing);
|
|
||||||
final port = find.byKey(const ValueKey('bt-listen-port-input'));
|
|
||||||
await tester.ensureVisible(port);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.enterText(port, '6881');
|
|
||||||
await tester.pump(const Duration(milliseconds: 500));
|
|
||||||
expect(find.text(message), findsNothing);
|
|
||||||
await tester.pump(const Duration(milliseconds: 200));
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
expect(find.text(message), findsOneWidget);
|
|
||||||
expect(tester.widget<AppToastContent>(find.byType(AppToastContent)).type, AppToastType.info);
|
|
||||||
await tester.pump(const Duration(seconds: 6));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
controller.btRestartRequired = false;
|
|
||||||
final seedRatio = find.byKey(const ValueKey('bt-seed-ratio-input'));
|
|
||||||
await tester.ensureVisible(seedRatio);
|
|
||||||
await tester.enterText(seedRatio, '2');
|
|
||||||
await tester.pump(const Duration(milliseconds: 700));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.text(message), findsNothing);
|
|
||||||
expect(tester.takeException(), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('settings FTP connections save into the FTP protocol config', (WidgetTester tester) async {
|
testWidgets('settings FTP connections save into the FTP protocol config', (WidgetTester tester) async {
|
||||||
await _setTestSize(tester, const Size(1024, 900));
|
await _setTestSize(tester, const Size(1024, 900));
|
||||||
final settingsController = FakeSettingsController();
|
final settingsController = FakeSettingsController();
|
||||||
@@ -6221,15 +6181,12 @@ ApiServerState _testApiServerState({
|
|||||||
}
|
}
|
||||||
|
|
||||||
class FakeSettingsController extends SettingsController {
|
class FakeSettingsController extends SettingsController {
|
||||||
bool btRestartRequired = false;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<SettingsState> build() async => SettingsState(config: DownloaderConfig());
|
Future<SettingsState> build() async => SettingsState(config: DownloaderConfig());
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<SettingsSaveResult> save(DownloaderConfig config) async {
|
Future<void> save(DownloaderConfig config) async {
|
||||||
state = AsyncValue.data(SettingsState(config: config));
|
state = AsyncValue.data(SettingsState(config: config));
|
||||||
return SettingsSaveResult(btRestartRequired: btRestartRequired);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ project(runner LANGUAGES CXX)
|
|||||||
#
|
#
|
||||||
# Any new source files that you add to the application should be added here.
|
# Any new source files that you add to the application should be added here.
|
||||||
add_executable(${BINARY_NAME} WIN32
|
add_executable(${BINARY_NAME} WIN32
|
||||||
|
"crash_handler.cpp"
|
||||||
"flutter_window.cpp"
|
"flutter_window.cpp"
|
||||||
"main.cpp"
|
"main.cpp"
|
||||||
"utils.cpp"
|
"utils.cpp"
|
||||||
@@ -34,6 +35,7 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
|
|||||||
# dependencies here.
|
# dependencies here.
|
||||||
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
|
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
|
||||||
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
|
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE "dbghelp.lib")
|
||||||
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
|
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
|
||||||
|
|
||||||
# Run the Flutter tool portions of the build. This must not be removed.
|
# Run the Flutter tool portions of the build. This must not be removed.
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Windows native crash diagnostics
|
||||||
|
|
||||||
|
The runner installs diagnostics before starting Flutter and plugins. Files are
|
||||||
|
written beside the executable under `storage/logs`, matching Windows app storage:
|
||||||
|
|
||||||
|
- `native-crash.log`: UTC timestamp, app version, process/thread, exception code,
|
||||||
|
faulting module/address/offset, and minidump success or the Windows error code.
|
||||||
|
- `native-crash.dmp`: the most recent native crash, including thread stacks,
|
||||||
|
loaded modules and unloaded module information.
|
||||||
|
- `crash.log`: Go runtime crash output, kept separately from native diagnostics.
|
||||||
|
|
||||||
|
Logs are appended and existing dumps survive normal restarts. A subsequent native
|
||||||
|
crash replaces the previous dump. Dump generation is best effort, particularly
|
||||||
|
for stack exhaustion, heap corruption or unavailable disk space. Process kills
|
||||||
|
and fail-fast termination can bypass exception handlers.
|
||||||
|
|
||||||
|
The top-level unhandled filter covers native exceptions on process threads. An
|
||||||
|
SEH boundary inside the runner's window callback records the original escaping exception
|
||||||
|
before Windows wraps a window callback failure as `0xC000041D`. A vectored handler
|
||||||
|
also observes that fatal callback status, since it can bypass the unhandled
|
||||||
|
filter. All handlers continue exception processing; they do not attempt recovery
|
||||||
|
or log ordinary handled first-chance exceptions.
|
||||||
|
|
||||||
|
On Windows, verify a release build by exercising tray clicks, Explorer restart,
|
||||||
|
system font changes and child-window open/close. In a disposable test build,
|
||||||
|
raise an unhandled access violation inside a window callback and on a worker
|
||||||
|
thread, then raise `0xC000041D`; check that the log and dump are written and
|
||||||
|
survive relaunch. A debugger may intercept these before application handlers.
|
||||||
|
Open the dump with WinDbg and matching runner/Flutter/plugin PDBs to locate the
|
||||||
|
faulting stack. Minidumps can contain application data; inspect them before
|
||||||
|
sharing.
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
#include "crash_handler.h"
|
||||||
|
|
||||||
|
#include <dbghelp.h>
|
||||||
|
#include <strsafe.h>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstring>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <string>
|
||||||
|
#include <system_error>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
HANDLE crash_log = INVALID_HANDLE_VALUE;
|
||||||
|
std::wstring dump_path;
|
||||||
|
volatile LONG recording = 0;
|
||||||
|
LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = nullptr;
|
||||||
|
|
||||||
|
void WriteLog(const char* text) {
|
||||||
|
if (crash_log == INVALID_HANDLE_VALUE) return;
|
||||||
|
DWORD written = 0;
|
||||||
|
WriteFile(crash_log, text, static_cast<DWORD>(strlen(text)), &written,
|
||||||
|
nullptr);
|
||||||
|
FlushFileBuffers(crash_log);
|
||||||
|
}
|
||||||
|
|
||||||
|
LONG WINAPI UnhandledException(EXCEPTION_POINTERS* exception) {
|
||||||
|
RecordNativeCrash(exception);
|
||||||
|
return previous_filter ? previous_filter(exception)
|
||||||
|
: EXCEPTION_CONTINUE_SEARCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
LONG CALLBACK FatalCallbackException(EXCEPTION_POINTERS* exception) {
|
||||||
|
// Windows can terminate on this callback exception without invoking the
|
||||||
|
// process's unhandled filter. Ignore ordinary first-chance exceptions (Go,
|
||||||
|
// Dart and plugins may handle those) and observe only this fatal status.
|
||||||
|
if (exception->ExceptionRecord->ExceptionCode == 0xC000041D) {
|
||||||
|
RecordNativeCrash(exception);
|
||||||
|
}
|
||||||
|
return EXCEPTION_CONTINUE_SEARCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
LONG RecordNativeCrash(EXCEPTION_POINTERS* exception) {
|
||||||
|
if (!exception || InterlockedCompareExchange(&recording, 1, 0) != 0) {
|
||||||
|
return EXCEPTION_CONTINUE_SEARCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
SYSTEMTIME time;
|
||||||
|
GetSystemTime(&time);
|
||||||
|
const auto* record = exception->ExceptionRecord;
|
||||||
|
HMODULE module = nullptr;
|
||||||
|
wchar_t module_path[MAX_PATH] = L"unknown";
|
||||||
|
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
|
||||||
|
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||||
|
reinterpret_cast<LPCWSTR>(record->ExceptionAddress),
|
||||||
|
&module);
|
||||||
|
if (module) GetModuleFileNameW(module, module_path, MAX_PATH);
|
||||||
|
|
||||||
|
char line[2048] = {};
|
||||||
|
StringCchPrintfA(
|
||||||
|
line, ARRAYSIZE(line),
|
||||||
|
"\r\n%04u-%02u-%02uT%02u:%02u:%02uZ Gopeed %s pid=%lu tid=%lu "
|
||||||
|
"exception=0x%08lX address=%p module=%ls offset=0x%llX\r\n",
|
||||||
|
time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute,
|
||||||
|
time.wSecond, FLUTTER_VERSION, GetCurrentProcessId(), GetCurrentThreadId(),
|
||||||
|
record->ExceptionCode, record->ExceptionAddress, module_path,
|
||||||
|
static_cast<unsigned long long>(
|
||||||
|
reinterpret_cast<uintptr_t>(record->ExceptionAddress) -
|
||||||
|
reinterpret_cast<uintptr_t>(module)));
|
||||||
|
WriteLog(line);
|
||||||
|
|
||||||
|
HANDLE dump = CreateFileW(dump_path.c_str(), GENERIC_WRITE, 0, nullptr,
|
||||||
|
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||||
|
if (dump != INVALID_HANDLE_VALUE) {
|
||||||
|
MINIDUMP_EXCEPTION_INFORMATION info = {};
|
||||||
|
info.ThreadId = GetCurrentThreadId();
|
||||||
|
info.ExceptionPointers = exception;
|
||||||
|
info.ClientPointers = FALSE;
|
||||||
|
const BOOL ok = MiniDumpWriteDump(
|
||||||
|
GetCurrentProcess(), GetCurrentProcessId(), dump,
|
||||||
|
static_cast<MINIDUMP_TYPE>(MiniDumpNormal | MiniDumpWithThreadInfo |
|
||||||
|
MiniDumpWithUnloadedModules),
|
||||||
|
&info, nullptr, nullptr);
|
||||||
|
const DWORD error = ok ? ERROR_SUCCESS : GetLastError();
|
||||||
|
FlushFileBuffers(dump);
|
||||||
|
CloseHandle(dump);
|
||||||
|
StringCchPrintfA(line, ARRAYSIZE(line), "minidump success=%d error=%lu\r\n",
|
||||||
|
ok, error);
|
||||||
|
WriteLog(line);
|
||||||
|
} else {
|
||||||
|
StringCchPrintfA(line, ARRAYSIZE(line), "minidump open error=%lu\r\n",
|
||||||
|
GetLastError());
|
||||||
|
WriteLog(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not swallow an exception or resume a potentially corrupted process.
|
||||||
|
return EXCEPTION_CONTINUE_SEARCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InstallCrashHandler() {
|
||||||
|
// Match Dart's Windows storage path independently of the working directory.
|
||||||
|
wchar_t executable[32768] = {};
|
||||||
|
const DWORD length = GetModuleFileNameW(nullptr, executable, ARRAYSIZE(executable));
|
||||||
|
if (length == 0 || length >= ARRAYSIZE(executable)) return;
|
||||||
|
const auto directory = std::filesystem::path(executable).parent_path() /
|
||||||
|
L"storage" / L"logs";
|
||||||
|
std::error_code error;
|
||||||
|
std::filesystem::create_directories(directory, error);
|
||||||
|
if (error) return;
|
||||||
|
|
||||||
|
dump_path = (directory / L"native-crash.dmp").wstring();
|
||||||
|
crash_log = CreateFileW((directory / L"native-crash.log").c_str(),
|
||||||
|
FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, OPEN_ALWAYS,
|
||||||
|
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||||
|
previous_filter = SetUnhandledExceptionFilter(UnhandledException);
|
||||||
|
AddVectoredExceptionHandler(1, FatalCallbackException);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#ifndef RUNNER_CRASH_HANDLER_H_
|
||||||
|
#define RUNNER_CRASH_HANDLER_H_
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
// Installs best-effort native diagnostics before Flutter or plugins start.
|
||||||
|
void InstallCrashHandler();
|
||||||
|
|
||||||
|
// Records the exception and continues normal Windows exception processing.
|
||||||
|
LONG RecordNativeCrash(EXCEPTION_POINTERS* exception);
|
||||||
|
|
||||||
|
#endif // RUNNER_CRASH_HANDLER_H_
|
||||||
@@ -63,7 +63,9 @@ FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
|
|||||||
|
|
||||||
switch (message) {
|
switch (message) {
|
||||||
case WM_FONTCHANGE:
|
case WM_FONTCHANGE:
|
||||||
|
if (flutter_controller_ && flutter_controller_->engine()) {
|
||||||
flutter_controller_->engine()->ReloadSystemFonts();
|
flutter_controller_->engine()->ReloadSystemFonts();
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
#include <desktop_multi_window/desktop_multi_window_plugin.h>
|
#include <desktop_multi_window/desktop_multi_window_plugin.h>
|
||||||
|
|
||||||
#include "app_links/app_links_plugin_c_api.h"
|
#include "app_links/app_links_plugin_c_api.h"
|
||||||
|
#include "crash_handler.h"
|
||||||
#include "flutter_window.h"
|
#include "flutter_window.h"
|
||||||
#include "flutter/generated_plugin_registrant.h"
|
#include "flutter/generated_plugin_registrant.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
@@ -43,6 +44,7 @@ bool IsMultiWindowLaunch(const std::vector<std::string>& arguments) {
|
|||||||
|
|
||||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||||
_In_ wchar_t *command_line, _In_ int show_command) {
|
_In_ wchar_t *command_line, _In_ int show_command) {
|
||||||
|
InstallCrashHandler();
|
||||||
// Attach to console when present (e.g., 'flutter run') or create a
|
// Attach to console when present (e.g., 'flutter run') or create a
|
||||||
// new console when running with a debugger.
|
// new console when running with a debugger.
|
||||||
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
||||||
@@ -77,11 +79,12 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
|||||||
window.SetQuitOnClose(true);
|
window.SetQuitOnClose(true);
|
||||||
|
|
||||||
::MSG msg;
|
::MSG msg;
|
||||||
while (::GetMessage(&msg, nullptr, 0, 0)) {
|
BOOL message_result;
|
||||||
|
while ((message_result = ::GetMessage(&msg, nullptr, 0, 0)) > 0) {
|
||||||
::TranslateMessage(&msg);
|
::TranslateMessage(&msg);
|
||||||
::DispatchMessage(&msg);
|
::DispatchMessage(&msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
::CoUninitialize();
|
::CoUninitialize();
|
||||||
return EXIT_SUCCESS;
|
return message_result == -1 ? EXIT_FAILURE : static_cast<int>(msg.wParam);
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <dwmapi.h>
|
#include <dwmapi.h>
|
||||||
#include <flutter_windows.h>
|
#include <flutter_windows.h>
|
||||||
|
|
||||||
|
#include "crash_handler.h"
|
||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
@@ -158,6 +159,9 @@ LRESULT CALLBACK Win32Window::WndProc(HWND const window,
|
|||||||
UINT const message,
|
UINT const message,
|
||||||
WPARAM const wparam,
|
WPARAM const wparam,
|
||||||
LPARAM const lparam) noexcept {
|
LPARAM const lparam) noexcept {
|
||||||
|
// Capture inside the callback, before user32 wraps or suppresses an escaping
|
||||||
|
// exception. Keep C++ objects requiring unwinding out of this SEH boundary.
|
||||||
|
__try {
|
||||||
if (message == WM_NCCREATE) {
|
if (message == WM_NCCREATE) {
|
||||||
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
|
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
|
||||||
SetWindowLongPtr(window, GWLP_USERDATA,
|
SetWindowLongPtr(window, GWLP_USERDATA,
|
||||||
@@ -171,6 +175,10 @@ LRESULT CALLBACK Win32Window::WndProc(HWND const window,
|
|||||||
}
|
}
|
||||||
|
|
||||||
return DefWindowProc(window, message, wparam, lparam);
|
return DefWindowProc(window, message, wparam, lparam);
|
||||||
|
} __except (RecordNativeCrash(GetExceptionInformation())) {
|
||||||
|
// The filter always continues the exception search; this is unreachable.
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LRESULT
|
LRESULT
|
||||||
|
|||||||
Reference in new issue
Block a user