1#include "toys.h"
2
3// Insert one stack into another before position in old stack.
4// (Does not copy contents of strings, just shuffles index array contents.)
5void linestack_addstack(struct linestack **lls, struct linestack *throw,
6  long pos)
7{
8  struct linestack *catch = *lls;
9
10  if (CFG_TOYBOX_DEBUG)
11    if (pos > catch->len) error_exit("linestack_addstack past end.");
12
13  // Make a hole, allocating more space if necessary.
14  if (catch->len+throw->len >= catch->max) {
15    // New size rounded up to next multiple of 64, allocate and copy start.
16    catch->max = ((catch->len+throw->len)|63)+1;
17    *lls = xmalloc(sizeof(struct linestack)+catch->max*sizeof(struct ptr_len));
18    memcpy(*lls, catch, sizeof(struct linestack)+pos*sizeof(struct ptr_len));
19  }
20
21  // Copy end (into new allocation if necessary)
22  if (pos != catch->len)
23    memmove((*lls)->idx+pos+throw->len, catch->idx+pos,
24      (catch->len-pos)*sizeof(struct ptr_len));
25
26  // Cleanup if we had to realloc.
27  if (catch != *lls) {
28    free(catch);
29    catch = *lls;
30  }
31
32  memcpy(catch->idx+pos, throw->idx, throw->len*sizeof(struct ptr_len));
33  catch->len += throw->len;
34}
35
36void linestack_insert(struct linestack **lls, long pos, char *line, long len)
37{
38  // alloca() was in 32V and Turbo C for DOS, but isn't in posix or c99.
39  // I'm not thrashing the heap for this, but this should work even if
40  // a broken compiler adds gratuitous padding.
41  struct {
42    struct linestack ls;
43    struct ptr_len pl;
44  } ls;
45
46  ls.ls.len = ls.ls.max = 1;
47  ls.ls.idx[0].ptr = line;
48  ls.ls.idx[0].len = len;
49  linestack_addstack(lls, &ls.ls, pos);
50}
51
52void linestack_append(struct linestack **lls, char *line)
53{
54  linestack_insert(lls, (*lls)->len, line, strlen(line));
55}
56
57struct linestack *linestack_load(char *name)
58{
59  FILE *fp = fopen(name, "r");
60  struct linestack *ls;
61
62  if (!fp) return 0;
63
64  ls = xzalloc(sizeof(struct linestack));
65
66  for (;;) {
67    char *line = 0;
68    ssize_t len;
69
70    if ((len = getline(&line, (void *)&len, fp))<1) break;
71    if (line[len-1]=='\n') len--;
72    linestack_insert(&ls, ls->len, line, len);
73  }
74  fclose(fp);
75
76  return ls;
77}
78
79// Show width many columns, negative means from right edge.
80// If out=0 just measure
81// if escout, send it unprintable chars, returns columns output or -1 for
82// standard escape: ^X if <32, <XX> if invliad UTF8, U+XXXX if UTF8 !iswprint()
83// Returns width in columns, moves *str to end of data consumed.
84int crunch_str(char **str, int width, FILE *out,
85  int (*escout)(FILE *out, int cols, char **buf))
86{
87  int columns = 0, col, bytes;
88  char *start, *end;
89
90  for (end = start = *str; *end;) {
91    wchar_t wc = *end;
92
93    bytes = 0;
94    if (*end >= ' ' && (bytes = mbrtowc(&wc, end, 99,0))>0
95        && (col = wcwidth(wc))>=0)
96    {
97      if (width-columns<col) break;
98      if (out) fwrite(end, bytes, 1, out);
99    } else if (!escout || 0>(col = escout(out, width-columns, &end))) {
100      char buf[32];
101
102      tty_esc("7m");
103      if (*end < ' ') {
104        bytes = 1;
105        sprintf(buf, "^%c", '@'+*end);
106      } else if (bytes<1) {
107        bytes = 1;
108        sprintf(buf, "<%02X>", *end);
109      } else sprintf(buf, "U+%04X", wc);
110      col = strlen(buf);
111      if (width-columns<col) buf[col = width-columns] = 0;
112      if (out) fputs(buf, out);
113      tty_esc("27m");
114    } else continue;
115    columns += col;
116    end += bytes;
117  }
118  *str = end;
119
120  return columns;
121}
122
123// Write width chars at start of string to strdout with standard escapes
124// Returns length in columns so caller can pad it out with spaces.
125int draw_str(char *start, int width)
126{
127  return crunch_str(&start, width, stdout, 0);
128}
129
130// Return utf8 columns
131int utf8len(char *str)
132{
133  return crunch_str(&str, INT_MAX, 0, 0);
134}
135
136// Return bytes used by (up to) this many columns
137int utf8skip(char *str, int width)
138{
139  char *s = str;
140
141  crunch_str(&s, width, 0, 0);
142
143  return s-str;
144}
145
146// Print utf8 to stdout with standard escapes,trimmed to width and padded
147// out to padto. If padto<0 left justify. Returns columns printed
148int draw_trim(char *str, int padto, int width)
149{
150  int apad = abs(padto), len = utf8len(str);
151
152  if (padto<0 && len>width) str += utf8skip(str, len-width);
153  if (len>width) len = width;
154
155  // Left pad if right justified
156  if (padto>0 && apad>len) printf("%*s", apad-len, "");
157  crunch_str(&str, len, stdout, 0);
158  if (padto<0 && apad>len) printf("%*s", apad-len, "");
159
160  return (apad > len) ? apad : len;
161}
162