Ver Fonte

Unify async file operations and progress UI

Refactors file operations into tracked background tasks with richer task state, per-file subtasks, pause/continue/cancel/remove controls, retention cleanup, and new async/status WebSocket endpoints. Operation execution is centralized and shared across legacy and async flows.

In filesystem operations, adds byte-level progress reporting for copy/move (including folder transfers), keeps legacy percent callbacks compatible, improves move behavior with same-filesystem rename optimization, and fixes destination mkdir/remove handling through filesystem abstractions.

Replaces the old per-operation popup with a unified system-wide file operation dialog, adds reusable launch API (`ao_module_startFileOperation`), updates explorer/desktop/archive/zip integration to use it, and includes related UX updates (hidden files toggle, hidden item styling, permission table rendering, and localization updates). Adds comprehensive Go tests for task bookkeeping, progress helpers, and copy/move progress behavior.
Toby Chui há 3 meses atrás
pai
commit
9e63be2295

Diff do ficheiro suprimidas por serem muito extensas
+ 549 - 264
src/file_system.go


+ 420 - 0
src/file_system_task_test.go

@@ -0,0 +1,420 @@
+package main
+
+import (
+	"strconv"
+	"testing"
+	"time"
+
+	"imuslab.com/arozos/mod/filesystem"
+)
+
+// newTestFileOperationTask registers a task record for testing and returns it
+func newTestFileOperationTask(t *testing.T, id string, sizes []int64) *fileOperationTask {
+	t.Helper()
+	subtasks := []*fileOperationSubtask{}
+	totalSize := int64(0)
+	for _, size := range sizes {
+		totalSize += size
+		subtasks = append(subtasks, &fileOperationSubtask{
+			Filename: "testfile",
+			Src:      "user:/testfile",
+			Size:     size,
+			Status:   FsTask_Pending,
+		})
+	}
+
+	thisTask := &fileOperationTask{
+		ID:                  id,
+		Owner:               "test_user",
+		Operation:           "copy",
+		Src:                 "user:/",
+		Dest:                "user:/Desktop/",
+		FileOperationSignal: filesystem.FsOpr_Continue,
+		Files:               subtasks,
+		TotalSize:           totalSize,
+		Status:              FsTask_Ongoing,
+	}
+
+	wsConnectionStore.Store(id, thisTask)
+	t.Cleanup(func() {
+		wsConnectionStore.Delete(id)
+	})
+	return thisTask
+}
+
+func TestTaskIsFinished(t *testing.T) {
+	tests := []struct {
+		name   string
+		status string
+		want   bool
+	}{
+		{"pending task is not finished", FsTask_Pending, false},
+		{"ongoing task is not finished", FsTask_Ongoing, false},
+		{"completed task is finished", FsTask_Completed, true},
+		{"errored task is finished", FsTask_Error, true},
+		{"cancelled task is finished", FsTask_Cancelled, true},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := taskIsFinished(&fileOperationTask{Status: tt.status})
+			if got != tt.want {
+				t.Errorf("taskIsFinished(%s) = %v, want %v", tt.status, got, tt.want)
+			}
+		})
+	}
+}
+
+func TestSumFileOperationDoneSize(t *testing.T) {
+	tests := []struct {
+		name string
+		done []int64
+		want int64
+	}{
+		{"no file", []int64{}, 0},
+		{"single file", []int64{1024}, 1024},
+		{"multiple files", []int64{100, 250, 650}, 1000},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			thisTask := &fileOperationTask{}
+			for _, done := range tt.done {
+				thisTask.Files = append(thisTask.Files, &fileOperationSubtask{Done: done})
+			}
+			if got := sumFileOperationDoneSize(thisTask); got != tt.want {
+				t.Errorf("sumFileOperationDoneSize() = %d, want %d", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestUpdateOngoingFileOperationSubtask(t *testing.T) {
+	thisTask := newTestFileOperationTask(t, "test_opr_subtask", []int64{1000, 1000})
+
+	sig, progress, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 0, "testfile", 500, 1000)
+	if err != nil {
+		t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
+	}
+	if sig != filesystem.FsOpr_Continue {
+		t.Errorf("signal = %d, want %d", sig, filesystem.FsOpr_Continue)
+	}
+	if thisTask.Files[0].Done != 500 {
+		t.Errorf("subtask done size = %d, want 500", thisTask.Files[0].Done)
+	}
+	if thisTask.DoneSize != 500 {
+		t.Errorf("task done size = %d, want 500", thisTask.DoneSize)
+	}
+	//500 of the 2000 bytes in this operation are done
+	if progress != 25 || thisTask.Progress != 25 {
+		t.Errorf("task progress = %v (returned %v), want 25", thisTask.Progress, progress)
+	}
+
+	//A size the file operation reports overrides the one resolved at task creation
+	if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 1, "testfile", 250, 3000); err != nil {
+		t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
+	}
+	if thisTask.Files[1].Size != 3000 {
+		t.Errorf("subtask size = %d, want 3000", thisTask.Files[1].Size)
+	}
+	if thisTask.TotalSize != 4000 {
+		t.Errorf("task total size = %d, want 4000", thisTask.TotalSize)
+	}
+
+	//Bytes beyond the size of a file are clamped rather than trusted
+	if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 0, "testfile", 999999, 0); err != nil {
+		t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
+	}
+	if thisTask.Files[0].Done != 1000 {
+		t.Errorf("subtask done size = %d, want it clamped to 1000", thisTask.Files[0].Done)
+	}
+
+	//Out of range subtask index should not panic nor change the per file records
+	if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 9, "testfile", 100, 100); err != nil {
+		t.Fatalf("UpdateOngoingFileOperationSubtask() with out of range index returned error: %v", err)
+	}
+
+	//Unknown operation id must return an error
+	if _, _, err := UpdateOngoingFileOperationSubtask("no_such_opr", 0, "testfile", 10, 10); err == nil {
+		t.Error("UpdateOngoingFileOperationSubtask() with unknown oprid should return an error")
+	}
+}
+
+// A small file next to a large one must not count for the same share of the bar
+func TestRecalculateFileOperationProgressIsSizeWeighted(t *testing.T) {
+	//One 1 KB file and one 4 GB file
+	small := int64(1024)
+	large := int64(4 * 1024 * 1024 * 1024)
+	thisTask := newTestFileOperationTask(t, "test_opr_weighted", []int64{small, large})
+
+	//The small file is done, the large one has not started
+	MarkFileOperationSubtaskEnded(thisTask.ID, 0, "")
+
+	if thisTask.Progress > 1 {
+		t.Errorf("progress = %v after the small file finished, want it near 0", thisTask.Progress)
+	}
+
+	//Half of the large file is through
+	if _, _, err := UpdateOngoingFileOperationSubtask(thisTask.ID, 1, "big", large/2, large); err != nil {
+		t.Fatalf("UpdateOngoingFileOperationSubtask() returned error: %v", err)
+	}
+	if thisTask.Progress < 49 || thisTask.Progress > 51 {
+		t.Errorf("progress = %v with half the large file done, want about 50", thisTask.Progress)
+	}
+}
+
+// Operations whose file sizes could not be resolved still report something sane
+func TestRecalculateFileOperationProgressWithoutSizes(t *testing.T) {
+	thisTask := newTestFileOperationTask(t, "test_opr_nosize", []int64{0, 0})
+
+	thisTask.Files[0].Progress = 100
+	thisTask.Files[1].Progress = 0
+	recalculateFileOperationProgress(thisTask)
+
+	if thisTask.Progress != 50 {
+		t.Errorf("progress = %v, want 50 when falling back to equal weighting", thisTask.Progress)
+	}
+}
+
+func TestMarkFileOperationSubtaskEnded(t *testing.T) {
+	thisTask := newTestFileOperationTask(t, "test_opr_subtask_end", []int64{800, 200})
+
+	MarkFileOperationSubtaskEnded(thisTask.ID, 0, "")
+	if thisTask.Files[0].Status != FsTask_Completed {
+		t.Errorf("subtask status = %s, want %s", thisTask.Files[0].Status, FsTask_Completed)
+	}
+	if thisTask.Files[0].Done != 800 || thisTask.DoneSize != 800 {
+		t.Errorf("done size = %d / %d, want 800 / 800", thisTask.Files[0].Done, thisTask.DoneSize)
+	}
+
+	MarkFileOperationSubtaskEnded(thisTask.ID, 1, "Source file not exists")
+	if thisTask.Files[1].Status != FsTask_Error {
+		t.Errorf("subtask status = %s, want %s", thisTask.Files[1].Status, FsTask_Error)
+	}
+	if thisTask.Files[1].Error != "Source file not exists" {
+		t.Errorf("subtask error = %q, want %q", thisTask.Files[1].Error, "Source file not exists")
+	}
+}
+
+func TestSetFileOperationTaskEnded(t *testing.T) {
+	tests := []struct {
+		name         string
+		endingSignal int
+		errmsg       string
+		wantStatus   string
+	}{
+		{"normal completion", filesystem.FsOpr_Continue, "", FsTask_Completed},
+		{"cancelled by user", filesystem.FsOpr_Cancel, "", FsTask_Cancelled},
+		{"ended with error", filesystem.FsOpr_Error, "Access Denied", FsTask_Error},
+	}
+
+	for i, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			thisTask := newTestFileOperationTask(t, "test_opr_end_"+string(rune('a'+i)), []int64{500})
+			SetFileOperationTaskEnded(thisTask.ID, tt.endingSignal, tt.errmsg)
+
+			if thisTask.Status != tt.wantStatus {
+				t.Errorf("task status = %s, want %s", thisTask.Status, tt.wantStatus)
+			}
+			if thisTask.EndTime == 0 {
+				t.Error("task end time should be set after the task ended")
+			}
+			if !taskIsFinished(thisTask) {
+				t.Error("task should be reported as finished")
+			}
+			if thisTask.Files[0].Status == FsTask_Pending {
+				t.Error("subtask should not be left in pending state after the task ended")
+			}
+		})
+	}
+}
+
+// A file operation stopped by the user reports the abort as an error on its way
+// out. That must be recorded as a cancellation, not as a failure.
+func TestSetFileOperationTaskEndedAfterUserCancel(t *testing.T) {
+	thisTask := newTestFileOperationTask(t, "test_opr_usercancel", []int64{500})
+	thisTask.FileOperationSignal = filesystem.FsOpr_Cancel
+	MarkFileOperationSubtaskEnded(thisTask.ID, 0, "Operation cancelled by user")
+
+	SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Error, "Operation cancelled by user")
+
+	if thisTask.Status != FsTask_Cancelled {
+		t.Errorf("task status = %s, want %s", thisTask.Status, FsTask_Cancelled)
+	}
+	if thisTask.Error != "" {
+		t.Errorf("task error = %q, want it cleared", thisTask.Error)
+	}
+	if thisTask.Files[0].Status != FsTask_Cancelled {
+		t.Errorf("subtask status = %s, want %s", thisTask.Files[0].Status, FsTask_Cancelled)
+	}
+	if thisTask.Files[0].Error != "" {
+		t.Errorf("subtask error = %q, want it cleared", thisTask.Files[0].Error)
+	}
+}
+
+func TestGetAllFileOperationForUser(t *testing.T) {
+	ongoing := newTestFileOperationTask(t, "test_opr_list_1", []int64{100})
+	finished := newTestFileOperationTask(t, "test_opr_list_2", []int64{100})
+	SetFileOperationTaskEnded(finished.ID, filesystem.FsOpr_Continue, "")
+
+	onlyOngoing := GetAllFileOperationForUser("test_user", false)
+	if len(onlyOngoing) != 1 || onlyOngoing[0].ID != ongoing.ID {
+		t.Errorf("expecting only the ongoing task to be listed, got %d task(s)", len(onlyOngoing))
+	}
+
+	all := GetAllFileOperationForUser("test_user", true)
+	if len(all) != 2 {
+		t.Errorf("expecting 2 tasks to be listed, got %d", len(all))
+	}
+	if len(all) == 2 && all[0].ID > all[1].ID {
+		t.Error("task listing should be sorted by operation id")
+	}
+
+	if len(GetAllFileOperationForUser("another_user", true)) != 0 {
+		t.Error("tasks of a user should not be visible to another user")
+	}
+}
+
+func TestApplyFileOperationControl(t *testing.T) {
+	thisTask := newTestFileOperationTask(t, "test_opr_control", []int64{100})
+
+	if err := ApplyFileOperationControl("test_user", "pause", thisTask.ID); err != nil {
+		t.Fatalf("pause returned error: %v", err)
+	}
+	if thisTask.FileOperationSignal != filesystem.FsOpr_Pause {
+		t.Errorf("signal = %d, want %d", thisTask.FileOperationSignal, filesystem.FsOpr_Pause)
+	}
+
+	if err := ApplyFileOperationControl("test_user", "continue", thisTask.ID); err != nil {
+		t.Fatalf("continue returned error: %v", err)
+	}
+	if thisTask.FileOperationSignal != filesystem.FsOpr_Continue {
+		t.Errorf("signal = %d, want %d", thisTask.FileOperationSignal, filesystem.FsOpr_Continue)
+	}
+
+	//A running task cannot be removed from the listing
+	if err := ApplyFileOperationControl("test_user", "remove", thisTask.ID); err == nil {
+		t.Error("removing a running task should return an error")
+	}
+
+	//Another user must not be able to control this task
+	if err := ApplyFileOperationControl("another_user", "cancel", thisTask.ID); err == nil {
+		t.Error("controlling a task of another user should return an error")
+	}
+
+	//Unsupported commands are rejected
+	if err := ApplyFileOperationControl("test_user", "explode", thisTask.ID); err == nil {
+		t.Error("unsupported command should return an error")
+	}
+
+	//A finished task can be removed
+	SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Continue, "")
+	if err := ApplyFileOperationControl("test_user", "remove", thisTask.ID); err != nil {
+		t.Fatalf("removing a finished task returned error: %v", err)
+	}
+	if _, err := GetOngoingFileOperationByOprID(thisTask.ID); err == nil {
+		t.Error("the removed task should no longer exist in the store")
+	}
+}
+
+// Only a move can be handed to the storage as a rename. The paths of a move are
+// resolved against the running storage pools, which a unit test has none of, so
+// only the operation types are covered here.
+func TestFileOperationCanBeRenamed(t *testing.T) {
+	tests := []string{"copy", "zip", "unzip", ""}
+	for _, operation := range tests {
+		t.Run("operation "+operation, func(t *testing.T) {
+			if fileOperationCanBeRenamed(operation, []string{"user:/a.txt"}, "user:/Desktop/") {
+				t.Errorf("a %q operation should never be treated as a rename", operation)
+			}
+		})
+	}
+}
+
+func TestClearExpiredFileOperationRecords(t *testing.T) {
+	//An operation that is still running is never touched
+	running := newTestFileOperationTask(t, "test_opr_expire_running", []int64{100})
+
+	//A freshly finished operation is kept until a connected dialog has seen it
+	justDone := newTestFileOperationTask(t, "test_opr_expire_fresh", []int64{100})
+	SetFileOperationTaskEnded(justDone.ID, filesystem.FsOpr_Continue, "")
+
+	//An operation that finished a while ago is cleared on its own
+	oldDone := newTestFileOperationTask(t, "test_opr_expire_done", []int64{100})
+	SetFileOperationTaskEnded(oldDone.ID, filesystem.FsOpr_Continue, "")
+	oldDone.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL - 5
+
+	//So is one the user cancelled
+	oldCancelled := newTestFileOperationTask(t, "test_opr_expire_cancelled", []int64{100})
+	SetFileOperationTaskEnded(oldCancelled.ID, filesystem.FsOpr_Cancel, "")
+	oldCancelled.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL - 5
+
+	//A failure is kept so the user can still look at it later
+	oldError := newTestFileOperationTask(t, "test_opr_expire_error", []int64{100})
+	SetFileOperationTaskEnded(oldError.ID, filesystem.FsOpr_Error, "Access Denied")
+	oldError.EndTime = time.Now().Unix() - fileOprFinishedRecordTTL*100
+
+	clearExpiredFileOperationRecords()
+
+	kept := []struct {
+		name string
+		id   string
+		want bool
+	}{
+		{"running operation", running.ID, true},
+		{"operation that just finished", justDone.ID, true},
+		{"operation finished long ago", oldDone.ID, false},
+		{"operation cancelled long ago", oldCancelled.ID, false},
+		{"failed operation", oldError.ID, true},
+	}
+
+	for _, tt := range kept {
+		t.Run(tt.name, func(t *testing.T) {
+			_, err := GetOngoingFileOperationByOprID(tt.id)
+			if (err == nil) != tt.want {
+				t.Errorf("record still exists = %v, want %v", err == nil, tt.want)
+			}
+		})
+	}
+}
+
+func TestClearExpiredFileOperationRecordsTrimsErrorBacklog(t *testing.T) {
+	//Failures are kept, but not without a bound
+	newest := ""
+	for i := 0; i < fileOprErrorRecordLimit+5; i++ {
+		thisTask := newTestFileOperationTask(t, "test_opr_backlog_"+strconv.Itoa(i), []int64{100})
+		SetFileOperationTaskEnded(thisTask.ID, filesystem.FsOpr_Error, "Access Denied")
+		thisTask.EndTime = time.Now().Unix() - int64(fileOprErrorRecordLimit+5-i)
+		newest = thisTask.ID
+	}
+
+	clearExpiredFileOperationRecords()
+
+	remaining := 0
+	for _, task := range GetAllFileOperationForUser("test_user", true) {
+		if task.Status == FsTask_Error {
+			remaining++
+		}
+	}
+	if remaining != fileOprErrorRecordLimit {
+		t.Errorf("kept %d failed records, want %d", remaining, fileOprErrorRecordLimit)
+	}
+	if _, err := GetOngoingFileOperationByOprID(newest); err != nil {
+		t.Error("the newest failure should be among the records that are kept")
+	}
+}
+
+func TestClearFinishedFileOperationForUser(t *testing.T) {
+	ongoing := newTestFileOperationTask(t, "test_opr_clear_1", []int64{100})
+	finished := newTestFileOperationTask(t, "test_opr_clear_2", []int64{100})
+	SetFileOperationTaskEnded(finished.ID, filesystem.FsOpr_Continue, "")
+
+	ClearFinishedFileOperationForUser("test_user")
+
+	if _, err := GetOngoingFileOperationByOprID(finished.ID); err == nil {
+		t.Error("the finished task should have been cleared")
+	}
+	if _, err := GetOngoingFileOperationByOprID(ongoing.ID); err != nil {
+		t.Error("the ongoing task should not have been cleared")
+	}
+}

+ 142 - 85
src/mod/filesystem/fileOpr.go

@@ -25,6 +25,7 @@ import (
 	"strings"
 	"time"
 
+	"imuslab.com/arozos/mod/filesystem/abstractions/localfs"
 	"imuslab.com/arozos/mod/filesystem/arozfs"
 	"imuslab.com/arozos/mod/filesystem/hidden"
 	"imuslab.com/arozos/mod/info/logger"
@@ -752,7 +753,15 @@ func ViewZipFile(filepath string) ([]string, error) {
 	return filelist, err
 }
 
+// FileCopy copies a file or folder, reporting its progress as a percentage.
+// Prefer FileCopyWithProgress for a progress report counted in bytes.
 func FileCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, dest string, mode string, progressUpdate func(int, string) int) error {
+	return FileCopyWithProgress(srcFsh, src, destFsh, dest, mode, legacyProgressAdapter(progressUpdate))
+}
+
+// FileCopyWithProgress copies a file or folder and reports how many of its bytes
+// are already done, see FileOperationProgressHandler.
+func FileCopyWithProgress(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, dest string, mode string, progressHandler FileOperationProgressHandler) error {
 	srcFshAbs := srcFsh.FileSystemAbstraction
 	destFshAbs := destFsh.FileSystemAbstraction
 	if srcFshAbs.IsDir(src) && strings.HasPrefix(dest, src) {
@@ -807,7 +816,7 @@ func FileCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 	if srcFshAbs.IsDir(src) {
 		//Source file is directory. CopyFolder
 		realDest := filepath.Join(dest, copiedFilename)
-		err := dirCopy(srcFsh, src, destFsh, realDest, progressUpdate)
+		err := dirCopy(srcFsh, src, destFsh, realDest, progressHandler)
 		if err != nil {
 			return err
 		}
@@ -815,34 +824,84 @@ func FileCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 	} else {
 		//Source is file only. Copy file.
 		realDest := filepath.Join(dest, copiedFilename)
-		f, err := srcFshAbs.ReadStream(src)
-		if err != nil {
-			return err
-		}
-		defer f.Close()
-		err = destFshAbs.WriteStream(realDest, f, 0775)
+		err := streamFileWithProgress(srcFsh, src, destFsh, realDest, progressHandler)
 		if err != nil {
 			return err
 		}
+	}
+	return nil
+}
 
-		if progressUpdate != nil {
-			//Set progress to 100, leave it to upper level abstraction to handle
-			statusCode := progressUpdate(100, arozfs.Base(realDest))
-			for statusCode == 1 {
-				//Wait for the task to be resumed
-				time.Sleep(1 * time.Second)
-				statusCode = progressUpdate(100, arozfs.Base(realDest))
-			}
-			if statusCode == 2 {
-				//Cancel
-				return errors.New("Operation cancelled by user")
-			}
+/*
+streamFileWithProgress copies one file from one file system to another, counting
+the bytes as they go past so the caller can follow a large file while it is still
+being written. A cancelled transfer takes its half written destination file with
+it on the way out.
+*/
+func streamFileWithProgress(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, realDest string, progressHandler FileOperationProgressHandler) error {
+	srcFshAbs := srcFsh.FileSystemAbstraction
+	destFshAbs := destFsh.FileSystemAbstraction
+
+	reporter := newProgressReporter(progressHandler, srcFshAbs.GetFileSize(src))
+	reporter.currentFile = arozfs.Base(realDest)
+	if err := reporter.report(0, true); err != nil {
+		return err
+	}
+
+	f, err := srcFshAbs.ReadStream(src)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+
+	err = destFshAbs.WriteStream(realDest, newProgressReader(f, reporter, 0), 0775)
+	if err != nil {
+		if reporter.cancelled {
+			//Do not leave a truncated file behind at the destination
+			destFshAbs.Remove(realDest)
 		}
+		return err
 	}
-	return nil
+
+	//Report the file as done, the reader stops one report short of the end
+	return reporter.report(reporter.totalBytes, true)
 }
 
+/*
+SameFileSystem reports whether two handlers point at the same storage.
+
+A move between two paths of one storage can be handed to that storage as a
+rename, which is instant no matter how large the file is, instead of being
+streamed out and back through ArozOS.
+*/
+func SameFileSystem(srcFsh *FileSystemHandler, destFsh *FileSystemHandler) bool {
+	if srcFsh == nil || destFsh == nil {
+		return false
+	}
+	if srcFsh == destFsh {
+		return true
+	}
+	return srcFsh.UUID != "" && srcFsh.UUID == destFsh.UUID
+}
+
+// isLocalFileSystem reports whether a handler is backed by a disk of this machine
+func isLocalFileSystem(fsh *FileSystemHandler) bool {
+	if fsh == nil {
+		return false
+	}
+	_, isLocal := fsh.FileSystemAbstraction.(localfs.LocalFileSystemAbstraction)
+	return isLocal
+}
+
+// FileMove moves a file or folder, reporting its progress as a percentage.
+// Prefer FileMoveWithProgress for a progress report counted in bytes.
 func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, dest string, mode string, fastMove bool, progressUpdate func(int, string) int) error {
+	return FileMoveWithProgress(srcFsh, src, destFsh, dest, mode, fastMove, legacyProgressAdapter(progressUpdate))
+}
+
+// FileMoveWithProgress moves a file or folder and reports how many of its bytes
+// are already done, see FileOperationProgressHandler.
+func FileMoveWithProgress(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, dest string, mode string, fastMove bool, progressHandler FileOperationProgressHandler) error {
 	srcAbst := srcFsh.FileSystemAbstraction
 	destAbst := destFsh.FileSystemAbstraction
 
@@ -858,7 +917,8 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 			//User pass in the whole path for the folder. Report error usecase.
 			return errors.New("Dest location should be an existing folder instead of the full path of the moved file.")
 		}
-		os.MkdirAll(dest, 0775)
+		//Create it on the destination storage, not on whatever disk ArozOS runs on
+		destAbst.MkdirAll(dest, 0775)
 	}
 
 	//Check if the target file already exists.
