ansi-print.cc revision ff0f210519bcb0e44d4b986f7eef2004383cd344
1/*
2 * Copyright © 2012  Google, Inc.
3 *
4 *  This is part of HarfBuzz, a text shaping library.
5 *
6 * Permission is hereby granted, without written agreement and without
7 * license or royalty fees, to use, copy, modify, and distribute this
8 * software and its documentation for any purpose, provided that the
9 * above copyright notice and the following two paragraphs appear in
10 * all copies of this software.
11 *
12 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16 * DAMAGE.
17 *
18 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23 *
24 * Google Author(s): Behdad Esfahbod
25 */
26
27#ifdef HAVE_CONFIG_H
28#include "config.h"
29#endif
30
31#include "ansi-print.hh"
32
33#include <assert.h>
34#include <stdlib.h>
35#include <stddef.h>
36#include <string.h>
37#include <stdio.h>
38#include <math.h>
39#include <fcntl.h>
40#ifdef HAVE_UNISTD_H
41#include <unistd.h> /* for isatty() */
42#endif
43
44#ifdef _MSC_VER
45static inline long int
46lround (double x)
47{
48  if (x >= 0)
49    return floor (x + 0.5);
50  else
51    return ceil (x - 0.5);
52}
53#endif
54
55#define MIN(a,b) ((a) < (b) ? (a) : (b))
56
57#define CELL_W 8
58#define CELL_H (2 * CELL_W)
59
60struct color_diff_t
61{
62  int dot (const color_diff_t &o)
63  { return v[0]*o.v[0] + v[1]*o.v[1] + v[2]*o.v[2] + v[3]*o.v[3]; }
64
65  int v[4];
66};
67
68struct color_t
69{
70  static color_t from_ansi (unsigned int x)
71  {
72    color_t c = {(0xFF<<24) | ((0xFF*(x&1))<<16) | ((0xFF*((x >> 1)&1))<<8) | (0xFF*((x >> 2)&1))};
73    return c;
74  }
75  unsigned int to_ansi (void)
76  {
77    return ((v >> 23) & 1) | ((v >> 14)&2) | ((v >> 5)&4);
78  }
79
80  color_diff_t diff (const color_t &o)
81  {
82    color_diff_t d;
83    for (unsigned int i = 0; i < 4; i++)
84      d.v[i] = (int) ((v >> (i*8))&0xFF) - (int) ((o.v >> (i*8))&0xFF);
85    return d;
86  }
87
88  uint32_t v;
89};
90
91struct image_t
92{
93  public:
94
95  image_t (unsigned int width_,
96	   unsigned int height_,
97	   const uint32_t *data_,
98	   unsigned int stride_) :
99		width (width_),
100		height (height_),
101		own_data (false),
102		data ((color_t *) data_),
103		stride (stride_) {}
104  image_t (unsigned int width_,
105	   unsigned int height_) :
106		width (width_),
107		height (height_),
108		own_data (true),
109		data ((color_t *) malloc (sizeof (data[0]) * width * height)),
110		stride (width) {}
111  ~image_t (void)
112  { if (own_data) free (data); }
113
114  color_t &operator () (unsigned int x, unsigned int y)
115  { return data[x + y * stride]; }
116
117  color_t operator () (unsigned int x, unsigned int y) const
118  { return data[x + y * stride]; }
119
120  void
121  copy_sub_image (const image_t &s,
122		  unsigned int x, unsigned int y,
123		  unsigned int w, unsigned int h)
124  {
125    assert (x < width);
126    assert (y < height);
127    for (unsigned int row = 0; row < h; row++) {
128      color_t *p = data + x + MIN (y + row, height - 1) * stride;
129      color_t *q = s.data + row * s.stride;
130      if (x + w <= width)
131	for (unsigned int col = 0; col < w; col++)
132	  *q++ = *p++;
133      else {
134        unsigned int limit = width - x;
135	for (unsigned int col = 0; col < limit; col++)
136	  *q++ = *p++;
137	p--;
138	for (unsigned int col = limit; col < w; col++)
139	  *q++ = *p;
140      }
141    }
142  }
143
144  const unsigned int width;
145  const unsigned int height;
146
147  private:
148  bool own_data;
149  color_t * const data;
150  const unsigned int stride;
151};
152
153struct biimage_t
154{
155  public:
156
157  biimage_t (unsigned int width, unsigned int height) :
158		width (width),
159		height (height),
160		bg (0), fg (0), unicolor (true),
161		data ((uint8_t *) malloc (sizeof (data[0]) * width * height)) {}
162  ~biimage_t (void)
163  { free (data); }
164
165  void set (const image_t &image)
166  {
167    assert (image.width == width);
168    assert (image.height == height);
169    int freq[8] = {0};
170    for (unsigned int y = 0; y < height; y++)
171      for (unsigned int x = 0; x < width; x++) {
172        color_t c = image (x, y);
173        freq[c.to_ansi ()]++;
174      }
175    bg = 0;
176    for (unsigned int i = 1; i < 8; i++)
177      if (freq[bg] < freq[i])
178        bg = i;
179    fg = 0;
180    for (unsigned int i = 1; i < 8; i++)
181      if (i != bg && freq[fg] < freq[i])
182        fg = i;
183    if (fg == bg || freq[fg] == 0) {
184      fg = bg;
185      unicolor = true;
186    }
187    else
188      unicolor = false;
189
190    /* Set the data... */
191
192    if (unicolor) {
193      memset (data, 0, sizeof (data[0]) * width * height);
194      return;
195    }
196
197    color_t bgc = color_t::from_ansi (bg);
198    color_t fgc = color_t::from_ansi (fg);
199    color_diff_t diff = fgc.diff (bgc);
200    int dd = diff.dot (diff);
201    for (unsigned int y = 0; y < height; y++)
202      for (unsigned int x = 0; x < width; x++) {
203        int d = diff.dot (image (x, y).diff (bgc));
204	(*this)(x, y) = d < 0 ? 0 : d > dd ? 255 : lround (d * 255. / dd);
205      }
206  }
207
208  uint8_t &operator () (unsigned int x, unsigned int y)
209  { return data[x + y * width]; }
210
211  uint8_t operator () (unsigned int x, unsigned int y) const
212  { return data[x + y * width]; }
213
214  const unsigned int width;
215  const unsigned int height;
216  unsigned int bg;
217  unsigned int fg;
218  bool unicolor;
219
220  private:
221  uint8_t * const data;
222};
223
224const char *
225block_best (const biimage_t &bi, bool *inverse)
226{
227  assert (bi.width  <= CELL_W);
228  assert (bi.height <= CELL_H);
229
230  unsigned int score = (unsigned int) -1;
231  unsigned int row_sum[CELL_H] = {0};
232  unsigned int col_sum[CELL_W] = {0};
233  unsigned int row_sum_i[CELL_H] = {0};
234  unsigned int col_sum_i[CELL_W] = {0};
235  unsigned int quad[2][2] = {{0}};
236  unsigned int quad_i[2][2] = {{0}};
237  unsigned int total = 0;
238  unsigned int total_i = 0;
239  for (unsigned int y = 0; y < bi.height; y++)
240    for (unsigned int x = 0; x < bi.width; x++) {
241      unsigned int c = bi (x, y);
242      unsigned int c_i = 255 - c;
243      row_sum[y] += c;
244      row_sum_i[y] += c_i;
245      col_sum[x] += c;
246      col_sum_i[x] += c_i;
247      quad[2 * y / bi.height][2 * x / bi.width] += c;
248      quad_i[2 * y / bi.height][2 * x / bi.width] += c_i;
249      total += c;
250      total_i += c_i;
251    }
252
253  /* Make the sums cummulative */
254  for (unsigned int i = 1; i < bi.height; i++) {
255    row_sum[i] += row_sum[i - 1];
256    row_sum_i[i] += row_sum_i[i - 1];
257  }
258  for (unsigned int i = 1; i < bi.width;  i++) {
259    col_sum[i] += col_sum[i - 1];
260    col_sum_i[i] += col_sum_i[i - 1];
261  }
262
263  const char *best_c = " ";
264
265  /* Maybe empty is better! */
266  if (total < score) {
267    score = total;
268    *inverse = false;
269    best_c = " ";
270  }
271  /* Maybe full is better! */
272  if (total_i < score) {
273    score = total_i;
274    *inverse = true;
275    best_c = " ";
276  }
277
278  /* Find best lower line */
279  if (1) {
280    unsigned int best_s = (unsigned int) -1;
281    bool best_inv = false;
282    int best_i = 0;
283    for (unsigned int i = 0; i < bi.height - 1; i++)
284    {
285      unsigned int s;
286      s = row_sum[i] + total_i - row_sum_i[i];
287      if (s < best_s) {
288        best_s = s;
289	best_i = i;
290	best_inv = false;
291      }
292      s = row_sum_i[i] + total - row_sum[i];
293      if (s < best_s) {
294        best_s = s;
295	best_i = i;
296	best_inv = true;
297      }
298    }
299    if (best_s < score) {
300      static const char *lower[7] = {"▁", "▂", "▃", "▄", "▅", "▆", "▇"};
301      unsigned int which = lround (((best_i + 1) * 8) / bi.height);
302      if (1 <= which && which <= 7) {
303	score = best_s;
304	*inverse = best_inv;
305	best_c = lower[7 - which];
306      }
307    }
308  }
309
310  /* Find best left line */
311  if (1) {
312    unsigned int best_s = (unsigned int) -1;
313    bool best_inv = false;
314    int best_i = 0;
315    for (unsigned int i = 0; i < bi.width - 1; i++)
316    {
317      unsigned int s;
318      s = col_sum[i] + total_i - col_sum_i[i];
319      if (s < best_s) {
320        best_s = s;
321	best_i = i;
322	best_inv = true;
323      }
324      s = col_sum_i[i] + total - col_sum[i];
325      if (s < best_s) {
326        best_s = s;
327	best_i = i;
328	best_inv = false;
329      }
330    }
331    if (best_s < score) {
332      static const char *left [7] = {"▏", "▎", "▍", "▌", "▋", "▊", "▉"};
333      unsigned int which = lround (((best_i + 1) * 8) / bi.width);
334      if (1 <= which && which <= 7) {
335	score = best_s;
336	*inverse = best_inv;
337	best_c = left[which - 1];
338      }
339    }
340  }
341
342  /* Find best quadrant */
343  if (1) {
344    unsigned int q = 0;
345    unsigned int qs = 0;
346    for (unsigned int i = 0; i < 2; i++)
347      for (unsigned int j = 0; j < 2; j++)
348	if (quad[i][j] > quad_i[i][j]) {
349	  q += 1 << (2 * i + j);
350	  qs += quad_i[i][j];
351	} else
352	  qs += quad[i][j];
353    if (qs < score) {
354      const char *c = NULL;
355      bool inv = false;
356      switch (q) {
357	case 1:  c = "▟"; inv = true;  break;
358	case 2:  c = "▙"; inv = true;  break;
359	case 4:  c = "▖"; inv = false; break;
360	case 8:  c = "▗"; inv = false; break;
361	case 9:  c = "▚"; inv = false; break;
362	case 6:  c = "▞"; inv = false; break;
363	case 7:  c = "▜"; inv = true;  break;
364	case 11: c = "▜"; inv = true;  break;
365	case 13: c = "▙"; inv = true;  break;
366	case 14: c = "▟"; inv = true;  break;
367      }
368      if (c) {
369	score = qs;
370	*inverse = inv;
371	best_c = c;
372      }
373    }
374  }
375
376  return best_c;
377}
378
379void
380ansi_print_image_rgb24 (const uint32_t *data,
381			unsigned int width,
382			unsigned int height,
383			unsigned int stride)
384{
385  image_t image (width, height, data, stride);
386
387  unsigned int rows = (height + CELL_H - 1) / CELL_H;
388  unsigned int cols = (width +  CELL_W - 1) / CELL_W;
389  image_t cell (CELL_W, CELL_H);
390  biimage_t bi (CELL_W, CELL_H);
391  unsigned int last_bg = -1, last_fg = -1;
392  for (unsigned int row = 0; row < rows; row++) {
393    for (unsigned int col = 0; col < cols; col++) {
394      image.copy_sub_image (cell, col * CELL_W, row * CELL_H, CELL_W, CELL_H);
395      bi.set (cell);
396      if (bi.unicolor) {
397        if (last_bg != bi.bg) {
398	  printf ("\e[%dm", 40 + bi.bg);
399	  last_bg = bi.bg;
400	}
401	printf (" ");
402      } else {
403        /* Figure out the closest character to the biimage */
404	bool inverse = false;
405        const char *c = block_best (bi, &inverse);
406	if (inverse) {
407	  if (last_bg != bi.fg || last_fg != bi.bg) {
408	    printf ("\e[%d;%dm", 30 + bi.bg, 40 + bi.fg);
409	    last_bg = bi.fg;
410	    last_fg = bi.bg;
411	  }
412	} else {
413	  if (last_bg != bi.bg || last_fg != bi.fg) {
414	    printf ("\e[%d;%dm", 40 + bi.bg, 30 + bi.fg);
415	    last_bg = bi.bg;
416	    last_fg = bi.fg;
417	  }
418	}
419	printf ("%s", c);
420      }
421    }
422    printf ("\e[0m\n"); /* Reset */
423    last_bg = last_fg = -1;
424  }
425}
426