Certainly! Let's walk through the issues in your Go code and provide a corrected version. Below are the key problems identified along with their respective solutions:
Identified Issues and Solutions
-
Incorrect Usage of app.GetScreen().Size() in Mouse Handler:
-
Issue: The method app.GetScreen().Size() returns two integers (width, height), but the code attempts to perform arithmetic directly on the tuple, which leads to a compilation error.
-
Solution: Decompose the returned values into separate variables and use them appropriately.
-
Unsafe Type Assertion on app.GetFocus():
-
Issue: The code uses a type assertion app.GetFocus().(*tview.List) without ensuring the actual type, which can cause a panic if the assertion fails.
-
Solution: Implement a safe type assertion using the "comma-ok" idiom to verify the type before proceeding.
-
Updating TUI Elements from a Goroutine:
-
Issue: The transferFile function runs in a goroutine and updates the progressBar directly. However, tview is not thread-safe, and UI updates should be performed on the main goroutine.
-
Solution: Pass the tview.Application instance to the transferFile function and use app.QueueUpdateDraw to safely update the progressBar.
-
Incorrect Path Joining for Remote File Systems:
-
Issue: The code uses filepath.Join, which is OS-specific, for both local and remote (SFTP) paths. Remote paths typically use forward slashes (/), regardless of the client's OS.
-
Solution: Use the path package for remote paths and filepath for local paths. Introduce a helper function to handle path joining based on the file system type.
-
Mouse Click Region Calculation:
-
Issue: The calculation to determine which list (local or remote) was clicked is based on dividing the total screen width by two, which might not align with the actual UI layout, especially if the window is resized.
-
Solution: Retrieve the actual rectangle (x, y, width, height) of each list and determine which one was clicked based on the mouse coordinates.
-
Handling Double Click Detection:
-
Issue: The current double-click detection logic assumes the entire screen is split into two equal halves, which might not align with the Flex layout.
-
Solution: Refine the double-click logic to accurately detect clicks within the bounds of each list.
Corrected Code
Below is the corrected version of your Go code with the above issues addressed:
package main
import (
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/gdamore/tcell/v2"
"github.com/pkg/sftp"
"github.com/rivo/tview"
"golang.org/x/crypto/ssh"
)
type FileSystem struct {
currentPath string
list *tview.List
isRemote bool
sftpClient *sftp.Client
app *tview.Application
}
func NewFileSystem(app *tview.Application, isRemote bool, sftpClient *sftp.Client) *FileSystem {
fs := &FileSystem{
currentPath: "/",
list: tview.NewList().ShowSecondaryText(false),
isRemote: isRemote,
sftpClient: sftpClient,
app: app,
}
fs.list.SetBorder(true).SetTitle(fmt.Sprintf("%s File System", getSystemType(isRemote)))
return fs
}
func getSystemType(isRemote bool) string {
if isRemote {
return "Remote"
}
return "Local"
}
func (fs *FileSystem) updateList() {
fs.list.Clear()
fs.list.AddItem("[::b]📁 ..[-:-:-]", "Go to parent directory", 0, nil)
if fs.isRemote {
files, err := fs.sftpClient.ReadDir(fs.currentPath)
if err != nil {
log.Printf("Error reading remote directory: %v", err)
return
}
for _, file := range files {
addFileItem(fs.list, file.Name(), file.IsDir(), file.Mode()&os.ModeSymlink != 0)
}
} else {
entries, err := os.ReadDir(fs.currentPath)
if err != nil {
log.Printf("Error reading local directory: %v", err)
return
}
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
log.Printf("Error getting file info: %v", err)
continue
}
addFileItem(fs.list, entry.Name(), entry.IsDir(), info.Mode()&os.ModeSymlink != 0)
}
}
}
func addFileItem(list *tview.List, name string, isDir bool, isSymlink bool) {
var icon string
var colorTag string
if isSymlink {
icon = "🔗"
colorTag = "[yellow]"
} else if isDir {
icon = "📁"
colorTag = "[blue]"
} else {
icon = "📄"
colorTag = "[white]"
}
list.AddItem(fmt.Sprintf("%s%s %s[-]", colorTag, icon, name), "", 0, nil)
}
func (fs *FileSystem) navigateTo(pathStr string) {
fs.currentPath = pathStr
fs.updateList()
}
func createSFTPClient(host, user, password string) (*sftp.Client, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", host, config)
if err != nil {
return nil, fmt.Errorf("failed to dial: %v", err)
}
client, err := sftp.NewClient(conn)
if err != nil {
return nil, fmt.Errorf("failed to create SFTP client: %v", err)
}
return client, nil
}
func transferFile(app *tview.Application, sourceFS, targetFS *FileSystem, filename string, progressBar *tview.TextView) {
sourcePath := joinPath(sourceFS, filename)
targetPath := joinPath(targetFS, filename)
var sourceFile io.ReadCloser
var targetFile io.WriteCloser
var err error
var fileSize int64
// Open source file
if sourceFS.isRemote {
sourceFile, err = sourceFS.sftpClient.Open(sourcePath)
if err == nil {
fileInfo, err := sourceFS.sftpClient.Stat(sourcePath)
if err == nil {
fileSize = fileInfo.Size()
}
}
} else {
sourceFile, err = os.Open(sourcePath)
if err == nil {
fileInfo, err := os.Stat(sourcePath)
if err == nil {
fileSize = fileInfo.Size()
}
}
}
if err != nil {
log.Printf("Error opening source file: %v", err)
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, fmt.Sprintf("Error opening source file: %v", err), 0)
})
return
}
defer sourceFile.Close()
// Create target file
if targetFS.isRemote {
targetFile, err = targetFS.sftpClient.Create(targetPath)
} else {
targetFile, err = os.Create(targetPath)
}
if err != nil {
log.Printf("Error creating target file: %v", err)
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, fmt.Sprintf("Error creating target file: %v", err), 0)
})
return
}
defer targetFile.Close()
// Perform file transfer
if sourceFS.isRemote {
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, "Downloading file...", 0)
})
} else {
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, "Uploading file...", 0)
})
}
buf := make([]byte, 32*1024)
var totalWritten int64
for {
n, err := sourceFile.Read(buf)
if err != nil && err != io.EOF {
log.Printf("Error reading from source: %v", err)
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, fmt.Sprintf("Error reading from source: %v", err), 0)
})
return
}
if n == 0 {
break
}
if _, err := targetFile.Write(buf[:n]); err != nil {
log.Printf("Error writing to target: %v", err)
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, fmt.Sprintf("Error writing to target: %v", err), 0)
})
return
}
totalWritten += int64(n)
if fileSize > 0 {
progress := float64(totalWritten) / float64(fileSize) * 100
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, fmt.Sprintf("Transferring... %.2f%%", progress), int(progress))
})
}
}
app.QueueUpdateDraw(func() {
updateProgressBar(progressBar, "Transfer completed successfully", 100)
})
// Update file lists after transfer
app.QueueUpdateDraw(func() {
sourceFS.updateList()
targetFS.updateList()
})
}
func joinPath(fs *FileSystem, elem string) string {
if fs.isRemote {
return path.Join(fs.currentPath, elem)
}
return filepath.Join(fs.currentPath, elem)
}
func updateProgressBar(progressBar *tview.TextView, message string, percent int) {
progressBar.Clear()
width := 50 // width of the progress bar
completed := width * percent / 100
if completed > width {
completed = width
}
progressBar.SetText(fmt.Sprintf("%s\n[green]%s[white]%s",
message,
strings.Repeat("█", completed),
strings.Repeat("░", width-completed)))
}
func main() {
// SFTP server credentials
host := "your_sftp_server:22"
user := "your_username"
password := "your_password"
sftpClient, err := createSFTPClient(host, user, password)
if err != nil {
log.Fatalf("Failed to create SFTP client: %v", err)
}
defer sftpClient.Close()
app := tview.NewApplication()
localFS := NewFileSystem(app, false, nil)
remoteFS := NewFileSystem(app, true, sftpClient)
flex := tview.NewFlex().
AddItem(localFS.list, 0, 1, true).
AddItem(remoteFS.list, 0, 1, false)
progressBar := tview.NewTextView().
SetDynamicColors(true).
SetRegions(true).
SetWrap(false)
progressBox := tview.NewBox().
SetBorder(true).
SetTitle("Transfer Progress")
progressFlex := tview.NewFlex().
AddItem(nil, 0, 1, false).
AddItem(progressBar, 0, 3, false).
AddItem(nil, 0, 1, false)
mainFlex := tview.NewFlex().
SetDirection(tview.FlexRow).
AddItem(flex, 0, 1, true).
AddItem(progressBox, 3, 1, false)
progressBox.SetDrawFunc(func(screen tcell.Screen, x, y, width, height int) (int, int, int, int) {
progressFlex.SetRect(x, y, width, height)
progressFlex.Draw(screen)
return x, y, width, height
})
localFS.updateList()
remoteFS.updateList()
lastClickTime := time.Now()
lastClickItem := -1
handleItemSelection := func(app *tview.Application, currentFS, targetFS *FileSystem, index int) {
if index == 0 {
// Navigate to parent directory
parentDir := path.Dir(currentFS.currentPath)
currentFS.navigateTo(parentDir)
return
}
selectedText, _ := currentFS.list.GetItemText(index)
selectedPath := strings.TrimSpace(strings.TrimLeft(selectedText, "📁📄🔗 "))
fullPath := joinPath(currentFS, selectedPath)
var isDir bool
if currentFS.isRemote {
info, err := currentFS.sftpClient.Stat(fullPath)
if err != nil {
log.Printf("Error getting remote file info: %v", err)
return
}
isDir = info.IsDir()
} else {
info, err := os.Stat(fullPath)
if err != nil {
log.Printf("Error getting local file info: %v", err)
return
}
isDir = info.IsDir()
}
if isDir {
currentFS.navigateTo(fullPath)
} else {
// Start file transfer in a new goroutine
go transferFile(app, currentFS, targetFS, selectedPath, progressBar)
}
}
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyTab:
if app.GetFocus() == localFS.list {
app.SetFocus(remoteFS.list)
} else {
app.SetFocus(localFS.list)
}
return nil
case tcell.KeyEnter:
currentList, ok := app.GetFocus().(*tview.List)
if !ok {
return event
}
currentFS := localFS
targetFS := remoteFS
if currentList == remoteFS.list {
currentFS = remoteFS
targetFS = localFS
}
selectedItem := currentList.GetCurrentItem()
handleItemSelection(app, currentFS, targetFS, selectedItem)
return nil
}
return event
})
app.SetMouseCapture(func(event *tcell.EventMouse, action tview.MouseAction) (*tcell.EventMouse, tview.MouseAction) {
if action == tview.MouseLeftClick {
x, y := event.Position()
// Get the rectangles of both lists
localRect := localFS.list.GetRect()
remoteRect := remoteFS.list.GetRect()
var currentFS, targetFS *FileSystem
var currentList *tview.List
if pointInRect(x, y, localRect) {
currentFS = localFS
targetFS = remoteFS
currentList = localFS.list
} else if pointInRect(x, y, remoteRect) {
currentFS = remoteFS
targetFS = localFS
currentList = remoteFS.list
} else {
// Click outside the lists
return event, action
}
index := y - currentRectTop(currentList)
if index >= 0 && index < currentList.GetItemCount() {
if index == lastClickItem && time.Since(lastClickTime) < 400*time.Millisecond {
// Double click detected
handleItemSelection(app, currentFS, targetFS, index)
lastClickItem = -1
} else {
lastClickItem = index
lastClickTime = time.Now()
}
}
}
return event, action
})
if err := app.SetRoot(mainFlex, true).EnableMouse(true).Run(); err != nil {
log.Fatalf("Error running application: %v", err)
}
}
// pointInRect checks if a point (x, y) is inside the given rectangle.
func pointInRect(x, y int, rect [4]int) bool {
rectX, rectY, rectWidth, rectHeight := rect[0], rect[1], rect[2], rect[3]
return x >= rectX && x < rectX+rectWidth && y >= rectY && y < rectY+rectHeight
}
// currentRectTop returns the top Y coordinate of the given list.
func currentRectTop(list *tview.List) int {
rect := list.GetRect()
return rect[1] + 1 // Adjust for border
}
Detailed Explanation of Corrections
-
Mouse Handler (SetMouseCapture):
-
Before:
if x < app.GetScreen().Size()/2
-
After:
width, _ := app.GetScreen().Size()
if x < width/2
The Size() method is correctly decomposed into width and height, and the comparison uses only the width.
-
Further Improvement:
Instead of assuming the screen is split exactly in half, the corrected code retrieves the actual rectangle (x, y, width, height) of each list and determines which one was clicked using the pointInRect helper function.
-
Safe Type Assertion:
-
Before:
currentList := app.GetFocus().(*tview.List)
-
After:
currentList, ok := app.GetFocus().(*tview.List)
if !ok {
return event
}
This ensures that currentList is indeed a *tview.List before proceeding, preventing potential panics.
-
Thread-Safe UI Updates:
-
Before: updateProgressBar was called directly from a goroutine, which is unsafe.
-
After: The transferFile function now accepts the *tview.Application instance and uses app.QueueUpdateDraw to safely update the progressBar. This ensures that all UI updates occur on the main goroutine, adhering to tview's thread-safety requirements.
-
Path Joining Based on File System Type:
-
Introduced a helper function joinPath that uses path.Join for remote file systems and filepath.Join for local ones. This ensures that path separators are handled correctly based on the context.
-
Example:
func joinPath(fs *FileSystem, elem string) string {
if fs.isRemote {
return path.Join(fs.currentPath, elem)
}
return filepath.Join(fs.currentPath, elem)
}
Testing the Corrections
To ensure that the corrected code works as expected:
-
Set SFTP Credentials:
Replace the placeholder values with actual SFTP server credentials:
host := "your_sftp_server:22"
user := "your_username"
password := "your_password"
-
Install Dependencies:
Ensure that all required packages are installed:
go get github.com/gdamore/tcell/v2
go get github.com/pkg/sftp
go get github.com/rivo/tview
go get golang.org/x/crypto/ssh
-
Run the Application:
go run your_file.go
Navigate through the local and remote file systems using the keyboard or mouse. Attempt file transfers to verify that progress updates correctly and that there are no runtime errors.
Conclusion
The corrected code addresses the primary compilation and runtime issues, ensuring type safety, thread-safe UI updates, and accurate path handling. By following these adjustments, your application should function smoothly, allowing users to navigate and transfer files between local and remote systems efficiently.