@@ -899,16 +959,38 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 		}
 	}
 
-	if fastMove {
-		//Ready to move with the quick rename method
+	/*
+		Both ends of this move sit on the same storage, so ask the storage to do
+		the move itself instead of streaming every byte out to ArozOS and back
+		in again. That is a rename on a local disk, a server side move on SMB and
+		WebDAV, and a server side copy on S3.
+
+		Anything the storage cannot do on its own falls through to the copy and
+		delete path below, which is also what happens for a move that crosses two
+		different storages.
+	*/
+	if fastMove && !srcFsh.ReadOnly && !destFsh.ReadOnly {
 		realDest := filepath.Join(dest, movedFilename)
-		err := os.Rename(src, realDest)
-		if err == nil {
-			//Fast move success
-			return nil
-		}
 
-		//Fast move failed. Back to the original copy and move method
+		if SameFileSystem(srcFsh, destFsh) {
+			//One storage, both ends. Let it move the file on its own.
+			if err := srcAbst.Rename(src, realDest); err == nil {
+				//Moved by the storage itself, nothing was streamed
+				return nil
+			}
+			//The storage could not do it. Back to the copy and delete method.
+			logger.PrintAndLog("Filesystem", "Storage side move unavailable for "+src+", falling back to copy and delete", nil)
+
+		} else if isLocalFileSystem(srcFsh) && isLocalFileSystem(destFsh) {
+			/*
+				Two different storages that both live on disks of this machine.
+				A rename still finishes instantly whenever the two happen to sit
+				on the same volume, and simply fails when they do not.
+			*/
+			if err := os.Rename(src, realDest); err == nil {
+				return nil
+			}
+		}
 	}
 
 	//Ready to move. Check if both folder are located in the same root devices. If not, use copy and delete method.
@@ -917,7 +999,7 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 		realDest := filepath.Join(dest, movedFilename)
 		//err := dircpy.Copy(src, realDest)
 
-		err := dirCopy(srcFsh, src, destFsh, realDest, progressUpdate)
+		err := dirCopy(srcFsh, src, destFsh, realDest, progressHandler)
 		if err != nil {
 			return err
 		} else {
@@ -927,37 +1009,10 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 		}
 
 	} else {
-		//Source is file only. Copy file.
+		//Source is file only. Copy file, then remove the source.
 		realDest := filepath.Join(dest, movedFilename)
-		/*
-			Updates 20-10-2020, replaced io.Copy to BufferedLargeFileCopy
-			Legacy code removed.
-		*/
-
-		//Update the progress
-		if progressUpdate != nil {
-			statusCode := progressUpdate(100, arozfs.Base(src))
-			for statusCode == 1 {
-				//Wait for the task to be resumed
-				time.Sleep(1 * time.Second)
-				statusCode = progressUpdate(100, arozfs.Base(realDest))
-			}
-			if statusCode == 2 {
-				//Cancel
-				return errors.New("Operation cancelled by user")
-			}
-		}
-
-		f, err := srcAbst.ReadStream(src)
-		if err != nil {
-			fmt.Println(err)
-			return err
-		}
-		defer f.Close()
-
-		err = destAbst.WriteStream(realDest, f, 0755)
+		err := streamFileWithProgress(srcFsh, src, destFsh, realDest, progressHandler)
 		if err != nil {
-			fmt.Println(err)
 			return err
 		}
 
@@ -967,9 +1022,12 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 		for err != nil {
 			//Sometime Windows need this to prevent windows caching bring problems to file remove
 			time.Sleep(1 * time.Second)
-			os.Remove(src)
 			counter++
 			logger.PrintAndLog("Filesystem", "Retrying to remove file: "+src, nil)
+			err = srcAbst.Remove(src)
+			if err == nil {
+				break
+			}
 			if counter > 10 {
 				return errors.New("Source file remove failed.")
 			}
@@ -982,20 +1040,19 @@ func FileMove(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 
 // Copy a given directory, with no progress udpate
 func CopyDir(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, dest string) error {
-	return dirCopy(srcFsh, src, destFsh, dest, func(progress int, name string) int { return 0 })
+	return dirCopy(srcFsh, src, destFsh, dest, nil)
 }
 
 // Replacment of the legacy dirCopy plugin with filepath.Walk function. Allowing real time progress update to front end
-func dirCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, realDest string, progressUpdate func(int, string) int) error {
+func dirCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler, realDest string, progressHandler FileOperationProgressHandler) error {
 	srcFshAbs := srcFsh.FileSystemAbstraction
 	destFshAbs := destFsh.FileSystemAbstraction
-	//Get the total file counts
-	totalFileCounts := int64(0)
+	//Get the total size of this folder. Progress is counted in bytes so a folder
+	//holding one large file does not jump straight from nothing to done.
+	totalBytes := int64(0)
 	srcFshAbs.Walk(src, func(path string, info os.FileInfo, err error) error {
 		if !info.IsDir() {
-			//Updates 22 April 2021, chnaged from file count to file size for progress update
-			//totalFileCounts++
-			totalFileCounts += info.Size()
+			totalBytes += info.Size()
 		}
 		return nil
 	})
@@ -1005,8 +1062,10 @@ func dirCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 		destFshAbs.Mkdir(realDest, 0755)
 	}
 
+	reporter := newProgressReporter(progressHandler, totalBytes)
+
 	//Start moving
-	fileCounter := int64(0)
+	copiedBytes := int64(0)
 	src = filepath.ToSlash(src)
 	err := srcFshAbs.Walk(src, func(path string, info os.FileInfo, err error) error {
 		path = filepath.ToSlash(path)
@@ -1019,27 +1078,17 @@ func dirCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 			//Mkdir base on relative path
 			return destFshAbs.MkdirAll(filepath.Join(realDest, folderRootRelative), 0755)
 		} else {
-			//fileCounter++
-			fileCounter += info.Size()
 			//Move file base on relative path
 			fileSrc := filepath.ToSlash(filepath.Join(filepath.Clean(src), folderRootRelative))
 			fileDest := filepath.ToSlash(filepath.Join(filepath.Clean(realDest), folderRootRelative))
 
-			//Update move progress
-			if progressUpdate != nil {
-				statusCode := progressUpdate(int(float64(fileCounter)/float64(totalFileCounts)*100), arozfs.Base(fileSrc))
-				for statusCode == 1 {
-					//Wait for the task to be resumed
-					time.Sleep(1 * time.Second)
-					statusCode = progressUpdate(int(float64(fileCounter)/float64(totalFileCounts)*100), arozfs.Base(fileSrc))
-				}
-				if statusCode == 2 {
-					//Cancel
-					return errors.New("Operation cancelled by user")
-				}
+			//Report where this folder actually is before starting on this file,
+			//the bytes of this one are only counted once they are written
+			reporter.currentFile = arozfs.Base(fileSrc)
+			if err := reporter.report(copiedBytes, true); err != nil {
+				return err
 			}
 
-			//Move the file using BLFC
 			f, err := srcFshAbs.ReadStream(fileSrc)
 			if err != nil {
 				logger.PrintAndLog("Filesystem", fmt.Sprint(err), nil)
@@ -1047,12 +1096,20 @@ func dirCopy(srcFsh *FileSystemHandler, src string, destFsh *FileSystemHandler,
 			}
 			defer f.Close()
 
-			err = destFshAbs.WriteStream(fileDest, f, 0755)
+			err = destFshAbs.WriteStream(fileDest, newProgressReader(f, reporter, copiedBytes), 0755)
 			if err != nil {
-				fmt.Println(err)
+				if reporter.cancelled {
+					//Do not leave a truncated file behind at the destination
+					destFshAbs.Remove(fileDest)
+				}
+				logger.PrintAndLog("Filesystem", fmt.Sprint(err), err)
 				return err
 			}
 
+			copiedBytes += info.Size()
+			if err := reporter.report(copiedBytes, true); err != nil {
+				return err
+			}
 		}
 		return nil
 	})

+ 317 - 0
src/mod/filesystem/fileOprCopy_test.go

@@ -0,0 +1,317 @@
+package filesystem
+
+import (
+	"bytes"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// newTestLocalHandler builds a local file system handler rooted at a temp folder
+func newTestLocalHandler(t *testing.T, name string) (*FileSystemHandler, string) {
+	t.Helper()
+	root := t.TempDir()
+	fsh, err := NewFileSystemHandler(FileSystemOption{
+		Name:      name,
+		Uuid:      name,
+		Path:      root,
+		Access:    "readwrite",
+		Hierarchy: "public",
+	}, RuntimePersistenceConfig{})
+	if err != nil {
+		t.Fatalf("NewFileSystemHandler() returned error: %v", err)
+	}
+	return fsh, filepath.ToSlash(root) + "/"
+}
+
+// writeTestFile drops a file of the given size at the given path
+func writeTestFile(t *testing.T, path string, size int) {
+	t.Helper()
+	os.MkdirAll(filepath.Dir(path), 0755)
+	if err := os.WriteFile(path, bytes.Repeat([]byte("x"), size), 0644); err != nil {
+		t.Fatalf("unable to write the test file: %v", err)
+	}
+}
+
+/*
+A single large file used to report nothing at all until it was finished, which
+left the progress bar frozen for as long as the transfer took. It must now
+report positions while the bytes are still moving.
+*/
+func TestFileCopyWithProgressReportsWhileCopying(t *testing.T) {
+	srcFsh, srcRoot := newTestLocalHandler(t, "srcdrive")
+	destFsh, destRoot := newTestLocalHandler(t, "destdrive")
+
+	fileSize := 8 * 1024 * 1024
+	srcFile := srcRoot + "big.bin"
+	writeTestFile(t, srcFile, fileSize)
+
+	positions := []int64{}
+	var reportedTotal int64
+	err := FileCopyWithProgress(srcFsh, srcFile, destFsh, destRoot, "overwrite",
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			positions = append(positions, bytesDone)
+			reportedTotal = bytesTotal
+			return FsOpr_Continue
+		})
+	if err != nil {
+		t.Fatalf("FileCopyWithProgress() returned error: %v", err)
+	}
+
+	//The copy must have actually happened
+	copied, err := os.ReadFile(destRoot + "big.bin")
+	if err != nil {
+		t.Fatalf("the copied file is missing: %v", err)
+	}
+	if len(copied) != fileSize {
+		t.Errorf("copied file is %d bytes, want %d", len(copied), fileSize)
+	}
+
+	if reportedTotal != int64(fileSize) {
+		t.Errorf("reported total = %d, want %d", reportedTotal, fileSize)
+	}
+	if len(positions) < 2 {
+		t.Fatalf("got %d progress reports, want a start and an end at the very least", len(positions))
+	}
+	if positions[0] != 0 {
+		t.Errorf("first report = %d, want the copy to start from 0", positions[0])
+	}
+	if positions[len(positions)-1] != int64(fileSize) {
+		t.Errorf("last report = %d, want the full %d bytes", positions[len(positions)-1], fileSize)
+	}
+
+	//Positions must never walk backwards
+	for i := 1; i < len(positions); i++ {
+		if positions[i] < positions[i-1] {
+			t.Errorf("report %d went backwards: %d after %d", i, positions[i], positions[i-1])
+		}
+	}
+}
+
+// A cancelled copy stops where it is and does not leave a half written file
+func TestFileCopyWithProgressCancel(t *testing.T) {
+	srcFsh, srcRoot := newTestLocalHandler(t, "srcdrive")
+	destFsh, destRoot := newTestLocalHandler(t, "destdrive")
+
+	srcFile := srcRoot + "big.bin"
+	writeTestFile(t, srcFile, 4*1024*1024)
+
+	err := FileCopyWithProgress(srcFsh, srcFile, destFsh, destRoot, "overwrite",
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			return FsOpr_Cancel
+		})
+	if err == nil {
+		t.Fatal("FileCopyWithProgress() should return an error when the user cancels")
+	}
+
+	if _, statErr := os.Stat(destRoot + "big.bin"); statErr == nil {
+		t.Error("a cancelled copy should not leave its destination file behind")
+	}
+}
+
+/*
+A folder copy weights its files by size, so the position reported while walking
+a folder of mixed sizes must track the bytes rather than the file count.
+*/
+func TestFileCopyWithProgressFolderIsByteWeighted(t *testing.T) {
+	srcFsh, srcRoot := newTestLocalHandler(t, "srcdrive")
+	destFsh, destRoot := newTestLocalHandler(t, "destdrive")
+
+	//One tiny file next to one large file
+	smallSize := 16
+	largeSize := 4 * 1024 * 1024
+	writeTestFile(t, srcRoot+"mixed/small.txt", smallSize)
+	writeTestFile(t, srcRoot+"mixed/large.bin", largeSize)
+
+	positions := []int64{}
+	var reportedTotal int64
+	err := FileCopyWithProgress(srcFsh, srcRoot+"mixed", destFsh, destRoot, "overwrite",
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			positions = append(positions, bytesDone)
+			reportedTotal = bytesTotal
+			return FsOpr_Continue
+		})
+	if err != nil {
+		t.Fatalf("FileCopyWithProgress() returned error: %v", err)
+	}
+
+	if reportedTotal != int64(smallSize+largeSize) {
+		t.Errorf("reported total = %d, want %d", reportedTotal, smallSize+largeSize)
+	}
+
+	//The first report must be the honest starting position, not the position the
+	//first file is about to reach
+	if positions[0] != 0 {
+		t.Errorf("first report = %d, want 0", positions[0])
+	}
+
+	//Finishing the tiny file must not move the bar anywhere near half way
+	for _, position := range positions {
+		ratio := float64(position) / float64(smallSize+largeSize)
+		if position <= int64(smallSize) && ratio > 0.05 {
+			t.Errorf("position %d is %.0f%% of the folder, the small file should barely move the bar", position, ratio*100)
+		}
+	}
+
+	if positions[len(positions)-1] != int64(smallSize+largeSize) {
+		t.Errorf("last report = %d, want the full %d bytes", positions[len(positions)-1], smallSize+largeSize)
+	}
+
+	//Both files must have arrived
+	for _, name := range []string{"mixed/small.txt", "mixed/large.bin"} {
+		if _, statErr := os.Stat(destRoot + name); statErr != nil {
+			t.Errorf("%s is missing at the destination: %v", name, statErr)
+		}
+	}
+}
+
+// The percentage based callback of the original FileCopy must keep working
+func TestFileCopyLegacyProgressStillWorks(t *testing.T) {
+	srcFsh, srcRoot := newTestLocalHandler(t, "srcdrive")
+	destFsh, destRoot := newTestLocalHandler(t, "destdrive")
+
+	srcFile := srcRoot + "file.bin"
+	writeTestFile(t, srcFile, 1024*1024)
+
+	percentages := []int{}
+	err := FileCopy(srcFsh, srcFile, destFsh, destRoot, "overwrite", func(progress int, filename string) int {
+		percentages = append(percentages, progress)
+		return FsOpr_Continue
+	})
+	if err != nil {
+		t.Fatalf("FileCopy() returned error: %v", err)
+	}
+
+	if len(percentages) == 0 {
+		t.Fatal("the legacy callback was never called")
+	}
+	if percentages[len(percentages)-1] != 100 {
+		t.Errorf("last percentage = %d, want 100", percentages[len(percentages)-1])
+	}
+	if _, statErr := os.Stat(destRoot + "file.bin"); statErr != nil {
+		t.Errorf("the copied file is missing: %v", statErr)
+	}
+}
+
+// A move that has to stream the bytes reports its progress like a copy does
+func TestFileMoveWithProgress(t *testing.T) {
+	srcFsh, srcRoot := newTestLocalHandler(t, "srcdrive")
+	destFsh, destRoot := newTestLocalHandler(t, "destdrive")
+
+	srcFile := srcRoot + "moved.bin"
+	fileSize := 2 * 1024 * 1024
+	writeTestFile(t, srcFile, fileSize)
+
+	var lastPosition int64
+	//fastMove is off so the move goes through the copy and delete path
+	err := FileMoveWithProgress(srcFsh, srcFile, destFsh, destRoot, "overwrite", false,
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			lastPosition = bytesDone
+			return FsOpr_Continue
+		})
+	if err != nil {
+		t.Fatalf("FileMoveWithProgress() returned error: %v", err)
+	}
+
+	if lastPosition != int64(fileSize) {
+		t.Errorf("last report = %d, want %d", lastPosition, fileSize)
+	}
+	if _, statErr := os.Stat(destRoot + "moved.bin"); statErr != nil {
+		t.Errorf("the moved file is missing at the destination: %v", statErr)
+	}
+	if _, statErr := os.Stat(srcFile); statErr == nil {
+		t.Error("the source file should be gone after a move")
+	}
+}
+
+/*
+Moving between two folders of one storage is handed to that storage as a rename,
+so nothing is streamed no matter how large the file is. This is what saves a
+same-share SMB move from being downloaded and uploaded again.
+*/
+func TestFileMoveSameFileSystemUsesRename(t *testing.T) {
+	fsh, root := newTestLocalHandler(t, "onedrive")
+
+	srcFile := root + "from/renamed.bin"
+	writeTestFile(t, srcFile, 1024*1024)
+	os.MkdirAll(root+"to", 0755)
+
+	reports := 0
+	err := FileMoveWithProgress(fsh, srcFile, fsh, root+"to/", "overwrite", true,
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			reports++
+			return FsOpr_Continue
+		})
+	if err != nil {
+		t.Fatalf("FileMoveWithProgress() returned error: %v", err)
+	}
+
+	if _, statErr := os.Stat(root + "to/renamed.bin"); statErr != nil {
+		t.Errorf("the moved file is missing at the destination: %v", statErr)
+	}
+	if _, statErr := os.Stat(srcFile); statErr == nil {
+		t.Error("the source file should be gone after a move")
+	}
+	if reports != 0 {
+		t.Errorf("a storage side move reported %d times, want it to stream nothing", reports)
+	}
+}
+
+// A whole folder moves in one step too, however many files are inside it
+func TestFileMoveSameFileSystemRenamesFolder(t *testing.T) {
+	fsh, root := newTestLocalHandler(t, "onedrive")
+
+	writeTestFile(t, root+"from/tree/a.bin", 1024)
+	writeTestFile(t, root+"from/tree/nested/b.bin", 2048)
+	os.MkdirAll(root+"to", 0755)
+
+	reports := 0
+	err := FileMoveWithProgress(fsh, root+"from/tree", fsh, root+"to/", "overwrite", true,
+		func(currentFile string, bytesDone int64, bytesTotal int64) int {
+			reports++
+			return FsOpr_Continue
+		})
+	if err != nil {
+		t.Fatalf("FileMoveWithProgress() returned error: %v", err)
+	}
+
+	for _, name := range []string{"to/tree/a.bin", "to/tree/nested/b.bin"} {
+		if _, statErr := os.Stat(root + name); statErr != nil {
+			t.Errorf("%s is missing after the move: %v", name, statErr)
+		}
+	}
+	if _, statErr := os.Stat(root + "from/tree"); statErr == nil {
+		t.Error("the source folder should be gone after a move")
+	}
+	if reports != 0 {
+		t.Errorf("a storage side folder move reported %d times, want it to stream nothing", reports)
+	}
+}
+
+// SameFileSystem decides whether the storage can be asked to do the move itself
+func TestSameFileSystem(t *testing.T) {
+	first, _ := newTestLocalHandler(t, "drive_a")
+	second, _ := newTestLocalHandler(t, "drive_b")
+	sameUUID, _ := newTestLocalHandler(t, "drive_a")
+
+	tests := []struct {
+		name string
+		src  *FileSystemHandler
+		dest *FileSystemHandler
+		want bool
+	}{
+		{"the very same handler", first, first, true},
+		{"two handlers of one storage", first, sameUUID, true},
+		{"two different storages", first, second, false},
+		{"nil source", nil, first, false},
+		{"nil destination", first, nil, false},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := SameFileSystem(tt.src, tt.dest); got != tt.want {
+				t.Errorf("SameFileSystem() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 150 - 0
src/mod/filesystem/fileOprProgress.go

@@ -0,0 +1,150 @@
+package filesystem
+
+/*
+	File Operation Progress Reporting
+	author: tobychui
+
+	Byte level progress reporting for the file operation wrappers in fileOpr.go.
+
+	A file operation used to report its progress once per file, which made the
+	bar useless for the two cases that matter most: a list of files with wildly
+	different sizes, and a single large file that would sit unchanged for
+	minutes before jumping straight to done. The helpers here count the bytes as
+	they stream through, so the progress of an operation always reflects how much
+	of it is actually finished.
+*/
+
+import (
+	"errors"
+	"io"
+	"time"
+)
+
+const (
+	//How often a running file operation reports its position upwards. A byte
+	//counting reader sees every buffer that goes past, which on a local disk is
+	//thousands of reads a second, so the reports are rate limited from here.
+	fileOprProgressInterval = 200 * time.Millisecond
+
+	//How long a paused file operation waits before asking for the signal again
+	fileOprPauseCheckInterval = 500 * time.Millisecond
+)
+
+/*
+FileOperationProgressHandler is called while a file operation is running.
+
+currentFile is the file being processed at this moment, bytesDone and bytesTotal
+describe the progress of the whole operation in bytes, where bytesTotal is 0 when
+the size could not be resolved beforehand. The handler returns one of the
+FsOpr_* control signals.
+*/
+type FileOperationProgressHandler func(currentFile string, bytesDone int64, bytesTotal int64) int
+
+// progressReporter rate limits the progress callbacks of a file operation and
+// applies the pause and cancel signals the handler returns.
+type progressReporter struct {
+	handler     FileOperationProgressHandler
+	totalBytes  int64  //Total size of this file operation in bytes
+	currentFile string //File being processed right now
+	cancelled   bool   //Whether the user asked to stop this operation
+	lastReport  time.Time
+}
+
+func newProgressReporter(handler FileOperationProgressHandler, totalBytes int64) *progressReporter {
+	return &progressReporter{
+		handler:    handler,
+		totalBytes: totalBytes,
+	}
+}
+
+/*
+report pushes the current position upwards, waits out a pause and returns an
+error once the user cancels the operation.
+
+Set force for the positions that must not be dropped, like the start and the end
+of a file. Everything else is subject to the fileOprProgressInterval rate limit.
+*/
+func (p *progressReporter) report(bytesDone int64, force bool) error {
+	if p == nil || p.handler == nil {
+		return nil
+	}
+	if p.cancelled {
+		return errors.New("Operation cancelled by user")
+	}
+	if !force && time.Since(p.lastReport) < fileOprProgressInterval {
+		return nil
+	}
+
+	signal := p.handler(p.currentFile, bytesDone, p.totalBytes)
+	for signal == FsOpr_Pause {
+		//Hold the transfer here until the operation is resumed or cancelled
+		time.Sleep(fileOprPauseCheckInterval)
+		signal = p.handler(p.currentFile, bytesDone, p.totalBytes)
+	}
+
+	//A pause may have held this call for a long time, restart the rate limit
+	//window from the moment the handler actually returned
+	p.lastReport = time.Now()
+
+	if signal == FsOpr_Cancel {
+		p.cancelled = true
+		return errors.New("Operation cancelled by user")
+	}
+	return nil
+}
+
+// progressReader counts the bytes that stream through it and reports them
+// upwards. A cancelled operation surfaces as a read error, which aborts the
+// copy where it stands.
+type progressReader struct {
+	reader   io.Reader
+	reporter *progressReporter
+	baseDone int64 //Bytes of this operation already done before this stream
+	streamed int64 //Bytes that went through this reader so far
+}
+
+// newProgressReader wraps a reader so the bytes going through it are reported.
+// baseDone is how much of the operation was already done when the stream began.
+// The reader is handed back untouched when there is nothing to report to.
+func newProgressReader(reader io.Reader, reporter *progressReporter, baseDone int64) io.Reader {
+	if reporter == nil || reporter.handler == nil {
+		return reader
+	}
+	return &progressReader{
+		reader:   reader,
+		reporter: reporter,
+		baseDone: baseDone,
+	}
+}
+
+func (p *progressReader) Read(buf []byte) (int, error) {
+	n, err := p.reader.Read(buf)
+	if n > 0 {
+		p.streamed += int64(n)
+		if reportErr := p.reporter.report(p.baseDone+p.streamed, false); reportErr != nil {
+			//Stop the transfer, the bytes read so far are still handed over so
+			//the writer can finish the buffer it is holding
+			return n, reportErr
+		}
+	}
+	return n, err
+}
+
+// legacyProgressAdapter turns a byte level progress handler back into the
+// percentage based callback that the original FileCopy and FileMove take.
+func legacyProgressAdapter(progressUpdate func(int, string) int) FileOperationProgressHandler {
+	if progressUpdate == nil {
+		return nil
+	}
+
+	return func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		progress := 0
+		if bytesTotal > 0 {
+			progress = int(float64(bytesDone) / float64(bytesTotal) * 100)
+		}
+		if progress > 100 {
+			progress = 100
+		}
+		return progressUpdate(progress, currentFile)
+	}
+}

+ 180 - 0
src/mod/filesystem/fileOprProgress_test.go

@@ -0,0 +1,180 @@
+package filesystem
+
+import (
+	"bytes"
+	"io"
+	"strings"
+	"testing"
+	"time"
+)
+
+func TestProgressReporterRateLimit(t *testing.T) {
+	calls := 0
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		calls++
+		return FsOpr_Continue
+	}, 1000)
+
+	//An unforced burst must collapse into a single report
+	for i := 0; i < 500; i++ {
+		if err := reporter.report(int64(i), false); err != nil {
+			t.Fatalf("report() returned error: %v", err)
+		}
+	}
+	if calls != 1 {
+		t.Errorf("handler called %d times for a burst of unforced reports, want 1", calls)
+	}
+
+	//A forced report always goes through
+	if err := reporter.report(1000, true); err != nil {
+		t.Fatalf("report() returned error: %v", err)
+	}
+	if calls != 2 {
+		t.Errorf("handler called %d times after a forced report, want 2", calls)
+	}
+}
+
+func TestProgressReporterCancel(t *testing.T) {
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		return FsOpr_Cancel
+	}, 1000)
+
+	err := reporter.report(0, true)
+	if err == nil {
+		t.Fatal("report() should return an error once the operation is cancelled")
+	}
+	if !reporter.cancelled {
+		t.Error("the reporter should remember that the operation was cancelled")
+	}
+
+	//Every later report keeps failing without asking the handler again
+	if err := reporter.report(10, true); err == nil {
+		t.Error("report() should keep failing after a cancellation")
+	}
+}
+
+func TestProgressReporterPause(t *testing.T) {
+	signals := []int{FsOpr_Pause, FsOpr_Pause, FsOpr_Continue}
+	call := 0
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		thisSignal := signals[call]
+		if call < len(signals)-1 {
+			call++
+		}
+		return thisSignal
+	}, 1000)
+
+	start := time.Now()
+	if err := reporter.report(0, true); err != nil {
+		t.Fatalf("report() returned error: %v", err)
+	}
+
+	//The reporter must hold the transfer until the operation is resumed
+	if time.Since(start) < fileOprPauseCheckInterval {
+		t.Error("report() should wait while the operation is paused")
+	}
+	if call != len(signals)-1 {
+		t.Errorf("handler asked %d times, want it polled until the pause lifted", call+1)
+	}
+}
+
+func TestProgressReaderCountsBytes(t *testing.T) {
+	payload := strings.Repeat("a", 4096)
+	var lastReported int64
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		lastReported = bytesDone
+		return FsOpr_Continue
+	}, int64(len(payload)))
+
+	reader := newProgressReader(strings.NewReader(payload), reporter, 0)
+	copied, err := io.Copy(io.Discard, reader)
+	if err != nil {
+		t.Fatalf("io.Copy() returned error: %v", err)
+	}
+	if copied != int64(len(payload)) {
+		t.Errorf("copied %d bytes, want %d", copied, len(payload))
+	}
+	if lastReported == 0 {
+		t.Error("the reader should have reported at least one position")
+	}
+	if lastReported > int64(len(payload)) {
+		t.Errorf("reported %d bytes, more than the %d that exist", lastReported, len(payload))
+	}
+}
+
+func TestProgressReaderCountsFromBase(t *testing.T) {
+	payload := strings.Repeat("b", 2048)
+	base := int64(10000)
+	var lastReported int64
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		lastReported = bytesDone
+		return FsOpr_Continue
+	}, base+int64(len(payload)))
+
+	reader := newProgressReader(strings.NewReader(payload), reporter, base)
+	io.Copy(io.Discard, reader)
+
+	if lastReported <= base {
+		t.Errorf("reported %d, want a position past the %d bytes already done", lastReported, base)
+	}
+}
+
+func TestProgressReaderStopsOnCancel(t *testing.T) {
+	payload := bytes.Repeat([]byte("c"), 1024*1024)
+	reporter := newProgressReporter(func(currentFile string, bytesDone int64, bytesTotal int64) int {
+		return FsOpr_Cancel
+	}, int64(len(payload)))
+
+	reader := newProgressReader(bytes.NewReader(payload), reporter, 0)
+	copied, err := io.Copy(io.Discard, reader)
+	if err == nil {
+		t.Fatal("io.Copy() should stop with an error once the operation is cancelled")
+	}
+	if copied == int64(len(payload)) {
+		t.Error("the whole payload was copied, the cancellation did not stop the transfer")
+	}
+}
+
+func TestNewProgressReaderWithoutHandler(t *testing.T) {
+	//Nothing to report to: the reader must be handed back untouched
+	source := strings.NewReader("hello")
+	if got := newProgressReader(source, nil, 0); got != io.Reader(source) {
+		t.Error("newProgressReader() should return the original reader when there is no reporter")
+	}
+	if got := newProgressReader(source, newProgressReporter(nil, 0), 0); got != io.Reader(source) {
+		t.Error("newProgressReader() should return the original reader when there is no handler")
+	}
+}
+
+func TestLegacyProgressAdapter(t *testing.T) {
+	tests := []struct {
+		name       string
+		bytesDone  int64
+		bytesTotal int64
+		want       int
+	}{
+		{"nothing done", 0, 1000, 0},
+		{"half way", 500, 1000, 50},
+		{"all done", 1000, 1000, 100},
+		{"unknown total", 500, 0, 0},
+		{"more than the total", 1500, 1000, 100},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := -1
+			adapter := legacyProgressAdapter(func(progress int, filename string) int {
+				got = progress
+				return FsOpr_Continue
+			})
+			adapter("testfile", tt.bytesDone, tt.bytesTotal)
+			if got != tt.want {
+				t.Errorf("percentage = %d, want %d", got, tt.want)
+			}
+		})
+	}
+
+	if legacyProgressAdapter(nil) != nil {
+		t.Error("legacyProgressAdapter(nil) should stay nil so the reader is not wrapped")
+	}
+}

