src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

buffers.go (2030B)


      1 package editor
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"os"
      7 	"path/filepath"
      8 
      9 	"code.dwrz.net/src/pkg/editor/buffer"
     10 	"code.dwrz.net/src/pkg/editor/event"
     11 )
     12 
     13 // load files into editor buffers.
     14 func (e *Editor) load(files []string) {
     15 	// Attempt to deduplicate any files.
     16 	var unique = map[string]struct{}{}
     17 	for _, f := range files {
     18 		path, err := filepath.Abs(f)
     19 		if err != nil {
     20 			e.log.Error.Printf(
     21 				"failed to get absolute path for %s: %v",
     22 				f, err,
     23 			)
     24 
     25 			path = filepath.Clean(f)
     26 		}
     27 
     28 		unique[path] = struct{}{}
     29 	}
     30 
     31 	// Load the files.
     32 	// Set the first successfully loaded file as the active buffer.
     33 	var setActive bool
     34 	for name := range unique {
     35 		p := buffer.NewBufferParams{
     36 			Name: name,
     37 			Log:  e.log,
     38 		}
     39 
     40 		b, err := buffer.Open(p)
     41 		// Create the file if it doesn't exist.
     42 		if errors.Is(err, os.ErrNotExist) {
     43 			b, err = buffer.Create(p)
     44 		}
     45 		// If there was an error, report it to the user.
     46 		if err != nil {
     47 			e.events <- event.NewMessage(fmt.Sprintf(
     48 				"failed to load buffer %s: %v",
     49 				name, err,
     50 			))
     51 			continue
     52 		}
     53 
     54 		e.log.Debug.Printf("loaded buffer %s", name)
     55 
     56 		e.setBuffer(b)
     57 
     58 		if !setActive {
     59 			e.setActiveBuffer(name)
     60 		}
     61 	}
     62 
     63 	e.events <- event.NewMessage("loaded buffers")
     64 }
     65 
     66 func (e *Editor) renameBuffer(b *buffer.Buffer, name string) error {
     67 	e.mu.Lock()
     68 	defer e.mu.Unlock()
     69 
     70 	delete(e.buffers, b.Name())
     71 	e.buffers[name] = b
     72 
     73 	if err := b.SaveAs(name); err != nil {
     74 		return fmt.Errorf("failed to save as %s: %v", name, err)
     75 	}
     76 
     77 	return nil
     78 }
     79 
     80 // setActiveBuffer sets the named buffer as the active buffer.
     81 func (e *Editor) setActiveBuffer(name string) {
     82 	e.mu.Lock()
     83 	defer e.mu.Unlock()
     84 
     85 	b, exists := e.buffers[name]
     86 	if !exists {
     87 		e.events <- event.NewError(fmt.Errorf(
     88 			"failed to set active buffer: %s does not exist", name,
     89 		))
     90 	}
     91 
     92 	e.active = b
     93 	e.log.Debug.Printf("set active buffer %s", b.Name())
     94 }
     95 
     96 // setBuffer stores a buffer in the editor's buffer map.
     97 func (e *Editor) setBuffer(b *buffer.Buffer) {
     98 	e.mu.Lock()
     99 	defer e.mu.Unlock()
    100 
    101 	e.buffers[b.Name()] = b
    102 }