src

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

run.go (1744B)


      1 package editor
      2 
      3 import (
      4 	"context"
      5 	"fmt"
      6 
      7 	"code.dwrz.net/src/pkg/build"
      8 	"code.dwrz.net/src/pkg/editor/event"
      9 )
     10 
     11 func (e *Editor) Run(ctx context.Context, files []string) error {
     12 	if err := e.terminal.SetRaw(); err != nil {
     13 		return fmt.Errorf("failed to set raw mode: %w", err)
     14 	}
     15 	e.canvas.Reset()
     16 
     17 	// Log build info.
     18 	e.log.Debug.Printf(
     19 		"文 version %s; built at %s on %s",
     20 		build.Commit, build.Time, build.Hostname,
     21 	)
     22 
     23 	// Reset the terminal before exiting.
     24 	defer func() {
     25 		e.canvas.Reset()
     26 
     27 		if err := e.terminal.Reset(); err != nil {
     28 			e.log.Error.Printf(
     29 				"failed to reset terminal attributes: %v", err,
     30 			)
     31 		}
     32 	}()
     33 
     34 	// Start reading user input.
     35 	go func() {
     36 		if err := e.reader.Run(ctx); err != nil {
     37 			e.events <- event.NewError(err)
     38 		}
     39 	}()
     40 
     41 	// Open the files.
     42 	go e.load(files)
     43 
     44 	// Main loop.
     45 	for {
     46 		select {
     47 		case <-ctx.Done():
     48 			e.log.Debug.Printf("context done: stopping")
     49 			return nil
     50 
     51 		case ev := <-e.events:
     52 			switch t := ev.(type) {
     53 			case *event.Error:
     54 				return t
     55 
     56 			case *event.Message:
     57 				e.prompt.SetText(t.Text())
     58 
     59 				if err := e.canvas.Render(
     60 					e.active, e.prompt,
     61 				); err != nil {
     62 					return fmt.Errorf(
     63 						"failed to render: %w", err,
     64 					)
     65 				}
     66 
     67 			case *event.Quit:
     68 				return nil
     69 			}
     70 
     71 		case event := <-e.input:
     72 			if e.prompt.IsPrompt() {
     73 				if err := e.promptInput(event); err != nil {
     74 					return fmt.Errorf(
     75 						"failed to process input: %w",
     76 						err,
     77 					)
     78 				}
     79 			} else {
     80 				if err := e.bufferInput(event); err != nil {
     81 					return fmt.Errorf(
     82 						"failed to process input: %w",
     83 						err,
     84 					)
     85 				}
     86 			}
     87 
     88 			if err := e.canvas.Render(
     89 				e.active, e.prompt,
     90 			); err != nil {
     91 				return fmt.Errorf("failed to render: %w", err)
     92 			}
     93 		}
     94 	}
     95 }