+ 2 - 1
src/storage.go

@@ -296,7 +296,8 @@ func GetFSHandlerSubpathFromVpath(vpath string) (*fs.FileSystemHandler, string,
 	}
 
 	if fsh == nil || fsh.FileSystemAbstraction == nil {
-		return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
+		//err is nil on this branch, do not dereference it for a message
+		return nil, "", errors.New("Unable to resolve requested path: file system handler not loaded")
 	}
 
 	if fsh.Closed {

+ 53 - 2
src/web/SystemAO/file_system/file_explorer.css

@@ -492,8 +492,8 @@ body.darkTheme .ui.icon.button{
 
 .addressText{
     padding:5px;
-    border-radius: 0.4em;
-    border: 1px solid var(--address_text_border);
+    border-radius: 0.5em;
+    /* border: 1px solid var(--address_text_border); */
     flex-grow: 1;
     background-color: var(--address_text_background);
 }
@@ -736,6 +736,20 @@ body.fmResizing *{
     border: 1px solid var(--divider);
 }
 
+/*
+    Hidden entries, shown only when the user turns them on. Dimmed so they stay
+    distinguishable from ordinary content at a glance; they lift to full
+    strength on hover and while selected so they are still readable to work
+    with.
+*/
+.fileObject[data-hidden="true"]{
+    opacity: 0.45;
+}
+.fileObject[data-hidden="true"]:hover,
+.fileObject[data-hidden="true"].selected{
+    opacity: 1;
+}
+
 .fileviewList .fileObject.item:hover,.fileviewList .fileObject.card:hover{
     background-color: var(--fileobject_background_hover) !important;
 }
@@ -934,6 +948,42 @@ body.fmResizing *{
     background-color: var(--folder_view_background);
 }
 
+/*
+    Permission grid in the properties panel. Compact enough to sit inside the
+    properties table cell without stretching the panel.
+*/
+#propertiesView .fmPermTable{
+    border-collapse: collapse;
+    width: auto;
+    font-size: 12px;
+    line-height: 1.3;
+}
+#propertiesView .fmPermTable th{
+    padding: 1px 7px 3px 7px;
+    font-weight: 400;
+    color: var(--fs-text-dim) !important;
+    text-align: center;
+    white-space: nowrap;
+}
+#propertiesView .fmPermTable td{
+    padding: 1px 7px;
+    text-align: center;
+}
+#propertiesView .fmPermTable td.fmPermWho{
+    padding-left: 0px;
+    padding-right: 10px;
+    text-align: left;
+    color: var(--fs-text-dim) !important;
+    white-space: nowrap;
+}
+/* Granted reads as present, denied as a quiet dash rather than a red cross */
+#propertiesView .fmPermTable td.fmPermOn{
+    color: var(--upload_progress_succ) !important;
+}
+#propertiesView .fmPermTable td.fmPermOff{
+    color: var(--fs-text-faint) !important;
+}
+
 #propertiesView td, #propertiesView span, #propertiesView div{
     color: var(--text_color);
 }
