font-out.go 13 KB

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