font-out.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package main
  2. import (
  3. "encoding/binary"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. // http://www.roysac.com/blog/2014/04/thedraw-fonts-file-tdf-specifications/
  11. var Conversion [][2]int
  12. // copied from tdfont.go, and modified
  13. func thedraw_to_ansi(c int) int {
  14. trans := []int{0, 4, 2, 6, 1, 5, 3, 7}
  15. // 0, 1, 2, 3, 4, 5, 6, 7
  16. return trans[c]
  17. }
  18. func MatchStyle(color byte, look byte) int {
  19. var match int = 0
  20. if ((color >> 4) & 0x07) == look {
  21. // Top
  22. match |= 1
  23. }
  24. if (color & 0x07) == look {
  25. // Bottom
  26. match |= 2
  27. }
  28. return match
  29. }
  30. func PatchColor(color byte, new_color byte, style int) byte {
  31. var c byte = color
  32. if style&1 == 1 {
  33. c = (c & 0x8f) | new_color<<4
  34. }
  35. if style&2 == 2 {
  36. c = (c & 0xf8) | new_color
  37. }
  38. return c
  39. }
  40. type ColorMap map[[2]int][][2]int
  41. func Scan(block [][][]byte, find_color int) ColorMap {
  42. var Targets ColorMap = make(ColorMap, 0)
  43. // Scan the font looking for the given color FG/BG
  44. // Covert color code to TheDraw Color
  45. actual := byte(thedraw_to_ansi(find_color))
  46. for charIndex := range block {
  47. for lineIndex := range block[charIndex] {
  48. var found bool = false
  49. var patches [][2]int = make([][2]int, 0)
  50. for offset := 1; offset < len(block[charIndex][lineIndex]); offset += 2 {
  51. color := block[charIndex][lineIndex][offset]
  52. style := MatchStyle(color, actual)
  53. if style != 0 {
  54. // log.Printf("color: %x actual %x style: %d\n", color, actual, style)
  55. patches = append(patches, [2]int{offset, style})
  56. found = true
  57. }
  58. }
  59. if found {
  60. pos := [2]int{charIndex, lineIndex}
  61. Targets[pos] = make([][2]int, len(patches))
  62. copy(Targets[pos], patches)
  63. /*
  64. for i := range patches {
  65. Targets[pos][i] = patches[i]
  66. }
  67. */
  68. // Targets[pos] = patches
  69. }
  70. }
  71. }
  72. return Targets
  73. }
  74. func Modify(block [][][]byte, new_color int, Targets ColorMap) {
  75. // Covert color code to TheDraw Color
  76. actual := byte(thedraw_to_ansi(new_color))
  77. for pos, patch := range Targets {
  78. for _, p := range patch {
  79. block[pos[0]][pos[1]][p[0]] = PatchColor(block[pos[0]][pos[1]][p[0]], actual, p[1])
  80. }
  81. }
  82. }
  83. // Use ExtractColor to get the font -- then output that?
  84. func OutputColor(writer *os.File, name string, offsets []uint16, data []byte) {
  85. // fmt.Printf("Extract Color Font: %s\n", name)
  86. var indexes []int
  87. var blocks [][][]byte
  88. var current [][]byte
  89. var line []byte
  90. pos := 0
  91. for pos < len(data) {
  92. indexes = append(indexes, pos)
  93. current = make([][]byte, 0)
  94. line = make([]byte, 0)
  95. // We don't use these.
  96. // w = data[pos]
  97. // h = data[pos+1]
  98. pos += 2
  99. // process this character
  100. for pos < len(data) {
  101. ch := data[pos]
  102. pos++
  103. if ch == 0x00 {
  104. // end of character
  105. current = append(current, line)
  106. blocks = append(blocks, current)
  107. // current = make([][]byte, 0)
  108. // line = make([]byte, 0)
  109. break
  110. }
  111. if ch == 0x0d {
  112. // end of this character line
  113. current = append(current, line)
  114. line = make([]byte, 0)
  115. continue
  116. }
  117. if ch == 0x26 {
  118. // & descender mark
  119. continue
  120. }
  121. line = append(line, ch)
  122. color := data[pos]
  123. pos++
  124. line = append(line, color)
  125. }
  126. }
  127. // offset optimization:
  128. var single []int
  129. for _, o := range offsets {
  130. if o == 65535 {
  131. single = append(single, -1)
  132. continue
  133. }
  134. for idx, i := range indexes {
  135. if o == uint16(i) {
  136. single = append(single, idx)
  137. break
  138. }
  139. }
  140. }
  141. /*
  142. // Handle Names with spaces
  143. filename := fmt.Sprintf("%s_font.go", strings.Replace(name, " ", "", -1))
  144. fp, err := os.Create(filename)
  145. if err != nil {
  146. panic(err)
  147. }
  148. fmt.Printf("Writing: %s\n", filename)
  149. defer fp.Close()
  150. writer := bufio.NewWriter(fp)
  151. */
  152. // writer := bufio.NewWriter(os.Stdout)
  153. writer.WriteString("\n// " + name + "\n\n")
  154. // Name := strings.ToUpper(name)
  155. Name := strings.Replace(name, " ", "", -1)
  156. writer.WriteString("func Font" + Name + "() door.ColorFont {\n")
  157. var output string
  158. output = "\treturn door.ColorFont{Characters: []int{"
  159. for _, s := range single {
  160. output += strconv.Itoa(s) + ", "
  161. }
  162. output = output[:len(output)-2] + "},\n"
  163. writer.WriteString(output)
  164. // writer.Flush()
  165. if len(Conversion) > 0 {
  166. // Color Convert time!
  167. var Maps []map[[2]int][][2]int = make([]map[[2]int][][2]int, len(Conversion))
  168. for idx, codes := range Conversion {
  169. Maps[idx] = Scan(blocks, codes[0])
  170. }
  171. for idx, codes := range Conversion {
  172. Modify(blocks, codes[1], Maps[idx])
  173. }
  174. }
  175. output = "\t\tData: [][][]byte{"
  176. for _, blk := range blocks {
  177. output += "{"
  178. if len(blk) == 0 {
  179. output += "{},"
  180. } else {
  181. for _, inner := range blk {
  182. // output += text_to_hextext(b) + ","
  183. output += "{" + byte_to_text(inner) + "}, "
  184. }
  185. output = output[:len(output)-2]
  186. }
  187. output += "},\n"
  188. writer.WriteString(output)
  189. output = "\t\t\t"
  190. }
  191. writer.WriteString("\t\t}}\n")
  192. writer.WriteString("}\n")
  193. // writer.Flush()
  194. }
  195. // Use ExtractBlock to get the Font, and then output that?
  196. func OutputBlock(writer *os.File, name string, offsets []uint16, data []byte) {
  197. // fmt.Printf("Extract Block Font: %s\n", name)
  198. var indexes []int
  199. var blocks [][][]byte
  200. var current [][]byte
  201. var line []byte
  202. pos := 0
  203. for pos < len(data) {
  204. indexes = append(indexes, pos)
  205. current = make([][]byte, 0)
  206. line = make([]byte, 0)
  207. // We don't use these
  208. // w = data[pos]
  209. // h = data[pos+1]
  210. pos += 2
  211. // process this character
  212. for pos < len(data) {
  213. ch := data[pos]
  214. pos++
  215. if ch == 0x00 {
  216. // end of character
  217. current = append(current, line)
  218. blocks = append(blocks, current)
  219. // current = make([][]byte, 0)
  220. // line = make([]byte, 0)
  221. break
  222. }
  223. if ch == 0x0d {
  224. // end of this character line
  225. current = append(current, line)
  226. line = make([]byte, 0)
  227. continue
  228. }
  229. if ch == 0x26 {
  230. // & descender mark
  231. continue
  232. }
  233. line = append(line, ch)
  234. }
  235. }
  236. // offset optimization:
  237. var single []int
  238. for _, o := range offsets {
  239. if o == 65535 {
  240. single = append(single, -1)
  241. continue
  242. }
  243. for idx, i := range indexes {
  244. if o == uint16(i) {
  245. single = append(single, idx)
  246. break
  247. }
  248. }
  249. }
  250. /*
  251. // Handle Names with spaces
  252. filename := fmt.Sprintf("%s_font.go", strings.Replace(name, " ", "", -1))
  253. fp, err := os.Create(filename)
  254. if err != nil {
  255. panic(err)
  256. }
  257. fmt.Printf("Writing: %s\n", filename)
  258. defer fp.Close()
  259. writer := bufio.NewWriter(fp)
  260. */
  261. // writer := bufio.NewWriter(os.Stdout)
  262. // Should this output routine be part of the BlockFont?
  263. // I think so!
  264. // writer.WriteString("package main\n")
  265. writer.WriteString("// " + name + "\n\n")
  266. // Name := strings.ToUpper(name)
  267. Name := strings.Replace(name, " ", "", -1)
  268. writer.WriteString("func Font" + Name + "() door.BlockFont {\n")
  269. var output string
  270. output = " return door.BlockFont{Characters: []int{"
  271. for _, s := range single {
  272. output += strconv.Itoa(s) + ", "
  273. }
  274. output = output[:len(output)-2] + "},\n"
  275. writer.WriteString(output)
  276. // writer.Flush()
  277. output = " Data: [][][]byte{"
  278. for _, blk := range blocks {
  279. output += "{"
  280. if len(blk) == 0 {
  281. output += "{},"
  282. } else {
  283. for _, inner := range blk {
  284. output += "{" + byte_to_text(inner) + "},"
  285. }
  286. output = output[:len(output)-1]
  287. }
  288. output += "},\n"
  289. // output = output[:len(output)-1]
  290. // output += "},\n"
  291. writer.WriteString(output)
  292. output = " "
  293. }
  294. writer.WriteString(" }}\n")
  295. writer.WriteString("}\n")
  296. // writer.Flush()
  297. }
  298. // outputs fonts
  299. func OutputFonts(writer *os.File, filename string, fonts []string) {
  300. f, err := os.Open(filename)
  301. if err != nil {
  302. fmt.Printf("Open(%s): %s\n", filename, err)
  303. panic(err)
  304. }
  305. defer f.Close()
  306. tdfonts := make([]byte, 20)
  307. f.Read(tdfonts)
  308. for {
  309. fontdef := make([]byte, 4)
  310. read, _ := f.Read(fontdef)
  311. if read != 4 {
  312. break
  313. }
  314. fontname := make([]byte, 13)
  315. f.Read(fontname)
  316. Name := strings.Trim(string(fontname[1:]), "\x00")
  317. // fmt.Printf("Font: %s\n", Name)
  318. f.Read(fontdef)
  319. single := make([]byte, 1)
  320. var FontType int8
  321. binary.Read(f, binary.LittleEndian, &FontType)
  322. // fmt.Printf("Font: %s (type %d)\n", Name, FontType)
  323. f.Read(single) // Spacing
  324. var BlockSize int16
  325. binary.Read(f, binary.LittleEndian, &BlockSize)
  326. letterOffsets := make([]uint16, 94)
  327. binary.Read(f, binary.LittleEndian, &letterOffsets)
  328. if false {
  329. for idx, i := range letterOffsets {
  330. fmt.Printf(" %04X", i)
  331. if (idx+1)%10 == 0 {
  332. fmt.Println("")
  333. }
  334. }
  335. fmt.Println("")
  336. }
  337. data := make([]byte, BlockSize)
  338. binary.Read(f, binary.LittleEndian, &data)
  339. // Special case where they are asking for all fonts
  340. if len(fonts) == 1 && fonts[0] == "*" {
  341. switch FontType {
  342. case 1:
  343. OutputBlock(writer, Name, letterOffsets, data)
  344. case 2:
  345. OutputColor(writer, Name, letterOffsets, data)
  346. default:
  347. fmt.Printf("// Sorry, I can't handle Font: %s Type %d!\n", Name, FontType)
  348. }
  349. } else {
  350. for _, f := range fonts {
  351. if Name == f {
  352. switch FontType {
  353. case 1:
  354. OutputBlock(writer, Name, letterOffsets, data)
  355. case 2:
  356. OutputColor(writer, Name, letterOffsets, data)
  357. default:
  358. fmt.Printf("// Sorry, I can't handle Font: %s Type %d!\n", Name, FontType)
  359. }
  360. break
  361. }
  362. }
  363. }
  364. }
  365. }
  366. // Created so that multiple inputs can be accepted
  367. type arrayFlags []string
  368. func (i *arrayFlags) String() string {
  369. // change this, this example is just to satisfy the interface
  370. result := ""
  371. for _, str := range *i {
  372. if result != "" {
  373. result += ", "
  374. }
  375. result += str
  376. }
  377. return result
  378. }
  379. func (i *arrayFlags) Set(value string) error {
  380. *i = append(*i, strings.TrimSpace(value))
  381. return nil
  382. }
  383. func ParseColorConvert(convert arrayFlags) {
  384. Conversion = make([][2]int, 0)
  385. if len(convert) > 0 {
  386. // Something to do
  387. for _, color := range convert {
  388. split := strings.Split(color, ",")
  389. v1, _ := strconv.Atoi(split[0])
  390. v2, _ := strconv.Atoi(split[1])
  391. Conversion = append(Conversion, [2]int{v1, v2})
  392. }
  393. }
  394. }
  395. /*
  396. I could envision something like this:
  397. https://blog.ralch.com/articles/golang-subcommands/
  398. https://stackoverflow.com/questions/23725924/can-gos-flag-package-print-usage
  399. list (font files)
  400. show -a -f (font files)
  401. extract -all -font -color -package -output (font files)
  402. show - under windows ? :cat_scream:
  403. */
  404. func main() {
  405. var usage func() = func() {
  406. fmt.Println("Usage: font-util <command> [<args>] fontfile.tdf...")
  407. fmt.Println(" list - List available fonts")
  408. fmt.Println(" show - Show fonts")
  409. fmt.Println(" extract - Extract to source.go file")
  410. }
  411. if len(os.Args) == 1 {
  412. usage()
  413. return
  414. }
  415. var fonts string
  416. var defaultPackage string = "main"
  417. var allFonts bool
  418. var convert arrayFlags
  419. var output string
  420. var width int
  421. var listCommand *flag.FlagSet = flag.NewFlagSet("list", flag.ExitOnError)
  422. var showCommand *flag.FlagSet = flag.NewFlagSet("show", flag.ExitOnError)
  423. showCommand.BoolVar(&allFonts, "a", false, "Show All Fonts")
  424. showCommand.StringVar(&fonts, "f", "", "Fonts to Show font1,font2,font3")
  425. showCommand.IntVar(&width, "w", 0, "Width to Show fonts")
  426. var extractCommand *flag.FlagSet = flag.NewFlagSet("extract", flag.ExitOnError)
  427. extractCommand.BoolVar(&allFonts, "a", false, "Extract All Fonts")
  428. extractCommand.StringVar(&fonts, "f", "", "Fonts to Extract font1,font2,font3")
  429. extractCommand.StringVar(&defaultPackage, "p", "main", "Package name to use")
  430. extractCommand.Var(&convert, "c", "Convert Color to Color n,n")
  431. extractCommand.StringVar(&output, "o", "", "Output to file")
  432. switch os.Args[1] {
  433. case "list":
  434. listCommand.Parse(os.Args[2:])
  435. if listCommand.Parsed() {
  436. if len(listCommand.Args()) == 0 {
  437. listCommand.Usage()
  438. fmt.Println("No TDF Font files given.")
  439. os.Exit(2)
  440. }
  441. for _, fontfile := range listCommand.Args() {
  442. ListFonts(fontfile)
  443. }
  444. }
  445. os.Exit(0)
  446. case "show":
  447. showCommand.Parse(os.Args[2:])
  448. case "extract":
  449. extractCommand.Parse(os.Args[2:])
  450. default:
  451. usage()
  452. fmt.Printf("%q is not a valid command.\n", os.Args[1])
  453. os.Exit(2)
  454. }
  455. var fontList []string
  456. if len(fonts) > 0 {
  457. fontList = strings.Split(fonts, ",")
  458. }
  459. if allFonts {
  460. fontList = make([]string, 0)
  461. fontList = append(fontList, "*")
  462. }
  463. var err error
  464. if showCommand.Parsed() {
  465. // Show Fonts
  466. var exit bool
  467. if len(fontList) == 0 {
  468. showCommand.Usage()
  469. fmt.Println("No Fonts selected.")
  470. exit = true
  471. }
  472. if len(showCommand.Args()) == 0 {
  473. if !exit {
  474. showCommand.Usage()
  475. }
  476. fmt.Println("No TDF Fonts files given.")
  477. exit = true
  478. }
  479. if exit {
  480. os.Exit(2)
  481. }
  482. for _, fontfile := range showCommand.Args() {
  483. fmt.Println("FILE:", fontfile)
  484. DisplayFonts(fontfile, fontList, width)
  485. }
  486. }
  487. if extractCommand.Parsed() {
  488. // Extract Fonts
  489. var exit bool
  490. if len(fontList) == 0 {
  491. extractCommand.Usage()
  492. fmt.Println("No Fonts selected.")
  493. exit = true
  494. }
  495. if len(extractCommand.Args()) == 0 {
  496. if !exit {
  497. extractCommand.Usage()
  498. }
  499. fmt.Println("No TDF Fonts files given.")
  500. exit = true
  501. }
  502. if exit {
  503. os.Exit(2)
  504. }
  505. var saveTo *os.File
  506. ParseColorConvert(convert)
  507. // Setup saveTo
  508. if output == "" {
  509. saveTo = os.Stdout
  510. } else {
  511. saveTo, err = os.Create(output)
  512. if err != nil {
  513. fmt.Println("Create", output, "error:", err)
  514. os.Exit(2)
  515. }
  516. }
  517. fmt.Fprintf(saveTo, "package %s\n\n", defaultPackage)
  518. fmt.Fprintf(saveTo, "import (\n\t\"red-green/door\"\n)\n")
  519. for _, fontfile := range extractCommand.Args() {
  520. OutputFonts(saveTo, fontfile, fontList)
  521. }
  522. }
  523. }