@@ -1991,6 +2041,7 @@ i.blue{
     min-width: 0;
     cursor: text;
     padding-left: 4px;
+    padding-right: 0px;
 }
 
 .fmPathHome {

+ 1 - 0
src/web/SystemAO/file_system/file_explorer.html

@@ -141,6 +141,7 @@
                     <div class="fsMenuSep"></div>
                     <div class="fsMenuItem" onclick="runFileOpr(toggleDarkTheme);"><span class="fsMenuIcon" data-fsicon="moon"></span><span locale="fileopr/Dark Theme">Dark Theme</span></div>
                     <div class="fsMenuSep fmDupSep"></div>
+                    <div class="fsMenuItem" id="fmHiddenToggle" onclick="toggleHiddenFiles();"><span locale="fileopr/Hidden Files">Show Hidden Files</span><span class="fsMenuCheck" data-fsicon="check"></span></div>
                     <div class="fsMenuItem" id="fmToolbarToggle" onclick="toggleFileOprBar();"><span locale="fileopr/Toolbar">Operation Toolbar</span><span class="fsMenuCheck" data-fsicon="check"></span></div>
                 </div>
             </div>

+ 495 - 0
src/web/SystemAO/file_system/file_operation.css

@@ -0,0 +1,495 @@
+/*
+    file_operation.css
+
+    Styling for the unified ArozOS file operation dialog. One dialog shows
+    every ongoing file operation of the current user, see file_operation.html
+    and js/file_operation/dialog.js.
+*/
+
+:root {
+    --fo-bg: #ffffff;
+    --fo-header-bg: #ffffff;
+    --fo-footer-bg: #f7f9fb;
+    --fo-border: #e4e9ef;
+    --fo-fg: #1f2429;
+    --fo-muted: #78838f;
+    --fo-accent: #2f7fd1;
+    --fo-accent-fg: #ffffff;
+    --fo-track: #e6ebf1;
+    --fo-bar: #2f80ed;
+    --fo-bar-done: #21ba45;
+    --fo-bar-error: #db2828;
+    --fo-bar-paused: #b0b8c1;
+    --fo-hover: rgba(0, 0, 0, 0.045);
+    --fo-btn-border: #d6dce4;
+    --fo-warn: #a5720b;
+    --fo-warn-bg: rgba(240, 173, 27, 0.12);
+}
+
+[data-theme="dark"] {
+    --fo-bg: #1b2027;
+    --fo-header-bg: #161b21;
+    --fo-footer-bg: #161b21;
+    --fo-border: #2a313a;
+    --fo-fg: #e7edf3;
+    --fo-muted: #8b97a5;
+    --fo-accent: #4a92e0;
+    --fo-accent-fg: #ffffff;
+    --fo-track: #2c333c;
+    --fo-bar: #4a92e0;
+    --fo-bar-done: #2fbe52;
+    --fo-bar-error: #e05252;
+    --fo-bar-paused: #57616d;
+    --fo-hover: rgba(255, 255, 255, 0.06);
+    --fo-btn-border: #39424e;
+    --fo-warn: #e0b445;
+    --fo-warn-bg: rgba(224, 180, 69, 0.12);
+}
+
+html, body {
+    height: 100%;
+}
+
+body {
+    margin: 0;
+    padding: 0;
+    /* Semantic UI floors the body at 320px, which would push this dialog wider
+       than the window it sits in on a narrow screen */
+    min-width: 0;
+    overflow: hidden;
+    background: var(--fo-bg);
+    color: var(--fo-fg);
+    font-size: 14px;
+    -webkit-font-smoothing: antialiased;
+}
+
+.fodialog {
+    display: flex;
+    flex-direction: column;
+    height: 100%;
+    width: 100%;
+    background: var(--fo-bg);
+}
+
+/* Header */
+.foheader {
+    flex: 0 0 auto;
+    display: flex;
+    align-items: center;
+    padding: 14px 12px 10px 18px;
+    background: var(--fo-header-bg);
+}
+
+.fotitle {
+    flex: 1 1 auto;
+    font-size: 15px;
+    font-weight: 500;
+    color: var(--fo-fg);
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+
+.foheaderbtns {
+    flex: 0 0 auto;
+    display: flex;
+    align-items: center;
+    gap: 2px;
+}
+
+.foiconbtn {
+    width: 30px;
+    height: 30px;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    border-radius: 50%;
+    cursor: pointer;
+    color: var(--fo-muted);
+    transition: background-color 0.15s ease;
+}
+
+.foiconbtn:hover {
+    background: var(--fo-hover);
+}
+
+.foiconbtn i.icon {
+    margin: 0;
+    font-size: 14px;
+    line-height: 1;
+    height: auto;
+    width: auto;
+}
+
+/* Collapsed summary: the combined progress of every operation in one line */
+.fosummary {
+    display: none;
+    align-items: center;
+    gap: 12px;
+    padding: 4px 18px 14px 18px;
+    background: var(--fo-header-bg);
+}
+
+.fodialog.collapsed .fosummary {
+    display: flex;
+}
+
+.fosummary .foprogress {
+    flex: 1 1 auto;
+    margin-top: 0;
+    height: 6px;
+    border-radius: 3px;
+}
+
+.fosummary .foprogress .bar {
+    border-radius: 3px;
+}
+
+.fosummarypercent {
+    flex: 0 0 auto;
+    min-width: 42px;
+    text-align: right;
+    font-size: 12.5px;
+    font-variant-numeric: tabular-nums;
+    color: var(--fo-muted);
+}
+
+/* Body */
+.fobody {
+    flex: 1 1 auto;
+    overflow-y: auto;
+    overflow-x: hidden;
+    padding: 0 6px 6px 6px;
+}
+
+.fodialog.collapsed .fobody {
+    display: none;
+}
+
+.fobody::-webkit-scrollbar {
+    width: 8px;
+}
+
+.fobody::-webkit-scrollbar-thumb {
+    background: var(--fo-track);
+    border-radius: 4px;
+}
+
+/* One operation group */
+.fooperation {
+    padding: 0 12px 6px 12px;
+}
+
+.foopinfo {
+    font-size: 12.5px;
+    color: var(--fo-accent);
+    line-height: 1.55;
+    padding: 0 0 8px 0;
+    word-break: break-word;
+}
+
+.foopnote {
+    display: block;
+    color: var(--fo-accent);
+    opacity: 0.85;
+}
+
+/* Inline overwrite decision prompt */
+.fodupask {
+    background: var(--fo-warn-bg);
+    border-radius: 8px;
+    padding: 8px 10px;
+    margin-bottom: 10px;
+}
+
+.fodupask .foduptext {
+    display: block;
+    font-size: 12.5px;
+    color: var(--fo-warn);
+    margin-bottom: 7px;
+}
+
+.fodupbtns {
+    display: flex;
+    gap: 6px;
+    flex-wrap: wrap;
+}
+
+/* One file row inside an operation */
+.forow {
+    display: flex;
+    align-items: flex-start;
+    padding: 7px 0 9px 0;
+}
+
+.forowicon {
+    flex: 0 0 auto;
+    width: 30px;
+    height: 30px;
+    margin-right: 11px;
+    margin-top: 2px;
+}
+
+.forowicon svg {
+    display: block;
+    width: 30px;
+    height: 30px;
+}
+
+.forowmain {
+    flex: 1 1 auto;
+    min-width: 0;
+}
+
+.forowname {
+    font-size: 13px;
+    color: var(--fo-fg);
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    line-height: 1.45;
+}
+
+.forowmeta {
+    font-size: 11.5px;
+    color: var(--fo-muted);
+    margin-top: 2px;
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+
+.forowmeta.error {
+    color: var(--fo-bar-error);
+}
+
+.foprogress {
+    margin-top: 7px;
+    height: 4px;
+    width: 100%;
+    background: var(--fo-track);
+    border-radius: 2px;
+    overflow: hidden;
+}
+
+.foprogress .bar {
+    height: 100%;
+    width: 0%;
+    background: var(--fo-bar);
+    border-radius: 2px;
+    transition: width 0.25s linear;
+}
+
+.foprogress .bar.done {
+    background: var(--fo-bar-done);
+}
+
+.foprogress .bar.error {
+    background: var(--fo-bar-error);
+}
+
+.foprogress .bar.paused {
+    background: var(--fo-bar-paused);
+}
+
+.forowctrl {
+    flex: 0 0 auto;
+    width: 66px;
+    margin-left: 10px;
+    display: flex;
+    gap: 6px;
+    justify-content: flex-end;
+    align-items: flex-start;
+}
+
+.forowbtn {
+    width: 28px;
+    height: 28px;
+    border-radius: 50%;
+    border: 1px solid var(--fo-btn-border);
+    background: transparent;
+    color: var(--fo-muted);
+    cursor: pointer;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    padding: 0;
+    transition: background-color 0.15s ease, border-color 0.15s ease;
+}
+
+.forowbtn:hover {
+    background: var(--fo-hover);
+    border-color: var(--fo-accent);
+    color: var(--fo-accent);
+}
+
+.forowbtn.cancel:hover {
+    border-color: var(--fo-bar-error);
+    color: var(--fo-bar-error);
+}
+
+.forowbtn:disabled {
+    opacity: 0.5;
+    cursor: default;
+}
+
+.forowbtn i.icon {
+    margin: 0;
+    font-size: 11px;
+    line-height: 1;
+    height: auto;
+    width: auto;
+}
+
+/* Empty state */
+.foempty {
+    text-align: center;
+    color: var(--fo-muted);
+    font-size: 13px;
+    padding: 34px 12px;
+}
+
+.foempty i.icon {
+    display: block;
+    margin: 0 auto 8px auto;
+    font-size: 26px;
+    height: auto;
+    width: auto;
+    color: var(--fo-bar-done);
+}
+
+/* Footer */
+.fofooter {
+    flex: 0 0 auto;
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    padding: 9px 12px;
+    background: var(--fo-footer-bg);
+    border-top: 1px solid var(--fo-border);
+}
+
+.fototal {
+    flex: 1 1 auto;
+    min-width: 0;
+    font-size: 12px;
+    color: var(--fo-muted);
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+
+.fototal i.icon {
+    margin-right: 6px;
+    height: auto;
+    width: auto;
+    opacity: 0.8;
+}
+
+.fofooterbtns {
+    flex: 0 0 auto;
+    display: flex;
+    align-items: center;
+    gap: 6px;
+}
+
+.fobtn {
+    font-family: inherit;
+    font-size: 12px;
+    line-height: 1;
+    padding: 8px 11px;
+    border-radius: 6px;
+    border: 1px solid transparent;
+    background: transparent;
+    color: var(--fo-muted);
+    cursor: pointer;
+    white-space: nowrap;
+    transition: background-color 0.15s ease, color 0.15s ease;
+}
+
+.fobtn:hover {
+    background: var(--fo-hover);
+    color: var(--fo-fg);
+}
+
+.fobtn.primary {
+    background: var(--fo-accent);
+    color: var(--fo-accent-fg);
+}
+
+.fobtn.primary:hover {
+    background: var(--fo-accent);
+    color: var(--fo-accent-fg);
+    filter: brightness(1.08);
+}
+
+.fobtn.outline {
+    border-color: var(--fo-btn-border);
+    color: var(--fo-fg);
+}
+
+.fobtn:disabled {
+    opacity: 0.45;
+    cursor: default;
+}
+
+.fobtn:disabled:hover {
+    background: transparent;
+    filter: none;
+}
+
+.fobtn.primary:disabled:hover {
+    background: var(--fo-accent);
+}
+
+.fobtn i.icon {
+    margin: 0 5px 0 0;
+    height: auto;
+    width: auto;
+    font-size: 11px;
+}
+
+/*
+    Narrow windows give up the parts that matter least, in order, so the controls
+    always keep fitting instead of pushing the dialog wider than the window it
+    sits in: first the running total, then the labels of the footer buttons.
+*/
+@media (max-width: 420px) {
+    .fototal {
+        display: none;
+    }
+
+    .fofooterbtns {
+        flex: 1 1 auto;
+        min-width: 0;
+        justify-content: flex-end;
+    }
+}
+
+@media (max-width: 340px) {
+    /* Footer buttons go icon only, they carry their label as a tooltip */
+    .fofooterbtns .fobtn span {
+        display: none;
+    }
+
+    .fofooterbtns .fobtn i.icon {
+        margin-right: 0;
+    }
+
+    .fofooterbtns .fobtn {
+        padding: 8px 10px;
+    }
+
+    .fooperation {
+        padding-left: 10px;
+        padding-right: 10px;
+    }
+
+    .forowicon {
+        margin-right: 8px;
+    }
+
+    .forowctrl {
+        margin-left: 6px;
+    }
+}

+ 35 - 828
src/web/SystemAO/file_system/file_operation.html

@@ -9,842 +9,49 @@
         <script type="text/javascript" src="../../script/semantic/semantic.min.js"></script>
         <script type="text/javascript" src="../../script/ao_module.js"></script>
         <script type="text/javascript" src="../../script/applocale.js"></script>
-        <style>
-            body{
-                overflow: hidden;
-            }
-            .banner{
-                /*background-color:#2b4871;*/
-                background: rgb(43,72,113);
-                background: linear-gradient(153deg, rgba(43,72,113,1) 43%, rgba(141,146,147,1) 100%); 
-                height:50px;
-                padding:12px;
-                padding-left:20px;
-                padding-top:16px;
-            }
-
-            #opricon{
-                position:absolute;
-                top:0px;
-                right:0px;
-                width:80px;
-                height:80px;
-            }
-            .title{
-                color:white;
-                font-size:130%;
-            }
-            .content{
-                padding:12px;
-            }
-            .info{
-                margin-top:3px;
-                white-space: nowrap;
-                overflow: hidden;
-                text-overflow: ellipsis;
-            }
-        </style>
+        <link rel="stylesheet" href="file_operation.css">
     </head>
     <body>
-        <div class="banner">
-            <div class="title" locale="banner/title">Calculating Operation</div>
-            <img id="opricon" src="img/loading.png" class="ui image"></img>
-        </div>
-        <div class="content">
-            <div class="info"><span locale="info/from">From:</span> <span id="src"></span></div>
-            <div class="info"><span locale="info/to">To:</span> <span id="dest"></span></div>
-            <div class="info"><span locale="info/progress">Progress:</span> <span id="progress"> <i class="loading spinner icon"></i> <span>Calculating</span></div>
-            <div class="ui active small progress" style="margin-top:18px;">
-                <div id="progressbar" class="bar" style="width:100%; background-color:#4287f5;"></div>
-            </div>
-            <div id="advanceControlbtns" class="ui right floated small buttons" style="margin-top: -2em; display: none;">
-                <div id="pauseButton" locale="button/pause" class="ui basic grey button" onclick="togglePauseTask();">Pause</div>
-                <div id="cancelButton" class="ui basic red button" locale="button/cancel" onclick="cancelTask();">Cancel</div>
+        <div id="dialog" class="fodialog">
+            <div class="foheader">
+                <div class="fotitle" id="dialogTitle">File Operation</div>
+                <div class="foheaderbtns">
+                    <div class="foiconbtn" id="collapseBtn" title="Collapse" onclick="toggleCollapse();">
+                        <i class="chevron down icon"></i>
+                    </div>
+                </div>
             </div>
-        </div>
-        <div class="ui modal" id="duplicateAction">
-            <div class="content">
-                <div class="description" style="padding: 0px !important;">
-                    <p><i class="big exclamation triangle icon"></i> <span locale="dup/question">File with same name already exists. <b>Which action should be taken?</b></span></p><br>
+            <div class="fosummary" id="collapsedSummary">
+                <div class="foprogress">
+                    <div class="bar" id="summaryBar" style="width: 0%;"></div>
                 </div>
+                <div class="fosummarypercent" id="summaryPercent">0%</div>
             </div>
-            <div class="actions">
-                <div locale="dup/overwrite" class="ui labeled button" onclick="continueProcess('overwrite');">
-                    Overwrite
+            <div class="fobody" id="dialogBody">
+                <div id="operationList"></div>
+                <div id="emptyState" class="foempty">
+                    <i class="check circle outline icon"></i>
+                    <span locale="empty/noOperation">No file operation running</span>
                 </div>
-                <div locale="dup/skip" class="ui labeled button" onclick="continueProcess('skip');">
-                    Skip
+            </div>
+            <div class="fofooter" id="dialogFooter">
+                <div class="fototal">
+                    <i class="cloud icon"></i>
+                    <span id="totalSizeText"></span>
                 </div>
-                <div locale="dup/renameAndKeep" class="ui labeled button" style="color: #2fb55c;" onclick="continueProcess('keep');">
-                    Rename & Keep
+                <div class="fofooterbtns">
+                    <button class="fobtn" id="clearCompletedBtn" onclick="clearCompleted();">
+                        <i class="trash alternate outline icon"></i>
+                        <span locale="footer/clearCompleted">Clear completed</span>
+                    </button>
+                    <button class="fobtn primary" id="cancelAllBtn" onclick="cancelAll();">
+                        <i class="times icon"></i>
+                        <span locale="footer/cancelAll">Cancel all</span>
+                    </button>
                 </div>
-              
             </div>
         </div>
-        <script>
-            /*
-                ArOZ Online File Operation Listener
-                Usage: Pass in the following JSON object as hash with encodeURIComponent after JSON stringify
-                {
-                    opr: {move / copy / zip / unzip / download / zipAndDown / unzipAndOpen},
-                    src: {filelist, allow multiple files},
-                    dest: {filepath},
-                    
-                    //Optional paramters
-                    overwriteMode: {skip / overwrite / keep},
-                    callbackWindowID: {floatWindow ID},
-                    callbackFunction: {target Window Function Name as String}
-                }
-
-                **For download opr, it will first buffer into the browser memory.
-                It is not recommended for files > 2GB (Firefox Limit)
-
-                Example callbackFunction: "refreshList()" (string)
-
-            */
-            var operationConfig = null;
-            var opr = "";
-            var oprId = "";
-            var originalIcon = "";
-            var paused = false;
-            var maxPathDisplayLength = 40;
-            var legacyMode = !('WebSocket' in window || 'MozWebSocket' in window); //Use AJAX instead of WebSocket if legacy mode is activated
-            var enterErrorMode = false;
-
-            //Initalized floatWindow events
-            ao_module_setFixedWindowSize();
-            ao_module_setWindowSize(400,220);
-            
-            if (applocale){
-                //Applocale found. Do localization
-                applocale.init("../locale/file_operation.json", function(){
-                    applocale.translate();
-                    init();
-                });
-            }else{
-                //Applocale not found. Is this a trim down version of ArozOS?
-                applocale = {
-                    getString: function(key, original){
-                        return original;
-                    }
-                }
-                init();
-            }
-
-            
-            function init(){
-                console.log("Checking launch parameters...");
-                if (window.location.hash.length > 0){
-                    //OK to proceed
-                    try{
-                        operationConfig = JSON.parse(decodeURIComponent(window.location.hash.substring(1)));
-                        
-                        //Check if there are any missing paratmers
-                        configValid = true;
-                        if (typeof operationConfig.opr == "undefined"){ configValid = false; }
-                        if (typeof operationConfig.src == "undefined"){ configValid = false; }
-                        if (typeof operationConfig.dest == "undefined"){ configValid = false; }
-                        
-                        if (!configValid){
-                            console.log("Invalid file operation config. Please see the file_operation.html source code for the correct config json object.")
-                            ao_module_close();
-                            return;
-                        }
-
-                        //Parse the missing argument if there are any
-                        if (typeof operationConfig.overwriteMode == "undefined"){
-                            operationConfig.overwriteMode = "skip";
-                        }
-
-                        //Update 17-12-2020, ask the user for overwrite mode if file duplicate exists
-                        if (operationConfig.overwriteMode == "ask"){
-                            //Check if any file duplication before proceeding
-                            console.log(operationConfig.src);
-
-                            $.ajax({
-                                url: "../../system/file_system/listDir",
-                                data: {dir: operationConfig.dest},
-                                success: function(filelist){
-                                    //Check for duplication
-                                    var srcFilenameList = [];
-                                    operationConfig.src.forEach(srcpath => {
-                                        var filename = srcpath.split("/").pop();
-                                        srcFilenameList.push(filename);
-                                    })
-                                    var duplicateFound = filelist.some(function(file){
-                                        return srcFilenameList.includes(file.Filename);
-                                    }); 
-
-                                    console.log(filelist);
-                                    console.log(operationConfig.src);
-
-                                    if (duplicateFound){
-                                        //Duplication found. 
-                                        $("#duplicateAction").modal({
-                                            closable: false
-                                        }).modal("show");
-
-                                    }else{
-                                        //Duplication not found. Start the operation with default mode
-                                        operationConfig.overwriteMode = "skip";
-                                        processOperations(operationConfig);
-                                    }
-
-
-                                }
-                            })
-                        }else{
-                            //All information are defined. Process it now.
-                            processOperations(operationConfig)
-                        }
-                    
-                    }catch(ex){
-                        //Failed.
-                        console.log("Argument parse error", ex);
-                    }
-                    
-
-                }else{
-                    alert("Invalid use of File Operation Listener.")
-                    ao_module_close();
-                }
-            }
-
-            function continueProcess(duplicateMode){
-                operationConfig.overwriteMode = duplicateMode;
-                $("#duplicateAction").modal("hide");
-                processOperations(operationConfig)
-            }
-
-            function processOperations(operationConfig){
-                //Update the display information
-                $("#src").text(operationConfig.src);
-                $("#dest").text(operationConfig.dest);
-                opr = operationConfig.opr;
-                updateTitle(operationConfig.src.length, operationConfig.opr);
-
-                //Check which type of the oprs is about. And assign the related functions to start
-                if (operationConfig.opr == "move"){
-                    $("#opricon").attr("src","img/move.gif");
-                    originalIcon = "img/move.gif";
-                    cut(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
-                
-                }else if (operationConfig.opr == "copy"){
-                    $("#opricon").attr("src","img/copy.gif");
-                    originalIcon = "img/copy.gif"
-                    copyopr(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
-                
-                }else if (operationConfig.opr == "zip"){
-                    $("#opricon").attr("src","img/zip.gif");
-                    originalIcon = "img/zip.gif"
-                    zip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
-                
-                }else if (operationConfig.opr == "unzip"){
-                    $("#opricon").attr("src","img/unzip.gif");
-                    originalIcon = "img/unzip.gif"
-                    unzip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
-                }else if (operationConfig.opr == "unzipAndOpen"){
-                    $("#opricon").attr("src","img/unzip.gif");
-                    originalIcon = "img/unzip.gif"
-                    unzip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode, function(){
-                        //Open the target directory
-
-                    });
-                }
-            }
-
-            //Unzip zip
-            function unzip(srcList, dest, overwriteMode, callback=undefined){
-                if (legacyMode){
-                    //Run in legacy mode
-                    requestCSRFToken(function(token){
-                        $.ajax({
-                            type: 'POST',
-                            url: `../../system/file_system/fileOpr`,
-                            data: {opr: "unzip" ,src: JSON.stringify(srcList), dest: dest, csrft: token},
-                            success: function(data){
-                                handleFinish(data);
-                            }
-                        });
-                    });
-                    
-                }else{
-                    //Filter all + sign in the list
-                    var filteredSrcList = [];
-                    srcList.forEach(src => {
-                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
-                    });
-
-                    //Open WebSocket
-                    var endpoint = getWSEndpoint() + `?opr=unzip&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
-                    console.log(endpoint);
-                    var ws = new WebSocket(endpoint);
-
-                    ws.onopen = function(){
-                        //Do nothing. Just listen to the progress update
-                    };
-
-                    ws.onmessage = function (evt) { 
-                        var data = evt.data;
-                        var progress = JSON.parse(data);
-                        console.log(progress);
-                        if (progress.oprid != undefined){
-                            //This operation is assigned an ongoing task id. Show pause and cancel
-                            showPauseCancelButton();
-                            oprId = progress.oprid;
-                        }else if (progress.Error != ""){
-                            //Something went wrong
-                            $("#progressbar").css("background-color", "#eb3f28");
-                            enterErrorMode = true;
-                            handleFinish({error: progress.Error});
-                        }else{
-                            //Update the progress display
-                            var currentSrc = truncate(progress.LatestFile, maxPathDisplayLength);
-                            var filteredDest = operationConfig.dest.trim();
-                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
-                                filteredDest += "/"
-                            }
-                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
-                            $("#src").text(currentSrc);
-                            $("#dest").text(currentDest);
-
-                            handleProgressUpdate(progress);
-                        }
-                    };
-
-                    ws.onclose = function() {
-                        if (!enterErrorMode){
-                            $("#progressbar").css("background-color", "#2bba35");
-                            $("#progressbar").css("width", "100%");
-                            $("#progress").text("100%");
-                            $("#opricon").attr("src", "img/done.png")
-                            setTimeout(function(){
-                                if (operationConfig.opr == "unzipAndOpen"){
-                                    //If open after unzip is required
-                                    ao_module_openPath(operationConfig.dest);
-                                }
-                                ao_module_close();
-                            }, 100);
-                        }
-                    };  
-
-                    ws.onerror = function(event){
-                        console.error("WebSocket error observed:", event);
-                        legacyMode = true;
-                        console.log("Falling back to Legacy Mode");
-                        unzip(srcList, dest, overwriteMode, callback);
-                    }
-                }
-            }
-
-            //Create zip
-            function zip(srcList, dest, overwriteMode){
-                if (legacyMode){
-                    //Run in legacy mode
-                    requestCSRFToken(function(token){
-                        $.ajax({
-                            type: 'POST',
-                            url: `../../system/file_system/fileOpr`,
-                            data: {opr: "zip" ,src: JSON.stringify(srcList), dest: dest, csrft: token},
-                            success: function(data){
-                                handleFinish(data);
-                            }
-                        });
-                    });
-                }else{
-                     //Replace all + sign with tag
-                    var filteredSrcList = [];
-                    srcList.forEach(src => {
-                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
-                    })
-
-                    //Start WebSocket connection
-                    var endpoint = getWSEndpoint() + `?opr=zip&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
-                    console.log(endpoint);
-                    var ws = new WebSocket(endpoint);
-                    var srcZipRoot = "";
-                    ws.onopen = function() {
-                        console.log("File Operation WebSocket opened")
-                        //Emulate the src folder
-                        var srcDir = srcList[0].split("/");
-                        srcDir.pop();
-                        srcDir = srcDir.join("/");
-                        srcZipRoot = srcDir;
-                        var currentSrc = truncate(srcDir, maxPathDisplayLength);
-                        $("#src").text(currentSrc);
-
-                        //Emulate the dest folder
-                        var destFolderName = dest.substr(0, dest.length - 1).split('/').pop();
-                        destFolderName += ".zip";
-                        var currentDest = truncate(dest + destFolderName, maxPathDisplayLength);
-                        $("#dest").text(currentDest);
-
-                    };
-
-                    ws.onmessage = function (evt) { 
-                        var data = evt.data;
-                        var progress = JSON.parse(data);
-                        if (progress.oprid != undefined){
-                            //This operation is assigned an ongoing task id. Show pause and cancel
-                            showPauseCancelButton();
-                            oprId = progress.oprid;
-                        }else if (progress.Error != ""){
-                            //Something went wrong
-                            $("#progressbar").css("background-color", "#eb3f28");
-                            enterErrorMode = true;
-                            handleFinish({error: progress.Error});
-                        }else{
-                            //Update the progress display
-                            var currentSrc = truncate(srcZipRoot + "/" + progress.LatestFile, maxPathDisplayLength);
-                            var filteredDest = operationConfig.dest.trim();
-                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
-                                filteredDest += "/"
-                            }
-                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
-                            $("#src").text(currentSrc);
-                            $("#dest").text(currentDest);
-                            handleProgressUpdate(progress);
-                           
-                        }
-                    };
-                            
-                    ws.onclose = function() { 
-                        //Transfer finished! Set OK and close in 1 second
-                        if (!enterErrorMode){
-                            $("#progressbar").css("background-color", "#2bba35");
-                            $("#progressbar").css("width", "100%");
-                            $("#progress").text("100%")
-                            handleFinish({});
-                        }
-                    };
-
-                    ws.onerror = function(event){
-                        console.error("WebSocket error observed:", event);
-                        legacyMode = true;
-                        console.log("Falling back to Legacy Mode");
-                        zip(srcList, dest, overwriteMode);
-                    }
-                }
-            }
-
-            function cut(srcList, dest, overwriteMode){
-                if (legacyMode){
-                    console.log("WebSocket not found, Running in legacy mode");
-                    requestCSRFToken(function(token){
-                        $.ajax({
-                            type: 'POST',
-                            url: `../../system/file_system/fileOpr`,
-                            data: {opr: "move" ,src: JSON.stringify(srcList), dest: dest,existsresp: overwriteMode, csrft: token},
-                            success: function(data){
-                                handleFinish(data);
-                            }
-                        });
-                    });
-
-                    
-                }else{
-                    //Replace all + sign in srclist with {{plus_sign}}
-                    var filteredSrcList = [];
-                    srcList.forEach(src => {
-                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
-                    })
-
-                    //Use Websocket for operation updates
-                    var endpoint = getWSEndpoint() + `?opr=move&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
-                    console.log(endpoint);
-                    var ws = new WebSocket(endpoint);
-                    ws.onopen = function() {
-                        console.log("File Operation WebSocket opened")
-                    };
-                        
-                    ws.onmessage = function (evt) { 
-                        var data = evt.data;
-                        var progress = JSON.parse(data);
-                        if (progress.oprid != undefined){
-                            //This operation is assigned an ongoing task id. Show pause and cancel
-                            showPauseCancelButton();
-                            oprId = progress.oprid;
-                        }else if (progress.Error != ""){
-                            $("#progressbar").css("background-color", "#eb3f28");
-                            enterErrorMode = true;
-                            handleFinish({error: progress.Error});
-                           
-                        }else{
-                            var currentSrc = truncate(operationConfig.src + "/" + progress.LatestFile, maxPathDisplayLength);
-                            var filteredDest = operationConfig.dest.trim();
-                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
-                                filteredDest += "/"
-                            }
-                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
-                            $("#src").text(currentSrc);
-                            $("#dest").text(currentDest);
-
-                            handleProgressUpdate(progress);
-                        }
-                        
-                    };
-                        
-                    ws.onclose = function() { 
-                        //Transfer finished! Set OK and close in 1 second
-                        if (!enterErrorMode){
-                            $("#progressbar").css("background-color", "#2bba35");
-                            $("#progressbar").css("width", "100%");
-                            $("#progress").text("100%")
-                            handleFinish({});
-                        }
-                     
-                        
-                    };
-
-                    ws.onerror = function(event){
-                        console.error("WebSocket error observed:", event);
-                        console.log("Falling back to Legacy Mode")
-                        legacyMode = true;
-                        cut(srcList, dest, overwriteMode)
-                    }
-
-                }
-               
-            }
-
-            function copyopr(srcList, dest, overwriteMode){
-                if (legacyMode){
-                    //Open operation in legacy mode
-                    console.log("WebSocket not found, Running in legacy mode");
-                    requestCSRFToken(function(token){
-                        $.ajax({
-                            type: 'POST',
-                            url: `../../system/file_system/fileOpr`,
-                            data: {opr: "copy" ,src: JSON.stringify(srcList), dest: dest,existsresp: overwriteMode , csrft: token},
-                            success: function(data){
-                                handleFinish(data);
-                            }
-                        });
-                    });
-
-                    
-                }else{
-                    var filteredSrcList = [];
-                    srcList.forEach(src => {
-                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
-                    })
-
-
-                   //Use Websocket for operation updates
-                   var endpoint = getWSEndpoint() + `?opr=copy&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
-                    var ws = new WebSocket(endpoint);
-                    ws.onopen = function() {
-                        console.log("File Operation WebSocket opened")
-                    };
-                        
-                    ws.onmessage = function (evt) { 
-                        var data = evt.data;
-                        var progress = JSON.parse(data);
-                        if (progress.oprid != undefined){
-                            //This operation is assigned an ongoing task id. Show pause and cancel
-                            showPauseCancelButton();
-                            oprId = progress.oprid;
-                        }else if (progress.Error != ""){
-                            $("#progressbar").css("background-color", "#eb3f28");
-                            enterErrorMode = true;
-                            handleFinish({error: progress.Error});
-                        }else{
-                            var currentSrc = truncate(operationConfig.src + "/" + progress.LatestFile, maxPathDisplayLength);
-                            var filteredDest = operationConfig.dest.trim();
-                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
-                                filteredDest += "/"
-                            }
-                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
-                            $("#src").text(currentSrc);
-                            $("#dest").text(currentDest);
-                            
-                            handleProgressUpdate(progress);
-                        }
-                        
-                    };
-                        
-                    ws.onclose = function() { 
-                        //Transfer finished! Set OK and close in 1 second
-                        if (!enterErrorMode){
-                            $("#progressbar").css("background-color", "#2bba35");
-                            $("#progressbar").css("width", "100%");
-                            $("#progress").text("100%");
-                            handleFinish({});
-                        }
-                    };
-
-                    ws.onerror = function(event){
-                        console.error("WebSocket error observed:", event);
-                        console.log("Falling back to Legacy Mode")
-                        legacyMode = true;
-                        copyopr(srcList, dest, overwriteMode)
-                    }
-
-                }
-               
-            }
-
-            var truncate = function (fullStr, strLen, separator) {
-                if (fullStr.length <= strLen) return fullStr;
-
-                separator = separator || '...';
-
-                var sepLen = separator.length,
-                    charsToShow = strLen - sepLen,
-                    frontChars = Math.ceil(charsToShow/2),
-                    backChars = Math.floor(charsToShow/2);
-
-                return fullStr.substr(0, frontChars) + 
-                        separator + 
-                        fullStr.substr(fullStr.length - backChars);
-                 };
-
-            function getWSEndpoint(){
-                //Open opeartion in websocket
-                let protocol = "wss://";
-                if (location.protocol !== 'https:') {
-                    protocol = "ws://";
-                }
-
-                var port = window.location.port;
-                if (window.location.port == ""){
-                    if (location.protocol !== 'https:') {
-                        port = "80";
-                    }else{
-                        port = "443";
-                    }
-                    
-                }
-
-                wsControlEndpoint = (protocol + window.location.hostname + ":" + port + "/system/file_system/ws/fileOpr");
-                return wsControlEndpoint;
-            }
-
-            function updateTitle(fileNumber, opr){
-                var title = "";
-                if (opr == "move"){
-                    title = applocale.getString("title/moving","Moving ");
-                }else if (opr == "copy"){
-                    title = applocale.getString("title/copying","Copying ");
-                }else if (opr == "zip" || opr == "zipAndDownload"){
-                    title = applocale.getString("title/zipping","Zipping ");
-                }else if (opr == "download"){
-                    title = applocale.getString("title/downloading","Downloading ");
-                }else if (opr == "unzip" || opr == "unzipAndOpen"){
-                    title = applocale.getString("title/unzipping","Unzipping ");
-                }
-
-                title += fileNumber + " ";
-                if (fileNumber == 1){
-                    title += applocale.getString("title/file"," File");
-                }else{
-                    title += applocale.getString("title/files"," Files");
-                }
-
-                $(".title").text(title);
-            }
-            
-            function handleProgressUpdate(progress){
-                if (progress.StatusFlag != undefined){
-                    switch (progress.StatusFlag) {
-                        case 1:
-                            if ($("#opricon").attr("src") != "img/paused.png"){
-                                //Show paused UI state
-                                $("#opricon").attr("src", "img/paused.png");
-                                $("#pauseButton").text(applocale.getString("button/resume","Resume"));
-                            }
-                            break;
-                        case 2:
-                        if ($("#opricon").attr("src") != "img/error.png"){
-                                $("#opricon").attr("src", "img/error.png");
-                            }
-                            break;
-                        default:
-                            if ($("#opricon").attr("src") != originalIcon){
-                                //Show 
-                                $("#opricon").attr("src",originalIcon);
-                                $("#pauseButton").text(applocale.getString("button/pause","Pause"));
-                            }
-                    }
-                }
-                $("#progressbar").css("width", progress.Progress + "%");
-                $("#progress").text(progress.Progress + "%")
-                if (progress.Progress >= 100){
-                    //Set progress bar to green
-                    $("#progressbar").css("background-color", "#2bba35");
-                    $("#progress").text("100%");
-                }
-            }
-
-            function handleFinish(data){
-                $("#advanceControlbtns").find(".button").addClass("disabled");
-                if (data.error !== undefined){
-                    $("#progressbar").css("background-color","#db2828");
-                    $("#progressbar").parent().removeClass('active');
-                    $(".title").html(applocale.getString("error/" + data.error,data.error));
-                    $("#opricon").attr("src", "img/error.png");
-                    enterErrorMode = true;
-                    $("#cancelButton").html(applocale.getString("button/cancel", "Cancel"));
-                    return
-                }else{
-                    $("#progressbar").css("background-color","#21ba45");
-                    $("#progressbar").parent().removeClass('active');
-                    $("#opricon").attr("src", "img/done.png");
-
-                    if (opr == "move" || opr == "copy" || opr == "zip" || opr == "unzip"){
-                        //Action completed. close window.
-                        setTimeout(function(){
-                            //Do callback if exists
-                            if (operationConfig.callbackWindowID == "desktop"){
-                                //Special call from desktop
-                                parent.eval(operationConfig.callbackFunction);
-                            }else if (ao_module_virtualDesktop && operationConfig.callbackWindowID !== undefined && operationConfig.callbackFunction !== undefined){
-                                var callbackWindowObject = parent.getFloatWindowByID(operationConfig.callbackWindowID)
-                                var windowObject = $(callbackWindowObject).find("iframe")[0];
-                                if (windowObject == undefined || windowObject == null){
-                                    //Caller no longer exists.
-                                    
-                                }else{
-                                    //Caller still exists. Do callback events
-                                    //console.log(windowObject.contentWindow, operationConfig.callbackFunction);
-                                    windowObject.contentWindow.eval(operationConfig.callbackFunction);
-                                }
-                                
-                            }
-
-                            //If the target or src is desktop, refresh desktop as well
-                            if(pathIsOnDesktop(operationConfig.dest) || pathIsOnDesktop(operationConfig.src[0])){
-                                if (ao_module_virtualDesktop){
-                                    parent.refresh(undefined, true);
-                                }
-                            }
-
-                            if (!enterErrorMode){
-                                ao_module_close();
-                                setTimeout(function(){
-                                    //If ao_module_close is not working for some reason
-                                    open(location, '_self').close();
-                                }, 500);
-                            }
-                        }, 1000);
-                    }else if (opr == "download"){
-                        //Create download from buffer
-                        
-                    }else if (opr == "zipAndDown"){
-                        //Download
-                        
-                    }else if (opr == "unzipAndOpen"){
-                        //Unzip and open the target directory
-                        setTimeout(function(){
-                            //Open the target directory
-                            ao_module_openPath(operationConfig.dest);
-                            //Close the window
-                            ao_module_close();
-                        }, 1000);
-                       
-                    }
-                }
-                console.log(data);
-            }
-
-            function pathIsOnDesktop(path){
-                var filteredDest = path;
-                if (filteredDest.substr(filteredDest.length - 1) == "/"){
-                    filteredDest = filteredDest.substr(0, filteredDest.length - 1);
-                }
-                var dirChunk = filteredDest.split("/");
-                console.log(dirChunk);
-                if (dirChunk.length == 2 || dirChunk.length == 3){
-                    if (dirChunk[0].toLowerCase() == "user:" && dirChunk[1].toLowerCase() == "desktop"){
-                        //This is a direct access desktop file
-                        return true;
-                    }
-                }
-                return false;
-            }
-
-            function requestCSRFToken(callback){
-                $.ajax({
-                    url: "../../system/csrf/new",
-                    success: function(token){
-                        callback(token);
-                    }
-                })
-            }
-
-            /*
-                Functions related to pause and cancel of the file operations
-            */
-            
-            function togglePauseTask(){
-                if (paused){
-                    //Resume
-                    $.ajax({
-                        url: "../../system/file_system/ongoing",
-                        method: "POST",
-                        data: {"oprid": oprId, "flag": "continue"},
-                        success: function(data){
-                            if (data.error != undefined){
-                                console.log(data.error);
-                            }else{
-                                paused = false;
-                                $("#pauseButton").text(applocale.getString("button/pause","Pause"));
-                                $("#opricon").attr("src",originalIcon);
-                            }
-                        }
-                    });
-                }else{
-                    //Pause
-                    $.ajax({
-                        url: "../../system/file_system/ongoing",
-                        method: "POST",
-                        data: {"oprid": oprId, "flag": "pause"},
-                        success: function(data){
-                            if (data.error != undefined){
-                                console.log(data.error);
-                            }else{
-                                paused = true;
-                                $("#opricon").attr("src","img/paused.png");
-                                $("#pauseButton").text(applocale.getString("button/resume","Resume"));
-                            }
-                        }
-                    });
-                }
-                
-            }
-
-            //Cancel the current ongoing task
-            function cancelTask(){
-                $.ajax({
-                    url: "../../system/file_system/ongoing",
-                    method: "POST",
-                    data: {"oprid": oprId, "flag": "cancel"},
-                    success: function(data){
-                        if (data.error != undefined){
-                            console.log(data.error);
-                        }else{
-                            //Disable further operation untill task cancelled
-                            $("#advanceControlbtns").find(".button").addClass("disabled");
-                            $("#cancelButton").html(`<i class="ui loading spinner icon"></i>`);
-                        }
-                    }
-                });
-            }
-
-            function showPauseCancelButton(){
-                ao_module_setWindowSize(400,254);
-                $("#progressbar").parent().css({
-                    "margin-bottom":"1em"
-                });
-                $("#advanceControlbtns").show();
-            }
-
-
-            function hidePauseCancelButton(){
-                ao_module_setWindowSize(400,220);
-                $("#progressbar").parent().css("margin-bottom", "2.5em");
-                $("#advanceControlbtns").hide();
-            }
-        </script>
+        <script type="text/javascript" src="js/file_operation/icons.js"></script>
+        <script type="text/javascript" src="js/file_operation/dialog.js"></script>
     </body>
-</html>
+</html>

+ 5 - 49
src/web/SystemAO/file_system/js/explorer/archive.js

@@ -17,35 +17,14 @@ function zipFile(){
 
 
     //Request to create a zip file, named with the parent dir name
-    var oprConfig = {
+    ao_module_startFileOperation({
         opr: "zip",
         src: zippingFiles,
         dest: currentPath,
         overwriteMode: "overwrite",
         callbackWindowID: ao_module_windowID,
         callbackFunction: `callRefresh("${currentPath}")`
-    }
-    var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-    var title = applocale.getString("opr/zip/zipping","Zipping ") +  zippingFiles.length;
-    if (fileList.length > 1){
-        title += applocale.getString("opr/zip/files", " files");
-    }else{
-        title += applocale.getString("opr/zip/file"," file");
-    }
-
-    if (!ao_module_virtualDesktop){
-        window.open("file_operation.html#" + configHash);
-    }else{
-        parent.newFloatWindow({
-            url: "SystemAO/file_system/file_operation.html#" + configHash,
-            width: 400,
-            height: 220,
-            appicon: "SystemAO/file_system/img/selector.png",
-            title: title
-        });
-    }
-
-    
+    });
 }
 
 function unzipHere(){
@@ -67,38 +46,15 @@ function unzipHere(){
 
     //Start unzip progress
 
-    //Unzip and open them to tmp:/
-    var oprConfig = {
+    //Extract the archives into the folder the user is looking at
+    ao_module_startFileOperation({
         opr: "unzip",
         src: unzippingFiles,
         dest: currentPath,
         overwriteMode: "overwrite",
         callbackWindowID: ao_module_windowID,
         callbackFunction: `callRefresh("${currentPath}")`
-    }
-
-    //Render the dialog title name
-    var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-    var title = applocale.getString("opr/zip/unzipping","Unzipping ") + unzippingFiles.length;
-    if (unzippingFiles.length > 1){
-        title += applocale.getString("opr/zip/files", " files");
-    }else{
-        title += applocale.getString("opr/zip/file"," file");
-    }
-
-
-    if (!ao_module_virtualDesktop){
-        window.open("file_operation.html#" + configHash);
-    }else{
-        parent.newFloatWindow({
-            url: "SystemAO/file_system/file_operation.html#" + configHash,
-            width: 400,
-            height: 220,
-            appicon: "SystemAO/file_system/img/selector.png",
-            title: title,
-        });
-    }
-
+    });
 }
 
 

+ 6 - 0
src/web/SystemAO/file_system/js/explorer/boot.js

@@ -38,6 +38,12 @@ $(document).ready(function(){
             applyOprBarVisibility();
         });
 
+        //Hidden files stay hidden unless the user asked for them
+        loadPreference("file_explorer/showHidden", function(value){
+            showHiddenFiles = (value === "true" || value === true);
+            updateHiddenFilesToggle();
+        });
+
         //Restore the saved grid tile size
         loadPreference("file_explorer/gridZoom", function(value){
             let z = parseInt(value);

+ 4 - 32
src/web/SystemAO/file_system/js/explorer/clipboard.js

@@ -126,28 +126,14 @@ function paste(redirectPasteTarget="", nocheck=false){
                         });
                         
                     }else{
-                        //Pass the request to operation handler
-                        var oprConfig = {
+                        //Pass the request to the system wide file operation dialog
+                        ao_module_startFileOperation({
                             opr: "move",
                             src: fileList,
                             dest: targetDir,
                             overwriteMode: overwriteMode,
                             callbackWindowID: ao_module_windowID,
                             callbackFunction: `callRefresh("${targetDir}")`
-                        }
-                        var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-                        var title = "Moving " + fileList.length;
-                        if (fileList.length > 1){
-                            title += " files";
-                        }else{
-                            title += " file";
-                        }
-                        parent.newFloatWindow({
-                            url: "SystemAO/file_system/file_operation.html#" + configHash,
-                            width: 400,
-                            height: 220,
-                            appicon: "SystemAO/file_system/img/selector.png",
-                            title: title
                         });
                         hideAllPopupWindows();
                     }
@@ -187,28 +173,14 @@ function paste(redirectPasteTarget="", nocheck=false){
                         });
                         
                     }else{
-                        //Pass the request to operation handler
-                            var oprConfig = {
+                        //Pass the request to the system wide file operation dialog
+                        ao_module_startFileOperation({
                             opr: "copy",
                             src: fileList,
                             dest: targetDir,
                             overwriteMode: overwriteMode,
                             callbackWindowID: ao_module_windowID,
                             callbackFunction: `callRefresh("${targetDir}")`
-                        }
-                        var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-                        var title = "Copying " + fileList.length;
-                        if (fileList.length > 1){
-                            title += " files";
-                        }else{
-                            title += " file";
-                        }
-                        parent.newFloatWindow({
-                            url: "SystemAO/file_system/file_operation.html#" + configHash,
-                            width: 400,
-                            height: 220,
-                            appicon: "SystemAO/file_system/img/selector.png",
-                            title: title
                         });
                         hideAllPopupWindows();
                     }

+ 2 - 1
src/web/SystemAO/file_system/js/explorer/listing.js

@@ -126,7 +126,8 @@ function listDirectory(path, callback=undefined, recordUndo=true){
             $.ajax({
                 url: "../../system/file_system/listDir",
                 method: "POST",
-                data: {dir: decodeURIComponent(path), sort: sortMode},
+                data: {dir: decodeURIComponent(path), sort: sortMode,
+                       showHidden: showHiddenFiles ? "true" : "false"},
                 success: function(data){
                     //Parse the filelist into global variable
                     currentFilelist = [];

+ 73 - 16
src/web/SystemAO/file_system/js/explorer/properties.js

@@ -70,6 +70,60 @@ if ($(".fileObject.selected").length > 0){
 Properties Sidebar
 */
 
+/*
+    POSIX permission string as a grid.
+
+    "-rwxrwxrwx" is exact but asks the reader to count characters in threes to
+    answer "can the group write?". The same information as a table is read at a
+    glance. Anything that is not a recognisable 9 or 10 character mode string is
+    shown verbatim rather than guessed at - remote file systems and Windows
+    hosts do not all report this the same way.
+*/
+function renderPermissionTable(permission){
+    let mode = (permission == undefined || permission == null) ? "" : String(permission).trim();
+    //Drop the leading file type character when present
+    let bits = mode.length == 10 ? mode.substring(1) : mode;
+    if (bits.length != 9 || !/^[rwxsStTl-]{9}$/.test(bits)){
+        return escapeHTMLText(mode);
+    }
+
+    let rows = [
+        {label: applocale.getString("sidebar/properties/permOwner", "Owner"), offset: 0},
+        {label: applocale.getString("sidebar/properties/permGroup", "Group"), offset: 3},
+        {label: applocale.getString("sidebar/properties/permOthers", "Others"), offset: 6}
+    ];
+    let cols = [
+        applocale.getString("sidebar/properties/permRead", "Read"),
+        applocale.getString("sidebar/properties/permWrite", "Write"),
+        applocale.getString("sidebar/properties/permExec", "Exec")
+    ];
+
+    let html = '<table class="fmPermTable"><tr><th></th>';
+    for (let i = 0; i < cols.length; i++){
+        html += '<th>' + escapeHTMLText(cols[i]) + '</th>';
+    }
+    html += '</tr>';
+    rows.forEach(function(row){
+        html += '<tr><td class="fmPermWho">' + escapeHTMLText(row.label) + '</td>';
+        for (let i = 0; i < 3; i++){
+            //Only '-' means not granted; setuid/sticky letters still imply it
+            let granted = bits.charAt(row.offset + i) != "-";
+            html += '<td class="' + (granted ? "fmPermOn" : "fmPermOff") + '">' +
+                    (granted ? "✓" : "–") + '</td>';
+        }
+        html += '</tr>';
+    });
+    return html + '</table>';
+}
+
+//The mode string comes from the server, so escape before it goes into html
+function escapeHTMLText(text){
+    return String(text == undefined ? "" : text)
+        .split("&").join("&amp;")
+        .split("<").join("&lt;")
+        .split(">").join("&gt;");
+}
+
 function loadFileProperties(filepath){
 $.ajax({
     url: "../../system/file_system/getProperties",
@@ -92,28 +146,31 @@ $.ajax({
                 }
             }
             
-            //Load the preview 
+            /*
+                Preview
+
+                Hidden until a real thumbnail arrives. It used to fall back to
+                the generic file type icon, which told the reader nothing the
+                row they just clicked had not already shown them, and spent a
+                third of the panel doing it.
+
+                Hidden up front rather than only on failure, so the previously
+                selected file's image does not sit there while this one loads.
+            */
+            $(previewSidebar).find(".preview").hide();
             fetch("../../system/file_system/loadThumbnail?vpath=" + encodeURIComponent(data.VirtualPath))
             .then((response) => response.json())
             .then((imageData) => {
                 if (imageData.error !== undefined || imageData.trim() == ""){
-                    //Image load error.
-                    if (data.IsDirectory){
-                        //Load the folder image
-                        $(previewSidebar).find(".preview img").attr("src", "../../img/system/folder.svg")
-                    }else{
-                        let icon = "file outline";
-                        let ext = data.Basename.split(".").pop().toLowerCase();
-                        if (ext != ""){
-                            icon = ao_module_utils.getIconFromExt(ext);
-                        }
-                        let imagePath = "../../img/desktop/files_icon/default/" + icon + ".png";
-                        $(previewSidebar).find(".preview img").attr("src", imagePath);
-                    }
-                    
+                    //No thumbnail for this one - leave the preview hidden
+                    $(previewSidebar).find(".preview img").removeAttr("src");
                     return;
                 }
                 $(previewSidebar).find(".preview img").attr('src',"data:image/jpg;base64," + imageData);
+                $(previewSidebar).find(".preview").show();
+            })
+            .catch(() => {
+                $(previewSidebar).find(".preview").hide();
             });
 
             //Render the remaining information
@@ -156,7 +213,7 @@ $.ajax({
                     ${applocale.getString("sidebar/properties/permission", "Permission")}
                 </td>
                 <td>
-                    ${data.Permission}
+                    ${renderPermissionTable(data.Permission)}
                 </td>
             </tr><tr>
                 <td style="${styleOverwrite}">

+ 12 - 1
src/web/SystemAO/file_system/js/explorer/render.js

@@ -177,8 +177,19 @@ function fileObjectAttributes(d){
     let modAttr = ` modtime="${d.modTime}"`;
     //dragstart / drop / dragover / dblclick are delegated on #folderView by
     //bindFileListDelegates(), so rows carry no inline handlers.
+    /*
+        Dotfiles are dimmed so they read as "shown because you asked", not as
+        ordinary content. Decided from the name rather than a server flag: the
+        listing carries no hidden field, and a leading dot is the same rule the
+        server filters on.
+
+        A data attribute rather than a class: every caller below already writes
+        its own class attribute, and a second one on the same element is
+        discarded by the parser rather than merged.
+    */
+    let hiddenAttr = d.filename.charAt(0) == "." ? ` data-hidden="true"` : "";
     return `draggable="true" fileID="${d.fileID}" filename="${d.filename}"` +
-           ` filepath="${d.filepath}" type="${d.type}"${sizeAttrs}${modAttr}`;
+           ` filepath="${d.filepath}" type="${d.type}"${sizeAttrs}${modAttr}${hiddenAttr}`;
 }
 
 function renderListItem(d){

+ 1 - 0
src/web/SystemAO/file_system/js/explorer/state.js

@@ -33,6 +33,7 @@ let viewMode = "list"; //Viewmode, support {list, grid, detail}
 let sortMode = "default"; //Sortmode, support {default, reverse, smallToLarge, largeToSmall, mostRecent, leastRecent}
 let currentPath = "user:/"
 let showOprBar = true;               //Classic file operation toolbar, persisted server side
+let showHiddenFiles = false;         //Dotfiles and .metadata folders, persisted server side
 let gridZoom = 170;                  //Grid tile width in px (100-170), driven by the status bar slider
 let viewHistory = [];
 let forwardHistory = [];             //Paths popped by Back, replayed by Forward. Cleared on any other navigation. //View history

+ 21 - 0
src/web/SystemAO/file_system/js/explorer/viewmode.js

@@ -89,6 +89,26 @@ function updateViewmodeButtons(){
         });
     }
 
+/*
+    Show or hide dotfiles.
+
+    The filtering itself is the server's: listDir only returns hidden entries
+    when asked, so this re-lists rather than showing or hiding rows that were
+    never sent. Persisted server side like the toolbar preference, so it follows
+    the user between browsers.
+*/
+function toggleHiddenFiles(){
+    showHiddenFiles = !showHiddenFiles;
+    updateHiddenFilesToggle();
+    setPreference("file_explorer/showHidden", showHiddenFiles);
+    closeFileOprMenu();
+    refreshList();
+}
+
+function updateHiddenFilesToggle(){
+    $("#fmHiddenToggle").toggleClass("checked", showHiddenFiles);
+}
+
 //Update sorting method for file listing
 /*
     Apply a sort mode, persist it for this folder and re-list.
@@ -174,5 +194,6 @@ window.changeViewMode = changeViewMode;
 window.togglePreviewWindowSize = togglePreviewWindowSize;
 window.togglePropertiesView = togglePropertiesView;
 window.setSortMode = setSortMode;
+window.toggleHiddenFiles = toggleHiddenFiles;
             window.toggleSortMenu = toggleSortMenu;
             window.updateSortMenuState = updateSortMenuState;

+ 1213 - 0
src/web/SystemAO/file_system/js/file_operation/dialog.js

@@ -0,0 +1,1213 @@
+/*
+    dialog.js
+
+    The unified ArozOS file operation dialog.
+
+    There is only one of these open at a time. New operations are handed over
+    to the running dialog through window.addFileOperation() instead of opening
+    another float window, and the status of every operation of this user is
+    streamed over a single WebSocket connection. When that socket cannot be
+    opened the dialog falls back to polling the ongoing task listing endpoint.
+
+    Launch config, passed either in the URL hash or to addFileOperation():
+    {
+        opr: {move / copy / zip / unzip / unzipAndOpen},
+        src: [filelist],
+        dest: filepath,
+
+        //Optional
+        overwriteMode: {skip / overwrite / keep / ask},
+        callbackWindowID: {floatWindow ID},
+        callbackFunction: {target window function name as a string}
+    }
+*/
+
+//Control signals returned by the backend, see mod/filesystem/static.go
+var FSOPR_CONTINUE = 0;
+var FSOPR_PAUSE = 1;
+var FSOPR_CANCEL = 2;
+
+var POLLING_INTERVAL = 2000; //Status polling interval when the WebSocket is unusable, in ms
+var WS_RETRY_INTERVAL = 30000; //How often a failed WebSocket connection is retried, in ms
+var AUTOCLOSE_DELAY = 1000; //How long the dialog stays up after everything succeeded, in ms
+var MAX_SENSIBLE_ETA = 86400; //Remaining times above this are not shown at all, in seconds
+var STACKED_ROW_THRESHOLD = 8; //Operations with more files than this are drawn as one stacked row
+
+var operationConfigs = {}; //Launch config of the operations started by this dialog, keyed by oprid
+var pendingOperations = []; //Operations still waiting for the user to pick an overwrite mode
+var latestTasks = []; //Latest task listing reported by the backend
+var rateSamples = {}; //Transfer rate estimation state, keyed by oprid
+var completedHandled = {}; //Operations whose completion callback has already fired
+var statusSocket = null;
+var pollingTimer = null;
+var wsRetryTimer = null;
+var autoCloseTimer = null;
+var userIsInteracting = false;
+var collapsed = false;
+var everHadOperation = false;
+var lastWindowHeight = 0; //Last height this dialog asked its float window to take
+var lastContentHeight = 0; //Height of the rendered rows at the last resize
+var windowChromeHeight = 30; //Float window title bar and borders, measured at runtime
+var renderedStructure = ""; //Signature of the markup currently on screen
+var dynamicRows = []; //Cached nodes carrying a moving value, one per file row
+var pausedOverride = {}; //Locally applied pause state, until the backend confirms it
+
+/* ---------------------------------------------------------------
+    Startup
+--------------------------------------------------------------- */
+
+if (applocale) {
+    applocale.init("../locale/file_operation.json", function() {
+        applocale.translate();
+        init();
+    });
+} else {
+    //Applocale not found. Is this a trim down version of ArozOS?
+    applocale = {
+        getString: function(key, original) {
+            return original;
+        }
+    }
+    init();
+}
+
+function init() {
+    initTheme();
+    lastWindowHeight = 430;
+    ao_module_setWindowSize(480, 430);
+
+    //A narrow dialog drops these labels and keeps only the icons, so the button
+    //has to be able to say what it is on its own
+    $("#collapseBtn").attr("title", applocale.getString("button/collapse", "Collapse"));
+    $("#clearCompletedBtn").attr("title", applocale.getString("footer/clearCompleted", "Clear completed"));
+    $("#cancelAllBtn").attr("title", applocale.getString("footer/cancelAll", "Cancel all"));
+
+    //Keep the dialog up while the pointer is inside it
+    $(document).on("mouseenter", function() {
+        userIsInteracting = true;
+        cancelAutoClose();
+    });
+    $(document).on("mouseleave", function() {
+        userIsInteracting = false;
+        //The pointer left, the dialog may close itself again
+        render();
+    });
+
+    //Start streaming the status of all the operations of this user
+    startStatusStream();
+
+    //Queue the operation this dialog was launched with, if any
+    if (window.location.hash.length > 1) {
+        try {
+            var launchConfig = JSON.parse(decodeURIComponent(window.location.hash.substring(1)));
+            addFileOperation(launchConfig);
+        } catch (ex) {
+            console.log("[File Operation] Launch argument parse error", ex);
+        }
+    }
+
+    render();
+}
+
+function initTheme() {
+    var applyTheme = function(theme) {
+        document.documentElement.setAttribute("data-theme", theme == "dark" ? "dark" : "light");
+    };
+
+    //Follow the system theme, both under Virtual Desktop and as a standalone tab
+    ao_module_onThemeChanged(applyTheme);
+    $.get("../../system/file_system/preference?key=file_explorer/theme", function(data) {
+        applyTheme(data == "darkTheme" ? "dark" : "light");
+    }).fail(function() {
+        applyTheme("light");
+    });
+}
+
+/* ---------------------------------------------------------------
+    Public entry point: queue a new file operation into this dialog
+--------------------------------------------------------------- */
+
+window.addFileOperation = function(config) {
+    if (config == undefined || config.opr == undefined || config.src == undefined || config.dest == undefined) {
+        console.log("[File Operation] Invalid file operation config. See dialog.js for the expected config object.");
+        return false;
+    }
+
+    if (!Array.isArray(config.src)) {
+        config.src = [config.src];
+    }
+    if (config.src.length == 0) {
+        return false;
+    }
+
+    cancelAutoClose();
+    everHadOperation = true;
+
+    if (config.overwriteMode == "ask") {
+        //Ask the user what to do before starting, but only if it actually matters
+        checkForDuplication(config, function(duplicateCount) {
+            if (duplicateCount > 0) {
+                config.duplicateCount = duplicateCount;
+                config.pendingId = "pending_" + Date.now() + "_" + Math.floor(Math.random() * 100000);
+                pendingOperations.push(config);
+                render();
+            } else {
+                config.overwriteMode = "skip";
+                startOperation(config);
+            }
+        });
+    } else {
+        startOperation(config);
+    }
+    return true;
+}
+
+//Ask the backend how many of the source files already exist at the destination
+function checkForDuplication(config, callback) {
+    $.ajax({
+        type: "POST",
+        url: "../../system/file_system/validateFileOpr",
+        data: { src: JSON.stringify(config.src), dest: config.dest },
+        success: function(duplicateList) {
+            if (Array.isArray(duplicateList)) {
+                callback(duplicateList.length);
+            } else {
+                callback(0);
+            }
+        },
+        error: function() {
+            callback(0);
+        }
+    });
+}
+
+//The user picked an overwrite mode for one of the pending operations
+window.resolveDuplication = function(pendingId, overwriteMode) {
+    for (var i = 0; i < pendingOperations.length; i++) {
+        if (pendingOperations[i].pendingId == pendingId) {
+            var config = pendingOperations.splice(i, 1)[0];
+            config.overwriteMode = overwriteMode;
+            startOperation(config);
+            render();
+            return;
+        }
+    }
+}
+
+//Send the operation to the backend and let it run there in the background
+function startOperation(config) {
+    //unzipAndOpen is an unzip that opens the destination folder afterwards
+    var backendOpr = (config.opr == "unzipAndOpen") ? "unzip" : config.opr;
+
+    requestCSRFToken(function(token) {
+        $.ajax({
+            type: "POST",
+            url: "../../system/file_system/fileOprAsync",
+            data: {
+                opr: backendOpr,
+                src: JSON.stringify(config.src),
+                dest: config.dest,
+                existsresp: config.overwriteMode || "skip",
+                csrft: token
+            },
+            success: function(data) {
+                if (data.error !== undefined) {
+                    console.log("[File Operation] " + data.error);
+                    showStartupError(config, data.error);
+                    return;
+                }
+                operationConfigs[data.oprid] = config;
+                requestStatusUpdate();
+            },
+            error: function() {
+                showStartupError(config, "Unable to start file operation");
+            }
+        });
+    });
+}
+
+//An operation that never made it to the backend still deserves to be shown
+function showStartupError(config, errmsg) {
+    var files = [];
+    config.src.forEach(function(src) {
+        files.push({
+            Filename: basename(src),
+            Src: src,
+            Size: 0,
+            Done: 0,
+            Progress: 0,
+            Status: "error",
+            Error: errmsg
+        });
+    });
+
+    latestTasks.push({
+        ID: "local_" + Date.now() + "_" + Math.floor(Math.random() * 100000),
+        Operation: config.opr,
+        Src: config.src[0],
+        Dest: config.dest,
+        Progress: 0,
+        Files: files,
+        TotalSize: 0,
+        DoneSize: 0,
+        Status: "error",
+        Error: errmsg,
+        LocalOnly: true
+    });
+    render();
+}
+
+function requestCSRFToken(callback) {
+    $.ajax({
+        url: "../../system/csrf/new",
+        success: function(token) {
+            callback(token);
+        },
+        error: function() {
+            callback("");
+        }
+    });
+}
+
+/* ---------------------------------------------------------------
+    Status stream: one WebSocket for every operation of this user,
+    falling back to polling when the socket cannot be opened
+--------------------------------------------------------------- */
+
+function startStatusStream() {
+    if (!("WebSocket" in window || "MozWebSocket" in window)) {
+        console.log("[File Operation] WebSocket unsupported. Using status polling instead.");
+        startPolling();
+        return;
+    }
+
+    try {
+        statusSocket = new WebSocket(getStatusWSEndpoint());
+    } catch (ex) {
+        console.log("[File Operation] WebSocket creation failed. Using status polling instead.", ex);
+        startPolling();
+        return;
+    }
+
+    statusSocket.onopen = function() {
+        //The socket is alive, no need for the polling fallback anymore
+        stopPolling();
+    };
+
+    statusSocket.onmessage = function(evt) {
+        try {
+            handleTaskListUpdate(JSON.parse(evt.data));
+        } catch (ex) {
+            console.log("[File Operation] Malformed status update", ex);
+        }
+    };
+
+    statusSocket.onerror = function(event) {
+        console.log("[File Operation] Status WebSocket error. Falling back to status polling.", event);
+    };
+
+    statusSocket.onclose = function() {
+        statusSocket = null;
+        //The connection is gone, keep the dialog alive on polling and retry later
+        startPolling();
+        if (wsRetryTimer == null) {
+            wsRetryTimer = setTimeout(function() {
+                wsRetryTimer = null;
+                if (statusSocket == null) {
+                    startStatusStream();
+                }
+            }, WS_RETRY_INTERVAL);
+        }
+    };
+}
+
+function getStatusWSEndpoint() {
+    var protocol = (location.protocol === "https:") ? "wss://" : "ws://";
+    var port = window.location.port;
+    if (port == "") {
+        port = (location.protocol === "https:") ? "443" : "80";
+    }
+    return protocol + window.location.hostname + ":" + port + "/system/file_system/ws/fileOprStatus";
+}
+
+function startPolling() {
+    if (pollingTimer != null) {
+        return;
+    }
+    requestStatusUpdate();
+    pollingTimer = setInterval(requestStatusUpdate, POLLING_INTERVAL);
+}
+
+function stopPolling() {
+    if (pollingTimer != null) {
+        clearInterval(pollingTimer);
+        pollingTimer = null;
+    }
+}
+
+//Pull the whole task listing in one go. Used by the polling fallback and
+//right after starting an operation so the new row shows up without waiting.
+function requestStatusUpdate() {
+    $.get("../../system/file_system/ongoing?all=true", function(tasks) {
+        if (Array.isArray(tasks)) {
+            handleTaskListUpdate(tasks);
+        }
+    });
+}
+
+function handleTaskListUpdate(tasks) {
+    //Keep the operations that only exist on this client, e.g. failed startups
+    var localOnly = latestTasks.filter(function(task) {
+        return task.LocalOnly === true;
+    });
+
+    latestTasks = tasks.concat(localOnly);
+    clearConfirmedPauseOverrides();
+    latestTasks.forEach(updateRateSample);
+    latestTasks.forEach(handleTaskCompletion);
+    render();
+}
+
+/* ---------------------------------------------------------------
+    Transfer rate and time estimation
+--------------------------------------------------------------- */
+
+function updateRateSample(task) {
+    var now = Date.now();
+    var sample = rateSamples[task.ID];
+    if (sample == undefined) {
+        rateSamples[task.ID] = { time: now, done: task.DoneSize, rate: 0 };
+        return;
+    }
+
+    if (operationIsPaused(task) || taskIsFinished(task)) {
+        //No bytes move while the operation is paused. Counting that time would
+        //drag the measured rate to zero and blow the remaining time up to
+        //nonsense, so rebase the sample and measure again once it resumes.
+        sample.time = now;
+        sample.done = task.DoneSize;
+        return;
+    }
+
+    var elapsed = (now - sample.time) / 1000;
+    if (elapsed < 0.75) {
+        //Too soon for a meaningful reading
+        return;
+    }
+
+    var delta = task.DoneSize - sample.done;
+    if (delta < 0) {
+        delta = 0;
+    }
+    var instantRate = delta / elapsed;
+    //Smooth the reading so the remaining time does not jump around
+    sample.rate = (sample.rate == 0) ? instantRate : (sample.rate * 0.7 + instantRate * 0.3);
+    sample.time = now;
+    sample.done = task.DoneSize;
+}
+
+function getRemainingSeconds(task, remainingBytes) {
+    var sample = rateSamples[task.ID];
+    if (sample == undefined || sample.rate <= 0 || remainingBytes <= 0) {
+        return -1;
+    }
+
+    var remainingSeconds = remainingBytes / sample.rate;
+    if (remainingSeconds > MAX_SENSIBLE_ETA) {
+        //The transfer is barely moving. Showing a number here would only be
+        //misleading, so say nothing until the rate settles.
+        return -1;
+    }
+    return remainingSeconds;
+}
+
+/* ---------------------------------------------------------------
+    Rendering
+--------------------------------------------------------------- */
+
+/*
+    The status stream ticks twice a second. Rebuilding the whole list on every
+    tick burns GPU time on mobile and keeps destroying the buttons the user is
+    trying to press, so the markup is only rebuilt when the shape of the list
+    actually changes. In between, only the values that moved are written back.
+*/
+function render() {
+    var ongoingCount = 0;
+    var totalSize = 0;
+    var doneSize = 0;
+    var hasFinished = false;
+
+    latestTasks.forEach(function(task) {
+        if (!taskIsFinished(task)) {
+            ongoingCount++;
+        } else {
+            hasFinished = true;
+        }
+        totalSize += (task.TotalSize || 0);
+        doneSize += (task.DoneSize || 0);
+    });
+    ongoingCount += pendingOperations.length;
+
+    var structure = buildStructureSignature();
+    if (structure != renderedStructure) {
+        renderedStructure = structure;
+        rebuildOperationList();
+    }
+
+    updateDynamicValues();
+    setTextIfChanged($("#dialogTitle"), buildTitleText(ongoingCount));
+    setTextIfChanged($("#totalSizeText"), totalSize > 0 ?
+        applocale.getString("footer/total", "Total: {done} / {total}")
+            .replace("{done}", formatBytes(doneSize))
+            .replace("{total}", formatBytes(totalSize)) : "");
+    setDisabledIfChanged($("#clearCompletedBtn"), !hasFinished);
+    setDisabledIfChanged($("#cancelAllBtn"), ongoingCount == 0);
+    updateCollapsedSummary(totalSize, doneSize);
+
+    resizeToContent();
+    scheduleAutoCloseIfDone(ongoingCount);
+}
+
+/*
+    A signature of everything that changes the markup rather than just a value
+    inside it: which operations are listed, their state and the state of each of
+    their files. Progress numbers are deliberately left out of it.
+*/
+function buildStructureSignature() {
+    var parts = [];
+    pendingOperations.forEach(function(config) {
+        parts.push("p:" + config.pendingId + ":" + config.src.length + ":" + config.duplicateCount);
+    });
+    latestTasks.forEach(function(task) {
+        var signal = operationIsPaused(task) ? FSOPR_PAUSE : FSOPR_CONTINUE;
+        var states;
+        if (operationIsStacked(task)) {
+            //Only the file count is on screen, the individual states are not
+            states = "stacked:" + (task.Files || []).length;
+        } else {
+            states = (task.Files || []).map(function(file) {
+                return file.Status + "|" + file.Filename;
+            }).join(",");
+        }
+        parts.push("t:" + task.ID + ":" + task.Status + ":" + signal + ":" + (task.Error || "") + ":" + states);
+    });
+    return parts.join(";");
+}
+
+function rebuildOperationList() {
+    var html = "";
+    pendingOperations.forEach(function(config) {
+        html += renderPendingOperation(config);
+    });
+    latestTasks.forEach(function(task) {
+        html += renderOperation(task);
+    });
+
+    $("#operationList").html(html);
+    $("#emptyState").toggle(html == "");
+
+    //Cache the nodes that carry a moving value so the ticks do not have to search for them
+    dynamicRows = [];
+    $("#operationList").find(".forow[oprid]").each(function() {
+        var row = $(this);
+        dynamicRows.push({
+            oprid: row.attr("oprid"),
+            fileIndex: parseInt(row.attr("fileindex"), 10),
+            meta: row.find(".forowmeta"),
+            bar: row.find(".foprogress .bar")
+        });
+    });
+}
+
+//Write back the values that moved since the last tick, and nothing else
+function updateDynamicValues() {
+    var taskById = {};
+    latestTasks.forEach(function(task) {
+        taskById[task.ID] = task;
+    });
+
+    dynamicRows.forEach(function(row) {
+        var task = taskById[row.oprid];
+        if (task == undefined) {
+            return;
+        }
+        //A stacked row stands in for every file of the operation at once
+        var file = (row.fileIndex < 0) ? stackedPseudoFile(task) : (task.Files || [])[row.fileIndex];
+        if (file == undefined) {
+            return;
+        }
+
+        var state = file.Status || "pending";
+        var paused = operationIsPaused(task) && state == "ongoing";
+        setTextIfChanged(row.meta, describeFileState(task, file, state, paused));
+
+        var progress = (state == "completed") ? 100 : Math.max(0, Math.min(100, file.Progress || 0));
+        setBarWidthIfChanged(row.bar, progress);
+    });
+}
+
+/*
+    The one line shown in place of the list while the dialog is collapsed: the
+    progress of every operation of this user added up into a single bar.
+*/
+function updateCollapsedSummary(totalSize, doneSize) {
+    var progress = 0;
+    if (totalSize > 0) {
+        progress = doneSize / totalSize * 100;
+    } else if (latestTasks.length > 0) {
+        //Sizes are unknown for this batch, average the reported progress instead
+        latestTasks.forEach(function(task) {
+            progress += (task.Progress || 0);
+        });
+        progress = progress / latestTasks.length;
+    }
+    progress = Math.max(0, Math.min(100, progress));
+
+    /*
+        Colour the bar after the outcome, but only once there is nothing left
+        running: one finished operation, cancelled or failed, must not repaint
+        the bar of the transfers that are still going.
+    */
+    var stillRunning = pendingOperations.length > 0;
+    var anyError = false;
+    var anyCancelled = false;
+    latestTasks.forEach(function(task) {
+        if (!taskIsFinished(task)) {
+            stillRunning = true;
+        } else if (task.Status == "error") {
+            anyError = true;
+        } else if (task.Status == "cancelled") {
+            anyCancelled = true;
+        }
+    });
+
+    var barState = "";
+    if (latestTasks.length == 0 && pendingOperations.length == 0) {
+        //Nothing left in the list: there is no outstanding work to show
+        progress = 100;
+        barState = "done";
+    } else if (!stillRunning && latestTasks.length > 0) {
+        if (anyError) {
+            barState = "error";
+        } else if (anyCancelled) {
+            barState = "paused";
+        } else {
+            barState = "done";
+        }
+    }
+
+    setBarWidthIfChanged($("#summaryBar"), progress);
+    setClassIfChanged($("#summaryBar"), "bar " + barState);
+    setTextIfChanged($("#summaryPercent"), Math.round(progress) + "%");
+}
+
+function setClassIfChanged(element, className) {
+    if (element.length == 0 || element.attr("class") === className) {
+        return;
+    }
+    element.attr("class", className);
+}
+
+function setTextIfChanged(element, text) {
+    if (element.length == 0 || element.data("fotext") === text) {
+        return;
+    }
+    element.data("fotext", text);
+    element.text(text);
+}
+
+function setDisabledIfChanged(element, disabled) {
+    if (element.length == 0 || element.prop("disabled") === disabled) {
+        return;
+    }
+    element.prop("disabled", disabled);
+}
+
+function setBarWidthIfChanged(element, progress) {
+    if (element.length == 0) {
+        return;
+    }
+    //Rounded to whole percents: sub pixel updates are not worth a repaint
+    var rounded = Math.round(progress);
+    if (element.data("fowidth") === rounded) {
+        return;
+    }
+    element.data("fowidth", rounded);
+    element.css("width", rounded + "%");
+}
+
+/*
+    Grow and shrink the float window with the number of rows it has to show.
+
+    The wanted height is measured from the rows themselves, never from the
+    scroll box that holds them: measuring the box would feed the window height
+    back into the next measurement and walk the window down a few pixels on
+    every tick.
+*/
+function resizeToContent() {
+    if (collapsed) {
+        return;
+    }
+
+    var contentHeight = $(".foheader").outerHeight(true) + $(".fofooter").outerHeight(true) +
+        ($(".fosummary").is(":visible") ? $(".fosummary").outerHeight(true) : 0) +
+        parseFloat($("#dialogBody").css("padding-top")) +
+        parseFloat($("#dialogBody").css("padding-bottom"));
+    $("#dialogBody").children(":visible").each(function() {
+        contentHeight += $(this).outerHeight(true);
+    });
+    contentHeight = Math.ceil(contentHeight);
+
+    if (Math.abs(contentHeight - lastContentHeight) < 8) {
+        //The rows did not move, leave the window alone so a window the user
+        //resized by hand is not fought over on every tick
+        return;
+    }
+    lastContentHeight = contentHeight;
+
+    var wantedHeight = Math.max(200, Math.min(560, contentHeight + measureWindowChrome()));
+    lastWindowHeight = wantedHeight;
+    ao_module_setWindowSize(480, wantedHeight);
+}
+
+//How much taller the float window is than the page inside it (title bar and borders)
+function measureWindowChrome() {
+    if (lastWindowHeight > 0 && window.innerHeight > 0) {
+        var chrome = lastWindowHeight - window.innerHeight;
+        if (chrome >= 0 && chrome < 120) {
+            windowChromeHeight = chrome;
+        }
+    }
+    return windowChromeHeight;
+}
+
+function buildTitleText(ongoingCount) {
+    if (ongoingCount == 0) {
+        return applocale.getString("header/allDone", "All operations completed");
+    }
+    if (ongoingCount == 1) {
+        return applocale.getString("header/oneOperation", "1 operation in progress");
+    }
+    return applocale.getString("header/nOperations", "{n} operations in progress").replace("{n}", ongoingCount);
+}
+
+//An operation that is waiting for the user to pick an overwrite mode
+function renderPendingOperation(config) {
+    var html = '<div class="fooperation">';
+    html += '<div class="foopinfo">' + escapeHtml(describeOperation(config.opr, config.src.length, dirname(config.src[0]))) + '</div>';
+    html += '<div class="fodupask">';
+    html += '<span class="foduptext">' + escapeHtml(describeDuplication(config.duplicateCount)) + '</span>';
+    html += '<div class="fodupbtns">';
+    html += '<button class="fobtn outline" onclick="resolveDuplication(\'' + config.pendingId + '\', \'overwrite\');">' + escapeHtml(applocale.getString("dup/overwrite", "Overwrite")) + '</button>';
+    html += '<button class="fobtn outline" onclick="resolveDuplication(\'' + config.pendingId + '\', \'skip\');">' + escapeHtml(applocale.getString("dup/skip", "Skip")) + '</button>';
+    html += '<button class="fobtn primary" onclick="resolveDuplication(\'' + config.pendingId + '\', \'keep\');">' + escapeHtml(applocale.getString("dup/renameAndKeep", "Rename & Keep")) + '</button>';
+    html += '</div></div>';
+
+    if (config.src.length > STACKED_ROW_THRESHOLD) {
+        html += renderFileRow(null, {
+            Filename: describeFileCount(config.src.length),
+            Src: "",
+            Size: 0,
+            Done: 0,
+            Progress: 0,
+            Status: "pending",
+            Stacked: true
+        }, -1);
+    } else {
+        config.src.forEach(function(src, fileIndex) {
+            html += renderFileRow(null, {
+                Filename: basename(src),
+                Src: src,
+                Size: 0,
+                Done: 0,
+                Progress: 0,
+                Status: "pending"
+            }, fileIndex);
+        });
+    }
+
+    html += '</div>';
+    return html;
+}
+
+function renderOperation(task) {
+    var config = operationConfigs[task.ID];
+    var html = '<div class="fooperation" oprid="' + escapeHtml(task.ID) + '">';
+    html += '<div class="foopinfo">' + escapeHtml(describeOperation(task.Operation, (task.Files || []).length, task.Src));
+    if (config != undefined && config.duplicateCount > 0) {
+        //Remind the user that this operation was started on top of existing files
+        html += '<span class="foopnote">' + escapeHtml(describeDuplication(config.duplicateCount)) + '</span>';
+    }
+    if (task.Error) {
+        html += '<span class="foopnote" style="color: var(--fo-bar-error);">' + escapeHtml(applocale.getString("error/" + task.Error, task.Error)) + '</span>';
+    }
+    html += '</div>';
+
+    if (operationIsStacked(task)) {
+        //Too many files to draw one row each, show the pile as a single row
+        html += renderFileRow(task, stackedPseudoFile(task), -1);
+    } else {
+        (task.Files || []).forEach(function(file, fileIndex) {
+            html += renderFileRow(task, file, fileIndex);
+        });
+    }
+
+    html += '</div>';
+    return html;
+}
+
+function renderFileRow(task, file, fileIndex) {
+    var state = file.Status || "pending";
+    var paused = (task != null && operationIsPaused(task) && state == "ongoing");
+    var progress = Math.max(0, Math.min(100, file.Progress || 0));
+
+    var barClass = "";
+    if (state == "completed") {
+        barClass = " done";
+        progress = 100;
+    } else if (state == "error") {
+        barClass = " error";
+    } else if (state == "cancelled" || paused) {
+        barClass = " paused";
+    }
+
+    var badge = file.Stacked ?
+        renderStackedBadge(state) :
+        renderFileBadge(file.Filename, state, file.IsDir || isFolderPath(file.Src));
+
+    //A stacked row names the pile, so point at the file it is on right now instead
+    var nameHint = (file.Stacked && task != null && task.LatestFile) ? task.LatestFile : file.Filename;
+
+    var html = '<div class="forow"' + (task != null ? ' oprid="' + escapeHtml(task.ID) + '" fileindex="' + fileIndex + '"' : '') + '>';
+    html += '<div class="forowicon">' + badge + '</div>';
+    html += '<div class="forowmain">';
+    html += '<div class="forowname" title="' + escapeHtml(nameHint) + '">' + escapeHtml(file.Filename) + '</div>';
+    html += '<div class="forowmeta' + (state == "error" ? " error" : "") + '">' + escapeHtml(describeFileState(task, file, state, paused)) + '</div>';
+    html += '<div class="foprogress"><div class="bar' + barClass + '" style="width: ' + progress + '%;"></div></div>';
+    html += '</div>';
+
+    //Only rows that can still move carry the pause and cancel buttons
+    html += '<div class="forowctrl">';
+    if (task != null && taskIsFinished(task) && (task.Status == "cancelled" || task.Status == "error")) {
+        //A stopped operation stays in the list until the user dismisses it
+        html += '<button class="forowbtn cancel" title="' + escapeHtml(applocale.getString("button/remove", "Remove")) + '" onclick="removeOperation(\'' + escapeHtml(task.ID) + '\');">';
+        html += '<i class="times icon"></i></button>';
+    } else if (task != null && !taskIsFinished(task) && state != "completed" && state != "error") {
+        var pauseIcon = paused ? "play" : "pause";
+        var pauseTitle = paused ? applocale.getString("button/resume", "Resume") : applocale.getString("button/pause", "Pause");
+        html += '<button class="forowbtn" title="' + escapeHtml(pauseTitle) + '" onclick="toggleOperationPause(\'' + escapeHtml(task.ID) + '\', ' + (paused ? "true" : "false") + ');">';
+        html += '<i class="' + pauseIcon + ' icon"></i></button>';
+        html += '<button class="forowbtn cancel" title="' + escapeHtml(applocale.getString("button/cancel", "Cancel")) + '" onclick="cancelOperation(\'' + escapeHtml(task.ID) + '\');">';
+        html += '<i class="times icon"></i></button>';
+    }
+    html += '</div>';
+
+    html += '</div>';
+    return html;
+}
+
+/*
+    An operation over a long list of files is drawn as one stacked row rather
+    than one row each. A hundred rows is a hundred badges, progress bars and
+    buttons to build and repaint, which is enough to make a low powered device
+    stutter for a listing nobody can read at that length anyway.
+*/
+function operationIsStacked(task) {
+    return (task.Files || []).length > STACKED_ROW_THRESHOLD;
+}
+
+// The single file record a stacked row is drawn from, made of the whole operation
+function stackedPseudoFile(task) {
+    var files = task.Files || [];
+    var state = "ongoing";
+    if (task.Status == "completed" || task.Status == "error" || task.Status == "cancelled") {
+        state = task.Status;
+    }
+
+    return {
+        Filename: describeFileCount(files.length),
+        Src: "",
+        Size: task.TotalSize || 0,
+        Done: task.DoneSize || 0,
+        Progress: task.Progress || 0,
+        Status: state,
+        Error: task.Error || "",
+        Stacked: true
+    };
+}
+
+function describeFileCount(fileCount) {
+    if (fileCount == 1) {
+        return applocale.getString("stack/oneFile", "1 file");
+    }
+    return applocale.getString("stack/files", "{n} files").replace("{n}", fileCount);
+}
+
+function describeOperation(opr, fileCount, src) {
+    var text;
+    switch (opr) {
+        case "move":
+            text = applocale.getString("op/moving", "Moving {n} file(s)");
+            break;
+        case "copy":
+            text = applocale.getString("op/copying", "Copying {n} file(s)");
+            break;
+        case "zip":
+            text = applocale.getString("op/zipping", "Compressing {n} file(s)");
+            break;
+        case "unzip":
+        case "unzipAndOpen":
+            text = applocale.getString("op/unzipping", "Extracting {n} file(s)");
+            break;
+        default:
+            text = applocale.getString("op/processing", "Processing {n} file(s)");
+    }
+
+    text = text.replace("{n}", fileCount);
+    if (src) {
+        text += " " + applocale.getString("op/source", "· Source: {p}").replace("{p}", centerTruncate(src, 34));
+    }
+    return text;
+}
+
+function describeDuplication(duplicateCount) {
+    if (duplicateCount == 1) {
+        return applocale.getString("op/oneDuplicate", "1 file with the same name at the destination");
+    }
+    return applocale.getString("op/nDuplicates", "{n} files with the same name at the destination").replace("{n}", duplicateCount);
+}
+
+function describeFileState(task, file, state, paused) {
+    if (state == "completed") {
+        return applocale.getString("row/completed", "Completed");
+    }
+    if (state == "error") {
+        return applocale.getString("error/" + file.Error, file.Error || applocale.getString("row/failed", "Failed"));
+    }
+    if (state == "cancelled") {
+        return applocale.getString("row/cancelled", "Cancelled");
+    }
+    if (state == "pending") {
+        return applocale.getString("row/waiting", "Waiting");
+    }
+
+    //Ongoing: show the transferred size and the estimated remaining time
+    var meta = "";
+    if (file.Size > 0) {
+        meta = formatBytes(file.Done) + " / " + formatBytes(file.Size);
+    } else {
+        meta = Math.round(file.Progress || 0) + "%";
+    }
+
+    if (paused) {
+        return meta + " · " + applocale.getString("row/paused", "Paused");
+    }
+
+    if (task != null) {
+        var remainingSeconds = getRemainingSeconds(task, (task.TotalSize || 0) - (task.DoneSize || 0));
+        if (remainingSeconds > 0) {
+            meta += " · " + applocale.getString("row/remaining", "{t} remaining").replace("{t}", formatDuration(remainingSeconds));
+        }
+    }
+    return meta;
+}
+
+/* ---------------------------------------------------------------
+    Controls
+--------------------------------------------------------------- */
+
+window.toggleOperationPause = function(oprid, currentlyPaused) {
+    //Flip the button straight away instead of waiting for the next status tick
+    pausedOverride[oprid] = currentlyPaused ? FSOPR_CONTINUE : FSOPR_PAUSE;
+    sendControl(currentlyPaused ? "continue" : "pause", oprid);
+    render();
+}
+
+window.cancelOperation = function(oprid) {
+    delete pausedOverride[oprid];
+    sendControl("cancel", oprid);
+}
+
+//Dismiss a stopped operation from the listing
+window.removeOperation = function(oprid) {
+    delete pausedOverride[oprid];
+    delete rateSamples[oprid];
+    latestTasks = latestTasks.filter(function(task) {
+        return task.ID != oprid;
+    });
+    sendControl("remove", oprid);
+    render();
+}
+
+//The control signal of an operation, preferring the state the user just asked for
+function operationIsPaused(task) {
+    var override = pausedOverride[task.ID];
+    if (override !== undefined) {
+        return override == FSOPR_PAUSE;
+    }
+    return task.FileOperationSignal == FSOPR_PAUSE;
+}
+
+//Drop the local pause states the backend has caught up with
+function clearConfirmedPauseOverrides() {
+    latestTasks.forEach(function(task) {
+        if (pausedOverride[task.ID] !== undefined &&
+            (pausedOverride[task.ID] == task.FileOperationSignal || taskIsFinished(task))) {
+            delete pausedOverride[task.ID];
+        }
+    });
+}
+
+window.clearCompleted = function() {
+    //Drop the client side only records straight away
+    latestTasks = latestTasks.filter(function(task) {
+        return !(task.LocalOnly === true);
+    });
+    sendControl("clear");
+    render();
+}
+
+window.cancelAll = function() {
+    latestTasks.forEach(function(task) {
+        if (!taskIsFinished(task)) {
+            delete pausedOverride[task.ID];
+            sendControl("cancel", task.ID);
+        }
+    });
+    //Drop the operations that have not been started yet
+    pendingOperations = [];
+    render();
+}
+
+function sendControl(command, oprid) {
+    if (statusSocket != null && statusSocket.readyState == 1) {
+        statusSocket.send(JSON.stringify({ cmd: command, oprid: oprid || "" }));
+        return;
+    }
+
+    //No usable socket. Use the control endpoint instead.
+    $.ajax({
+        url: "../../system/file_system/ongoing",
+        method: "POST",
+        data: { oprid: oprid || "", flag: command },
+        success: function(data) {
+            if (data.error != undefined) {
+                console.log("[File Operation] " + data.error);
+            }
+            requestStatusUpdate();
+        }
+    });
+}
+
+window.toggleCollapse = function() {
+    collapsed = !collapsed;
+    $("#dialog").toggleClass("collapsed", collapsed);
+    $("#collapseBtn").find("i").attr("class", (collapsed ? "chevron up icon" : "chevron down icon"));
+    $("#collapseBtn").attr("title", collapsed ?
+        applocale.getString("button/expand", "Expand") :
+        applocale.getString("button/collapse", "Collapse"));
+
+    if (collapsed) {
+        lastWindowHeight = Math.ceil($(".foheader").outerHeight(true) + $(".fosummary").outerHeight(true) +
+            $(".fofooter").outerHeight(true) + windowChromeHeight);
+        ao_module_setWindowSize(480, lastWindowHeight);
+    } else {
+        lastContentHeight = 0;
+        resizeToContent();
+    }
+}
+
+window.closeDialog = function() {
+    //The operations keep running on the server, the desktop background task
+    //panel and this dialog will pick them up again when reopened
+    ao_module_close();
+    setTimeout(function() {
+        //If ao_module_close is not working for some reason
+        open(location, "_self").close();
+    }, 500);
+}
+
+/* ---------------------------------------------------------------
+    Completion handling
+--------------------------------------------------------------- */
+
+function handleTaskCompletion(task) {
+    if (!taskIsFinished(task) || completedHandled[task.ID]) {
+        return;
+    }
+    completedHandled[task.ID] = true;
+
+    var config = operationConfigs[task.ID];
+    if (config == undefined) {
+        //Started by another window. Still refresh the desktop if it is affected.
+        refreshDesktopIfAffected(task.Src, task.Dest);
+        return;
+    }
+
+    if (task.Status != "completed") {
+        //Failed or cancelled operations do not fire their success callback
+        return;
+    }
+
+    //Fire the callback of the window that requested this operation
+    try {
+        if (config.callbackWindowID == "desktop" && config.callbackFunction) {
+            parent.eval(config.callbackFunction);
+        } else if (ao_module_virtualDesktop && config.callbackWindowID !== undefined && config.callbackFunction !== undefined) {
+            var callbackWindowObject = parent.getFloatWindowByID(config.callbackWindowID);
+            var windowObject = $(callbackWindowObject).find("iframe")[0];
+            if (windowObject != undefined && windowObject != null) {
+                windowObject.contentWindow.eval(config.callbackFunction);
+            }
+        }
+    } catch (ex) {
+        console.log("[File Operation] Callback failed", ex);
+    }
+
+    refreshDesktopIfAffected(config.src[0], config.dest);
+
+    if (config.opr == "unzipAndOpen") {
+        ao_module_openPath(config.dest);
+    }
+}
+
+function refreshDesktopIfAffected(src, dest) {
+    if (!ao_module_virtualDesktop) {
+        return;
+    }
+    if (pathIsOnDesktop(dest) || pathIsOnDesktop(src)) {
+        try {
+            parent.refresh(undefined, true);
+        } catch (ex) {
+            console.log("[File Operation] Desktop refresh failed", ex);
+        }
+    }
+}
+
+function pathIsOnDesktop(path) {
+    if (typeof path != "string") {
+        return false;
+    }
+    var filteredDest = path;
+    if (filteredDest.substr(filteredDest.length - 1) == "/") {
+        filteredDest = filteredDest.substr(0, filteredDest.length - 1);
+    }
+    var dirChunk = filteredDest.split("/");
+    if (dirChunk.length == 2 || dirChunk.length == 3) {
+        if (dirChunk[0].toLowerCase() == "user:" && dirChunk[1].toLowerCase() == "desktop") {
+            return true;
+        }
+    }
+    return false;
+}
+
+/* ---------------------------------------------------------------
+    Auto close
+--------------------------------------------------------------- */
+
+//Close the dialog shortly after everything finished without problems, so a
+//single quick copy does not leave a window behind on the desktop
+function scheduleAutoCloseIfDone(ongoingCount) {
+    if (!everHadOperation || ongoingCount > 0) {
+        //Something is still running
+        cancelAutoClose();
+        return;
+    }
+
+    /*
+        Nothing is running any more. The dialog closes itself when there is
+        nothing left worth reading: every operation succeeded, or the user has
+        already dismissed the ones that did not. An operation that failed or was
+        stopped stays on screen until the user removes it or clears the list.
+    */
+    var needsAttention = latestTasks.some(function(task) {
+        return task.Status != "completed";
+    });
+
+    if (needsAttention || userIsInteracting) {
+        cancelAutoClose();
+        return;
+    }
+
+    if (autoCloseTimer == null) {
+        autoCloseTimer = setTimeout(function() {
+            autoCloseTimer = null;
+            if (!userIsInteracting) {
+                closeDialog();
+            }
+        }, AUTOCLOSE_DELAY);
+    }
+}
+
+function cancelAutoClose() {
+    if (autoCloseTimer != null) {
+        clearTimeout(autoCloseTimer);
+        autoCloseTimer = null;
+    }
+}
+
+/* ---------------------------------------------------------------
+    Helpers
+--------------------------------------------------------------- */
+
+function taskIsFinished(task) {
+    return task.Status != "ongoing" && task.Status != "pending";
+}
+
+function basename(path) {
+    return String(path || "").replace(/\/+$/, "").split("/").pop();
+}
+
+function dirname(path) {
+    var chunks = String(path || "").replace(/\/+$/, "").split("/");
+    chunks.pop();
+    return chunks.join("/") + "/";
+}
+
+function isFolderPath(path) {
+    return typeof path == "string" && path.length > 0 && path.substr(path.length - 1) == "/";
+}
+
+function formatBytes(bytes) {
+    if (typeof ao_module_utils != "undefined" && ao_module_utils.formatBytes) {
+        return ao_module_utils.formatBytes(bytes);
+    }
+    if (!bytes || bytes < 0) {
+        return "0 B";
+    }
+    var units = ["B", "KB", "MB", "GB", "TB"];
+    var i = Math.floor(Math.log(bytes) / Math.log(1024));
+    if (i >= units.length) {
+        i = units.length - 1;
+    }
+    return (bytes / Math.pow(1024, i)).toFixed(2) + " " + units[i];
+}
+
+function formatDuration(seconds) {
+    seconds = Math.ceil(seconds);
+    if (seconds >= 3600) {
+        var hours = Math.round(seconds / 3600);
+        return applocale.getString("time/hours", "{n} hour(s)").replace("{n}", hours);
+    }
+    if (seconds >= 60) {
+        var minutes = Math.round(seconds / 60);
+        return applocale.getString("time/minutes", "{n} minute(s)").replace("{n}", minutes);
+    }
+    return applocale.getString("time/seconds", "{n} second(s)").replace("{n}", seconds);
+}
+
+function centerTruncate(fullStr, strLen, separator) {
+    fullStr = String(fullStr || "");
+    if (fullStr.length <= strLen) {
+        return fullStr;
+    }
+    separator = separator || "...";
+    var charsToShow = strLen - separator.length;
+    var frontChars = Math.ceil(charsToShow / 2);
+    var backChars = Math.floor(charsToShow / 2);
+    return fullStr.substr(0, frontChars) + separator + fullStr.substr(fullStr.length - backChars);
+}
+
+function escapeHtml(text) {
+    return $("<div>").text(text == undefined ? "" : text).html();
+}

+ 131 - 0
src/web/SystemAO/file_system/js/file_operation/icons.js

@@ -0,0 +1,131 @@
+/*
+    icons.js
+
+    Inline SVG badges for the file rows of the file operation dialog.
+    Drawn locally instead of pulled from an icon font so the badge can carry
+    the file type colour, see file_operation.html.
+*/
+
+var fileOperationIconCategories = {
+    video: ["mp4", "mkv", "avi", "mov", "webm", "flv", "wmv", "m4v", "mpg", "mpeg", "3gp", "ts"],
+    image: ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg", "ico", "tif", "tiff", "heic", "psd"],
+    audio: ["mp3", "wav", "flac", "aac", "ogg", "m4a", "wma", "opus", "mid", "midi"],
+    archive: ["zip", "7z", "rar", "tar", "gz", "bz2", "xz", "iso"],
+    document: ["txt", "md", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "ods", "odp", "rtf", "csv"],
+    code: ["js", "ts", "html", "css", "json", "xml", "go", "py", "java", "c", "cpp", "h", "php", "sh", "yaml", "yml"]
+};
+
+var fileOperationIconColors = {
+    video: "#2f80ed",
+    image: "#8e5bd0",
+    audio: "#e07b39",
+    archive: "#c9a227",
+    document: "#4a90a4",
+    code: "#3aa06a",
+    folder: "#e0a92b",
+    file: "#7a8593"
+};
+
+/*
+    getFileCategory(filename, isFolder)
+
+    Resolve a filename into one of the categories above. Unknown extensions
+    fall back to the generic "file" category.
+*/
+function getFileCategory(filename, isFolder) {
+    if (isFolder) {
+        return "folder";
+    }
+    var ext = String(filename || "").split(".").pop().toLowerCase();
+    for (var category in fileOperationIconCategories) {
+        if (fileOperationIconCategories[category].indexOf(ext) != -1) {
+            return category;
+        }
+    }
+    return "file";
+}
+
+/*
+    renderStackedBadge(state)
+
+    The badge of a row that stands in for a whole pile of files at once, drawn
+    as a few sheets stacked on top of each other. Finished operations fall back
+    to the same result badges a single file gets, see renderFileBadge.
+*/
+function renderStackedBadge(state) {
+    if (state == "completed" || state == "error" || state == "cancelled") {
+        return renderFileBadge("", state, false);
+    }
+
+    var color = fileOperationIconColors.file;
+    return '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
+        '<rect x="6" y="2" width="22" height="24" rx="4" fill="' + color + '" opacity="0.35"></rect>' +
+        '<rect x="4" y="4" width="22" height="24" rx="4" fill="' + color + '" opacity="0.6"></rect>' +
+        '<rect x="2" y="6" width="22" height="24" rx="4" fill="' + color + '"></rect>' +
+        '<path d="M7 13 h12 M7 17.5 h12 M7 22 h7" fill="none" stroke="#ffffff" stroke-width="1.8" stroke-linecap="round"></path>' +
+        '</svg>';
+}
+
+/*
+    renderFileBadge(filename, state, isFolder)
+
+    Return the SVG markup of the badge shown at the left of a file row.
+    state is one of: ongoing / pending / completed / error / cancelled.
+*/
+function renderFileBadge(filename, state, isFolder) {
+    if (state == "completed") {
+        return '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
+            '<circle cx="16" cy="16" r="13" fill="#21ba45"></circle>' +
+            '<path d="M10 16.4 L14.3 20.6 L22 12.6" fill="none" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"></path>' +
+            '</svg>';
+    }
+
+    if (state == "error") {
+        return '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
+            '<circle cx="16" cy="16" r="13" fill="#db2828"></circle>' +
+            '<path d="M11.5 11.5 L20.5 20.5 M20.5 11.5 L11.5 20.5" fill="none" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round"></path>' +
+            '</svg>';
+    }
+
+    if (state == "cancelled") {
+        return '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
+            '<circle cx="16" cy="16" r="12.2" fill="none" stroke="#8b97a5" stroke-width="2.2"></circle>' +
+            '<path d="M11 11 L21 21" fill="none" stroke="#8b97a5" stroke-width="2.2" stroke-linecap="round"></path>' +
+            '</svg>';
+    }
+
+    var category = getFileCategory(filename, isFolder);
+    var color = fileOperationIconColors[category];
+    var glyph = "";
+    switch (category) {
+        case "video":
+            glyph = '<path d="M13 11.4 L21.4 16 L13 20.6 Z" fill="#ffffff"></path>';
+            break;
+        case "image":
+            glyph = '<circle cx="12.4" cy="12.6" r="1.9" fill="#ffffff"></circle>' +
+                '<path d="M9 21.4 L14.2 15.6 L17.4 19.1 L19.6 16.7 L23 21.4 Z" fill="#ffffff"></path>';
+            break;
+        case "audio":
+            glyph = '<path d="M19.8 9.4 L14 11.1 V19 a2.5 2.5 0 1 0 1.7 2.3 V14 l4.1-1.2 Z" fill="#ffffff"></path>';
+            break;
+        case "archive":
+            glyph = '<path d="M9.5 12.6 h13 v9.4 h-13 Z" fill="#ffffff"></path>' +
+                '<path d="M9.5 12.6 L11.6 9.6 h8.8 l2.1 3" fill="none" stroke="#ffffff" stroke-width="1.8" stroke-linejoin="round"></path>' +
+                '<path d="M14.4 16.2 h3.2" fill="none" stroke="' + color + '" stroke-width="1.8" stroke-linecap="round"></path>';
+            break;
+        case "folder":
+            glyph = '<path d="M9 11.6 h4.6 l1.5 1.9 h8 v9.1 h-14 Z" fill="#ffffff"></path>';
+            break;
+        case "code":
+            glyph = '<path d="M13.6 12.4 L9.6 16 L13.6 19.6 M18.4 12.4 L22.4 16 L18.4 19.6" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>';
+            break;
+        default:
+            glyph = '<path d="M11.4 9.4 h6.6 l4 4 v9.2 h-10.6 Z" fill="#ffffff"></path>' +
+                '<path d="M18 9.4 v4 h4" fill="none" stroke="' + color + '" stroke-width="1.4" stroke-linejoin="round"></path>';
+    }
+
+    return '<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
+        '<rect x="2" y="2" width="28" height="28" rx="7" fill="' + color + '"></rect>' +
+        glyph +
+        '</svg>';
+}

+ 1 - 19
src/web/SystemAO/file_system/zip_extractor.html

@@ -33,29 +33,11 @@
             });
 
             //Unzip and open them to tmp:/
-            var oprConfig = {
+            ao_module_startFileOperation({
                 opr: "unzipAndOpen",
                 src: targetFilePaths,
                 dest: "tmp:/tmp_" + Date.now() + "/",
                 overwriteMode: "overwrite",
-            }
-
-            //Render the dialog title name
-            var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-            var title = "Unzipping " + targetFilePaths.length;
-            if (targetFilePaths.length > 1){
-                title += " files";
-            }else{
-                title += " file";
-            }
-
-            //Open the operation dialog in new floatWindow
-            ao_module_newfw({
-                url: "SystemAO/file_system/file_operation.html#" + configHash,
-                width: 400,
-                height: 220,
-                appicon: "SystemAO/file_system/img/zip_extractor.png",
-                title: title
             });
 
             //CLose this window

+ 15 - 9
src/web/SystemAO/locale/desktop.json

@@ -106,6 +106,7 @@
                 "account/switch/signoutAll": "登出其他已儲存的帳戶",
                 "upload/message/uploading": "上載中…",
                 "upload/message/failed": "上載失敗",
+                "fileOperation/title": "檔案操作",
                 "": ""
             },
             "placeholder": {
@@ -214,9 +215,10 @@
                 "account/switch/signoutAll": "登出其他已儲存的帳戶",
                 "upload/message/uploading": "上載中…",
                 "upload/message/failed": "上載失敗",
-                "": "",
                 "error/connlost/readonly": "[唯讀] 帳戶",
-                "error/connlost/readonl/infoy": "由於此帳戶被鎖定在唯讀狀態,因此你無法在桌面進行任何檔案操作。"
+                "error/connlost/readonl/infoy": "由於此帳戶被鎖定在唯讀狀態,因此你無法在桌面進行任何檔案操作。",
+                "fileOperation/title": "檔案操作",
+                "": ""
             },
             "placeholder": {
                 "Search": "搜尋"
@@ -324,9 +326,10 @@
                 "account/switch/signoutAll": "登出其他已储存的帐户",
                 "upload/message/uploading": "上传中…",
                 "upload/message/failed": "上传失败",
-                "": "",
                 "error/connlost/readonly": "[只读] 账户",
-                "error/connlost/readonl/infoy": "由于此账户被锁定在只读状态,因此您无法在桌面进行任何文件操作。"
+                "error/connlost/readonl/infoy": "由于此账户被锁定在只读状态,因此您无法在桌面进行任何文件操作。",
+                "fileOperation/title": "文件操作",
+                "": ""
             },
             "placeholder": {
                 "Search": "搜索"
@@ -436,8 +439,9 @@
                 "account/switch/addAccount": "Add another account",
                 "account/switch/signoutAll": "Sign-out all accounts",
                 "upload/message/uploading": "Uploading...",
-                "": "",
-                "upload/message/failed": "Upload Failed"
+                "upload/message/failed": "Upload Failed",
+                "fileOperation/title": "File Operation",
+                "": ""
             },
             "placeholder": {
                 "Search": "Search"
@@ -547,8 +551,9 @@
                 "account/switch/addAccount": "別のアカウントを追加",
                 "account/switch/signoutAll": "すべてのアカウントからサインアウト",
                 "upload/message/uploading": "アップロード中...",
-                "": "",
-                "upload/message/failed": "アップロード失敗"
+                "upload/message/failed": "アップロード失敗",
+                "fileOperation/title": "ファイル操作",
+                "": ""
             },
             "placeholder": {
                 "Search": "検索"
@@ -659,6 +664,7 @@
                 "account/switch/signoutAll": "저장된 다른 모든 계정 로그아웃",
                 "upload/message/uploading": "업로드 중...",
                 "upload/message/failed": "업로드 실패",
+                "fileOperation/title": "파일 작업",
                 "": ""
             },
             "placeholder": {
@@ -666,4 +672,4 @@
             }
         }
     }
-}
+}

+ 48 - 6
src/web/SystemAO/locale/file_explorer.json

@@ -252,7 +252,14 @@
                 "upload/resume": "繼續",
                 "upload/cancel": "取消",
                 "upload/retry": "重試",
-                "upload/pauseExpired": "上傳已取消:暫停時間過長"
+                "upload/pauseExpired": "上傳已取消:暫停時間過長",
+                "sidebar/properties/permOwner": "擁有者",
+                "sidebar/properties/permGroup": "群組",
+                "sidebar/properties/permOthers": "其他",
+                "sidebar/properties/permRead": "讀取",
+                "sidebar/properties/permWrite": "寫入",
+                "sidebar/properties/permExec": "執行",
+                "fileopr/Hidden Files": "顯示隱藏檔案"
             },
             "titles": {
                 "Back": "上一頁",
@@ -550,7 +557,14 @@
                 "upload/resume": "繼續",
                 "upload/cancel": "取消",
                 "upload/retry": "重試",
-                "upload/pauseExpired": "上傳已取消:暫停時間過長"
+                "upload/pauseExpired": "上傳已取消:暫停時間過長",
+                "sidebar/properties/permOwner": "擁有者",
+                "sidebar/properties/permGroup": "群組",
+                "sidebar/properties/permOthers": "其他",
+                "sidebar/properties/permRead": "讀取",
+                "sidebar/properties/permWrite": "寫入",
+                "sidebar/properties/permExec": "執行",
+                "fileopr/Hidden Files": "顯示隱藏檔案"
             },
             "titles": {
                 "Back": "上一頁",
@@ -849,7 +863,14 @@
                 "upload/resume": "继续",
                 "upload/cancel": "取消",
                 "upload/retry": "重试",
-                "upload/pauseExpired": "上传已取消:暂停时间过长"
+                "upload/pauseExpired": "上传已取消:暂停时间过长",
+                "sidebar/properties/permOwner": "所有者",
+                "sidebar/properties/permGroup": "群组",
+                "sidebar/properties/permOthers": "其他",
+                "sidebar/properties/permRead": "读取",
+                "sidebar/properties/permWrite": "写入",
+                "sidebar/properties/permExec": "执行",
+                "fileopr/Hidden Files": "显示隐藏文件"
             },
             "titles": {
                 "Back": "上一页",
@@ -1149,7 +1170,14 @@
                 "upload/resume": "Resume",
                 "upload/cancel": "Cancel",
                 "upload/retry": "Retry",
-                "upload/pauseExpired": "Upload cancelled: paused for too long"
+                "upload/pauseExpired": "Upload cancelled: paused for too long",
+                "sidebar/properties/permOwner": "Owner",
+                "sidebar/properties/permGroup": "Group",
+                "sidebar/properties/permOthers": "Others",
+                "sidebar/properties/permRead": "Read",
+                "sidebar/properties/permWrite": "Write",
+                "sidebar/properties/permExec": "Exec",
+                "fileopr/Hidden Files": "Show Hidden Files"
             },
             "titles": {
                 "Back": "Back",
@@ -1449,7 +1477,14 @@
                 "upload/resume": "再開",
                 "upload/cancel": "キャンセル",
                 "upload/retry": "再試行",
-                "upload/pauseExpired": "アップロードを中止しました:一時停止が長すぎます"
+                "upload/pauseExpired": "アップロードを中止しました:一時停止が長すぎます",
+                "sidebar/properties/permOwner": "所有者",
+                "sidebar/properties/permGroup": "グループ",
+                "sidebar/properties/permOthers": "その他",
+                "sidebar/properties/permRead": "読取",
+                "sidebar/properties/permWrite": "書込",
+                "sidebar/properties/permExec": "実行",
+                "fileopr/Hidden Files": "隠しファイルを表示"
             },
             "titles": {
                 "Back": "戻る",
@@ -1751,7 +1786,14 @@
                 "upload/resume": "다시 시작",
                 "upload/cancel": "취소",
                 "upload/retry": "다시 시도",
-                "upload/pauseExpired": "업로드 취소됨: 너무 오래 일시중지되었습니다"
+                "upload/pauseExpired": "업로드 취소됨: 너무 오래 일시중지되었습니다",
+                "sidebar/properties/permOwner": "소유자",
+                "sidebar/properties/permGroup": "그룹",
+                "sidebar/properties/permOthers": "기타",
+                "sidebar/properties/permRead": "읽기",
+                "sidebar/properties/permWrite": "쓰기",
+                "sidebar/properties/permExec": "실행",
+                "fileopr/Hidden Files": "숨김 파일 표시"
             },
             "titles": {
                 "Back": "뒤로",

+ 191 - 5
src/web/SystemAO/locale/file_operation.json

@@ -36,6 +36,37 @@
                 "error/File already exists": "檔案已經存在",
                 "error/This directory is Read Only": "此資料夾是唯讀檔案",
                 "error/Operation cancelled by user": "使用者已取消此檔案操作",
+                "header/oneOperation": "1 個操作進行中",
+                "header/nOperations": "{n} 個操作進行中",
+                "header/allDone": "所有操作已完成",
+                "empty/noOperation": "沒有進行中的檔案操作",
+                "op/moving": "正在移動 {n} 個檔案",
+                "op/copying": "正在複製 {n} 個檔案",
+                "op/zipping": "正在壓縮 {n} 個檔案",
+                "op/unzipping": "正在解壓 {n} 個檔案",
+                "op/processing": "正在處理 {n} 個檔案",
+                "op/source": "· 來源:{p}",
+                "op/oneDuplicate": "目的地有 1 個相同名稱的檔案",
+                "op/nDuplicates": "目的地有 {n} 個相同名稱的檔案",
+                "row/completed": "已完成",
+                "row/cancelled": "已取消",
+                "row/failed": "失敗",
+                "row/waiting": "等待中",
+                "row/paused": "已暫停",
+                "row/remaining": "剩餘 {t}",
+                "time/hours": "{n} 小時",
+                "time/minutes": "{n} 分鐘",
+                "time/seconds": "{n} 秒",
+                "footer/total": "總計:{done} / {total}",
+                "footer/clearCompleted": "清除已完成項目",
+                "footer/cancelAll": "全部取消",
+                "error/Unable to start file operation": "無法開始檔案操作",
+                "error/Access Denied: No Write Permission": "存取被拒:沒有寫入權限",
+                "button/collapse": "收合",
+                "button/expand": "展開",
+                "button/remove": "移除",
+                "stack/oneFile": "1 個檔案",
+                "stack/files": "{n} 個檔案",
                 "": ""
             },
             "titles": {},
@@ -72,10 +103,41 @@
                 "error/File already exists": "檔案已經存在",
                 "error/This directory is Read Only": "此資料夾是唯讀檔案",
                 "error/Operation cancelled by user": "使用者已取消此檔案操作",
-                "": "",
                 "button/pause": "暫停",
                 "button/cancel": "取消",
-                "button/resume": "繼續"
+                "button/resume": "繼續",
+                "header/oneOperation": "1 個操作進行中",
+                "header/nOperations": "{n} 個操作進行中",
+                "header/allDone": "所有操作已完成",
+                "empty/noOperation": "沒有進行中的檔案操作",
+                "op/moving": "正在移動 {n} 個檔案",
+                "op/copying": "正在複製 {n} 個檔案",
+                "op/zipping": "正在壓縮 {n} 個檔案",
+                "op/unzipping": "正在解壓 {n} 個檔案",
+                "op/processing": "正在處理 {n} 個檔案",
+                "op/source": "· 來源:{p}",
+                "op/oneDuplicate": "目的地有 1 個相同名稱的檔案",
+                "op/nDuplicates": "目的地有 {n} 個相同名稱的檔案",
+                "row/completed": "已完成",
+                "row/cancelled": "已取消",
+                "row/failed": "失敗",
+                "row/waiting": "等待中",
+                "row/paused": "已暫停",
+                "row/remaining": "剩餘 {t}",
+                "time/hours": "{n} 小時",
+                "time/minutes": "{n} 分鐘",
+                "time/seconds": "{n} 秒",
+                "footer/total": "總計:{done} / {total}",
+                "footer/clearCompleted": "清除已完成項目",
+                "footer/cancelAll": "全部取消",
+                "error/Unable to start file operation": "無法開始檔案操作",
+                "error/Access Denied: No Write Permission": "存取被拒:沒有寫入權限",
+                "button/collapse": "收合",
+                "button/expand": "展開",
+                "button/remove": "移除",
+                "stack/oneFile": "1 個檔案",
+                "stack/files": "{n} 個檔案",
+                "": ""
             },
             "titles": {},
             "placeholder": {}
@@ -111,10 +173,41 @@
                 "error/File already exists": "文件已经存在",
                 "error/This directory is Read Only": "此文件夹只读",
                 "error/Operation cancelled by user": "使用者已取消此文件操作",
-                "": "",
                 "button/pause": "暂停",
                 "button/cancel": "取消",
-                "button/resume": "继续"
+                "button/resume": "继续",
+                "header/oneOperation": "1 个操作进行中",
+                "header/nOperations": "{n} 个操作进行中",
+                "header/allDone": "所有操作已完成",
+                "empty/noOperation": "没有进行中的文件操作",
+                "op/moving": "正在移动 {n} 个文件",
+                "op/copying": "正在复制 {n} 个文件",
+                "op/zipping": "正在压缩 {n} 个文件",
+                "op/unzipping": "正在解压 {n} 个文件",
+                "op/processing": "正在处理 {n} 个文件",
+                "op/source": "· 来源:{p}",
+                "op/oneDuplicate": "目标位置有 1 个相同名称的文件",
+                "op/nDuplicates": "目标位置有 {n} 个相同名称的文件",
+                "row/completed": "已完成",
+                "row/cancelled": "已取消",
+                "row/failed": "失败",
+                "row/waiting": "等待中",
+                "row/paused": "已暂停",
+                "row/remaining": "剩余 {t}",
+                "time/hours": "{n} 小时",
+                "time/minutes": "{n} 分钟",
+                "time/seconds": "{n} 秒",
+                "footer/total": "总计:{done} / {total}",
+                "footer/clearCompleted": "清除已完成项目",
+                "footer/cancelAll": "全部取消",
+                "error/Unable to start file operation": "无法开始文件操作",
+                "error/Access Denied: No Write Permission": "访问被拒:没有写入权限",
+                "button/collapse": "收起",
+                "button/expand": "展开",
+                "button/remove": "移除",
+                "stack/oneFile": "1 个文件",
+                "stack/files": "{n} 个文件",
+                "": ""
             },
             "titles": {},
             "placeholder": {}
@@ -153,6 +246,37 @@
                 "error/File already exists": "File already exists",
                 "error/This directory is Read Only": "This directory is Read-Only",
                 "error/Operation cancelled by user": "Operation cancelled by user",
+                "header/oneOperation": "1 operation in progress",
+                "header/nOperations": "{n} operations in progress",
+                "header/allDone": "All operations completed",
+                "empty/noOperation": "No file operation running",
+                "op/moving": "Moving {n} file(s)",
+                "op/copying": "Copying {n} file(s)",
+                "op/zipping": "Compressing {n} file(s)",
+                "op/unzipping": "Extracting {n} file(s)",
+                "op/processing": "Processing {n} file(s)",
+                "op/source": "· Source: {p}",
+                "op/oneDuplicate": "1 file with the same name at the destination",
+                "op/nDuplicates": "{n} files with the same name at the destination",
+                "row/completed": "Completed",
+                "row/cancelled": "Cancelled",
+                "row/failed": "Failed",
+                "row/waiting": "Waiting",
+                "row/paused": "Paused",
+                "row/remaining": "{t} remaining",
+                "time/hours": "{n} hour(s)",
+                "time/minutes": "{n} minute(s)",
+                "time/seconds": "{n} second(s)",
+                "footer/total": "Total: {done} / {total}",
+                "footer/clearCompleted": "Clear completed",
+                "footer/cancelAll": "Cancel all",
+                "error/Unable to start file operation": "Unable to start file operation",
+                "error/Access Denied: No Write Permission": "Access Denied: No Write Permission",
+                "button/collapse": "Collapse",
+                "button/expand": "Expand",
+                "button/remove": "Remove",
+                "stack/oneFile": "1 file",
+                "stack/files": "{n} files",
                 "": ""
             },
             "titles": {},
@@ -192,6 +316,37 @@
                 "error/File already exists": "ファイルは既に存在しています",
                 "error/This directory is Read Only": "このディレクトリは読み取り専用です",
                 "error/Operation cancelled by user": "ユーザーによって操作がキャンセルされました",
+                "header/oneOperation": "1 件の操作を実行中",
+                "header/nOperations": "{n} 件の操作を実行中",
+                "header/allDone": "すべての操作が完了しました",
+                "empty/noOperation": "実行中のファイル操作はありません",
+                "op/moving": "{n} 個のファイルを移動中",
+                "op/copying": "{n} 個のファイルをコピー中",
+                "op/zipping": "{n} 個のファイルを圧縮中",
+                "op/unzipping": "{n} 個のファイルを展開中",
+                "op/processing": "{n} 個のファイルを処理中",
+                "op/source": "· ソース:{p}",
+                "op/oneDuplicate": "コピー先に同じ名前のファイルが 1 個あります",
+                "op/nDuplicates": "コピー先に同じ名前のファイルが {n} 個あります",
+                "row/completed": "完了",
+                "row/cancelled": "キャンセル済み",
+                "row/failed": "失敗",
+                "row/waiting": "待機中",
+                "row/paused": "一時停止中",
+                "row/remaining": "残り {t}",
+                "time/hours": "{n} 時間",
+                "time/minutes": "{n} 分",
+                "time/seconds": "{n} 秒",
+                "footer/total": "合計:{done} / {total}",
+                "footer/clearCompleted": "完了した項目を消去",
+                "footer/cancelAll": "すべてキャンセル",
+                "error/Unable to start file operation": "ファイル操作を開始できません",
+                "error/Access Denied: No Write Permission": "アクセスが拒否されました:書き込み権限がありません",
+                "button/collapse": "折りたたむ",
+                "button/expand": "展開",
+                "button/remove": "削除",
+                "stack/oneFile": "1 個のファイル",
+                "stack/files": "{n} 個のファイル",
                 "": ""
             },
             "titles": {},
@@ -231,10 +386,41 @@
                 "error/File already exists": "파일이 이미 존재합니다",
                 "error/This directory is Read Only": "이 디렉토리는 읽기 전용입니다",
                 "error/Operation cancelled by user": "사용자에 의해 작업이 취소되었습니다",
+                "header/oneOperation": "작업 1개 진행 중",
+                "header/nOperations": "작업 {n}개 진행 중",
+                "header/allDone": "모든 작업이 완료되었습니다",
+                "empty/noOperation": "실행 중인 파일 작업이 없습니다",
+                "op/moving": "파일 {n}개 이동 중",
+                "op/copying": "파일 {n}개 복사 중",
+                "op/zipping": "파일 {n}개 압축 중",
+                "op/unzipping": "파일 {n}개 압축 해제 중",
+                "op/processing": "파일 {n}개 처리 중",
+                "op/source": "· 원본: {p}",
+                "op/oneDuplicate": "대상 위치에 같은 이름의 파일이 1개 있습니다",
+                "op/nDuplicates": "대상 위치에 같은 이름의 파일이 {n}개 있습니다",
+                "row/completed": "완료됨",
+                "row/cancelled": "취소됨",
+                "row/failed": "실패",
+                "row/waiting": "대기 중",
+                "row/paused": "일시 중지됨",
+                "row/remaining": "{t} 남음",
+                "time/hours": "{n}시간",
+                "time/minutes": "{n}분",
+                "time/seconds": "{n}초",
+                "footer/total": "합계: {done} / {total}",
+                "footer/clearCompleted": "완료된 항목 지우기",
+                "footer/cancelAll": "모두 취소",
+                "error/Unable to start file operation": "파일 작업을 시작할 수 없습니다",
+                "error/Access Denied: No Write Permission": "접근 거부: 쓰기 권한이 없습니다",
+                "button/collapse": "접기",
+                "button/expand": "펼치기",
+                "button/remove": "제거",
+                "stack/oneFile": "파일 1개",
+                "stack/files": "파일 {n}개",
                 "": ""
             },
             "titles": {},
             "placeholder": {}
         }
     }
-}
+}

