...

Source file src/github.com/common-nighthawk/go-figure/figure.go

Documentation: github.com/common-nighthawk/go-figure

     1  package figure
     2  
     3  import (
     4  	"io"
     5  	"log"
     6  	"reflect"
     7  	"strings"
     8  )
     9  
    10  const ascii_offset = 32
    11  const first_ascii = ' '
    12  const last_ascii = '~'
    13  
    14  type figure struct {
    15  	phrase string
    16  	font
    17  	strict bool
    18  	color  string
    19  }
    20  
    21  func NewFigure(phrase, fontName string, strict bool) figure {
    22  	font := newFont(fontName)
    23  	if font.reverse {
    24  		phrase = reverse(phrase)
    25  	}
    26  	return figure{phrase: phrase, font: font, strict: strict}
    27  }
    28  
    29  func NewColorFigure(phrase, fontName string, color string, strict bool) figure {
    30  	color = strings.ToLower(color)
    31  	if _, found := colors[color]; !found {
    32  		log.Fatalf("invalid color. must be one of: %s", reflect.ValueOf(colors).MapKeys())
    33  	}
    34  
    35  	fig := NewFigure(phrase, fontName, strict)
    36  	fig.color = color
    37  	return fig
    38  }
    39  
    40  func NewFigureWithFont(phrase string, reader io.Reader, strict bool) figure {
    41  	font := newFontFromReader(reader)
    42  	if font.reverse {
    43  		phrase = reverse(phrase)
    44  	}
    45  	return figure{phrase: phrase, font: font, strict: strict}
    46  }
    47  
    48  func (figure figure) Slicify() (rows []string) {
    49  	for r := 0; r < figure.font.height; r++ {
    50  		printRow := ""
    51  		for _, char := range figure.phrase {
    52  			if char < first_ascii || char > last_ascii {
    53  				if figure.strict {
    54  					log.Fatal("invalid input.")
    55  				} else {
    56  					char = '?'
    57  				}
    58  			}
    59  			fontIndex := char - ascii_offset
    60  			charRowText := scrub(figure.font.letters[fontIndex][r], figure.font.hardblank)
    61  			printRow += charRowText
    62  		}
    63  		if r < figure.font.baseline || len(strings.TrimSpace(printRow)) > 0 {
    64  			rows = append(rows, strings.TrimRight(printRow, " "))
    65  		}
    66  	}
    67  	return rows
    68  }
    69  
    70  func scrub(text string, char byte) string {
    71  	return strings.Replace(text, string(char), " ", -1)
    72  }
    73  
    74  func reverse(s string) string {
    75  	runes := []rune(s)
    76  	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
    77  		runes[i], runes[j] = runes[j], runes[i]
    78  	}
    79  	return string(runes)
    80  }
    81  

View as plain text