+ 47 - 61
src/web/desktop.html

@@ -1767,7 +1767,49 @@
             });
         }
 
-        //The background task checking function will ping server side at a more 
+        /*
+            System wide file operation dialog
+
+            Only one file operation dialog is opened at a time. Every move, copy,
+            zip and unzip request is handed over to the running dialog so the
+            desktop never ends up with a stack of windows each holding their own
+            status connection. See SystemAO/file_system/file_operation.html
+        */
+        var fileOperationWindowUID = "arozFileOperationDialog";
+        function startFileOperation(oprConfig, retryCount=0){
+            var fw = getFloatWindowByID(fileOperationWindowUID);
+            if (fw != undefined && $(fw).length > 0){
+                var dialogFrame = $(fw).find("iframe")[0];
+                if (dialogFrame != undefined && dialogFrame.contentWindow != null &&
+                    typeof dialogFrame.contentWindow.addFileOperation == "function"){
+                    dialogFrame.contentWindow.addFileOperation(oprConfig);
+
+                    //Bring the dialog back into view in case it was minimized
+                    $(fw).fadeIn(100);
+                    MoveFloatWindowToTop(fw);
+                    return;
+                }
+
+                //The dialog window exists but its page is still loading. Wait for it.
+                if (retryCount < 40){
+                    setTimeout(function(){
+                        startFileOperation(oprConfig, retryCount + 1);
+                    }, 250);
+                    return;
+                }
+            }
+
+            newFloatWindow({
+                uid: fileOperationWindowUID,
+                url: "SystemAO/file_system/file_operation.html#" + encodeURIComponent(JSON.stringify(oprConfig)),
+                width: 480,
+                height: 430,
+                appicon: "SystemAO/file_system/img/selector.png",
+                title: applocale.getString("fileOperation/title", "File Operation")
+            });
+        }
+
+        //The background task checking function will ping server side at a more
         //frequent interval if there is a background task running
         var rapidIntervalTaskListing = undefined;
         function updateBackgroundgTaskList(){
@@ -4605,11 +4647,9 @@
                             //Check if source is also from user:/
                             var srcVroot = filelist[0].filepath.split(":/").shift();
                             var mode = "copy"
-                            var title = "Copying "
                             if (srcVroot == "user"){
                                 //Move
                                 mode = "move"
-                                title = "Moving "
                             }
 
                             var filepathList = [];
@@ -4618,32 +4658,12 @@
                             });
 
                             //Start the file operation dialog
-                            var oprConfig = {
+                            startFileOperation({
                                 opr: mode,
                                 src: filepathList,
                                 dest: "user:/Desktop/",
                                 overwriteMode: "ask"
-                            }
-                            var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-
-                            //Genreate window title
-                            title = title + filepathList.length;
-                            if (filepathList.length > 1){
-                                title += " files";
-                            }else{
-                                title += " file";
-                            }
-
-                            newFloatWindow({
-                                url: "SystemAO/file_system/file_operation.html#" + configHash,
-                                width: 400,
-                                height: 220,
-                                appicon: "SystemAO/file_system/img/selector.png",
-                                title: title
                             });
-
-
-
                         }
 
                         
@@ -4851,28 +4871,13 @@
         
         //Use move if it is folder on desktop, use copy if it is a shortcut
         function moveSourceFilesToTarget(sourceList, target, opr="move"){
-            var oprConfig = {
+            //Hand the operation over to the system wide file operation dialog
+            startFileOperation({
                 opr: opr,
                 src: sourceList,
                 dest: target,
                 callbackWindowID: "desktop",
                 callbackFunction: `refresh(undefined, true)`
-            }
-            var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-            var title = "Copying " + sourceList.length;
-            if (sourceList.length > 1){
-                title += " files";
-            }else{
-                title += " file";
-            }
-
-            //Create FloatWindow to handle the file operations
-            newFloatWindow({
-                url: "SystemAO/file_system/file_operation.html#" + configHash,
-                width: 400,
-                height: 220,
-                appicon: "SystemAO/file_system/img/selector.png",
-                title: title
             });
 
             //Delete the file location from db
@@ -6532,36 +6537,17 @@
             }
 
             var mode = "copy";
-            var title = "Copying "
             if (thisOprCutMode){
                 mode = "move";
-                title = "Moving "
             }
 
             if (fileList.length > 0){
                 //There are something to move. Start the file operation dialog
-                var oprConfig = {
+                startFileOperation({
                     opr: mode,
                     src: fileList,
                     dest: "user:/Desktop/",
                     overwriteMode: "ask"
-                }
-                var configHash = encodeURIComponent(JSON.stringify(oprConfig));
-
-                //Genreate window title
-                var title = title + fileList.length;
-                if (fileList.length > 1){
-                    title += " files";
-                }else{
-                    title += " file";
-                }
-
-                newFloatWindow({
-                    url: "SystemAO/file_system/file_operation.html#" + configHash,
-                    width: 400,
-                    height: 220,
-                    appicon: "SystemAO/file_system/img/selector.png",
-                    title: title
                 });
             }
             hideAllContextMenus();

+ 42 - 0
src/web/script/ao_module.js

@@ -465,6 +465,48 @@ function ao_module_newfw(launchConfig){
     }
 }
 
+/*
+    ao_module_startFileOperation(oprConfig)
+
+    Start a move / copy / zip / unzip operation and show it in the system wide
+    file operation dialog. There is only ever one of those dialogs open: when it
+    is already running the operation is handed over to it instead of opening
+    another window with another status connection.
+
+    Example:
+        ao_module_startFileOperation({
+            opr: "copy",                            //move / copy / zip / unzip / unzipAndOpen
+            src: ["user:/Desktop/test.txt"],        //Source file list
+            dest: "user:/Documents/",               //Destination folder
+            overwriteMode: "ask",                   //skip / overwrite / keep / ask (optional)
+            callbackWindowID: ao_module_windowID,   //Window to notify when done (optional)
+            callbackFunction: "refreshList()"       //Function to call on that window (optional)
+        });
+*/
+function ao_module_startFileOperation(oprConfig){
+    if (ao_module_virtualDesktop){
+        parent.startFileOperation(oprConfig);
+        return;
+    }
+
+    //Standalone mode. Reuse the named window opened by the previous operation.
+    var dialogURL = ao_root + "SystemAO/file_system/file_operation.html#" + encodeURIComponent(JSON.stringify(oprConfig));
+    var existingDialog = null;
+    try {
+        existingDialog = window.open("", "arozFileOperationDialog");
+    } catch(ex) {
+        existingDialog = null;
+    }
+
+    if (existingDialog != null && typeof existingDialog.addFileOperation == "function"){
+        existingDialog.addFileOperation(oprConfig);
+        existingDialog.focus();
+        return;
+    }
+
+    window.open(dialogURL, "arozFileOperationDialog", "width=500,height=470");
+}
+
 /*
     File Selector Path Memory
 

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff