summaryrefslogtreecommitdiff
path: root/glnx-console.c
blob: c2fe29db0584b1e0780a2d655af9d320737e6f3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
 *
 * Copyright (C) 2013,2014,2015 Colin Walters <walters@verbum.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2 of the licence or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include "glnx-console.h"

#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>

/* For people with widescreen monitors and maximized terminals, it looks pretty
 * bad to have an enormous progress bar. For much the same reason as web pages
 * tend to have a maximum width;
 * https://ux.stackexchange.com/questions/48982/suggest-good-max-width-for-fluid-width-design
 */
#define MAX_PROGRESSBAR_COLUMNS 20

/* Max updates output per second.  On a tty there's no point to rendering
 * extremely fast; and for a non-tty we're probably in a Jenkins job
 * or whatever and having percentages spam multiple lines there is annoying.
 */
#define MAX_TTY_UPDATE_HZ (5)
#define MAX_NONTTY_UPDATE_HZ (1)

static gboolean locked;
static guint64 last_update_ms; /* monotonic time in millis we last updated */

gboolean
glnx_stdout_is_tty (void)
{
  static gsize initialized = 0;
  static gboolean stdout_is_tty_v;

  if (g_once_init_enter (&initialized))
    {
      stdout_is_tty_v = isatty (1);
      g_once_init_leave (&initialized, 1);
    }

  return stdout_is_tty_v;
}

static volatile guint cached_columns = 0;
static volatile guint cached_lines = 0;

static int
fd_columns (int fd)
{
  struct winsize ws = {};

  if (ioctl (fd, TIOCGWINSZ, &ws) < 0)
    return -errno;

  if (ws.ws_col <= 0)
    return -EIO;

  return ws.ws_col;
}

/**
 * glnx_console_columns:
 * 
 * Returns: The number of columns for terminal output
 */
guint
glnx_console_columns (void)
{
  if (G_UNLIKELY (cached_columns == 0))
    {
      int c;

      c = fd_columns (STDOUT_FILENO);

      if (c <= 0)
        c = 80;

      if (c > 256)
        c = 256;

      cached_columns = c;
    }

  return cached_columns;
}

static int
fd_lines (int fd)
{
  struct winsize ws = {};

  if (ioctl (fd, TIOCGWINSZ, &ws) < 0)
    return -errno;

  if (ws.ws_row <= 0)
    return -EIO;

  return ws.ws_row;
}

/**
 * glnx_console_lines:
 * 
 * Returns: The number of lines for terminal output
 */
guint
glnx_console_lines (void)
{
  if (G_UNLIKELY (cached_lines == 0))
    {
      int l;

      l = fd_lines (STDOUT_FILENO);

      if (l <= 0)
        l = 24;

      cached_lines = l;
    }

  return cached_lines;
}

static void
on_sigwinch (int signum)
{
  cached_columns = 0;
  cached_lines = 0;
}

void
glnx_console_lock (GLnxConsoleRef *console)
{
  static gsize sigwinch_initialized = 0;

  g_return_if_fail (!locked);
  g_return_if_fail (!console->locked);

  console->is_tty = glnx_stdout_is_tty ();

  locked = console->locked = TRUE;

  if (console->is_tty)
    {
      if (g_once_init_enter (&sigwinch_initialized))
        {
          signal (SIGWINCH, on_sigwinch);
          g_once_init_leave (&sigwinch_initialized, 1);
        }
      
      { static const char initbuf[] = { 0x1B, 0x37 };
        (void) fwrite (initbuf, 1, sizeof (initbuf), stdout);
      }
    }
}

static void
printpad (const char *padbuf,
          guint       padbuf_len,
          guint       n)
{
  const guint d = n / padbuf_len;
  const guint r = n % padbuf_len;
  guint i;

  for (i = 0; i < d; i++)
    fwrite (padbuf, 1, padbuf_len, stdout);
  fwrite (padbuf, 1, r, stdout);
}

static void
text_percent_internal (const char *text,
                       int percentage)
{
  /* Check whether we're trying to render too fast; unless percentage is 100, in
   * which case we assume this is the last call, so we always render it.
   */
  const guint64 current_ms = g_get_monotonic_time () / 1000;
  if (percentage != 100)
    {
      const guint64 diff_ms = current_ms - last_update_ms;
      if (glnx_stdout_is_tty ())
        {
          if (diff_ms < (1000/MAX_TTY_UPDATE_HZ))
            return;
        }
      else
        {
          if (diff_ms < (1000/MAX_NONTTY_UPDATE_HZ))
            return;
        }
    }
  last_update_ms = current_ms;

  static const char equals[] = "====================";
  const guint n_equals = sizeof (equals) - 1;
  static const char spaces[] = "                    ";
  const guint n_spaces = sizeof (spaces) - 1;
  const guint ncolumns = glnx_console_columns ();
  const guint bar_min = 10;

  if (text && !*text)
    text = NULL;

  const guint input_textlen = text ? strlen (text) : 0;

  if (!glnx_stdout_is_tty ())
    {
      if (text)
        fprintf (stdout, "%s", text);
      if (percentage != -1)
        {
          if (text)
            fputc (' ', stdout);
          fprintf (stdout, "%u%%", percentage);
        }
      fputc ('\n', stdout);
      fflush (stdout);
      return;
    }

  if (ncolumns < bar_min)
    return; /* TODO: spinner */

  /* Restore cursor */
  { const char beginbuf[2] = { 0x1B, 0x38 };
    (void) fwrite (beginbuf, 1, sizeof (beginbuf), stdout);
  }

  if (percentage == -1)
    {
      if (text != NULL)
        fwrite (text, 1, input_textlen, stdout);

      /* Overwrite remaining space, if any */
      if (ncolumns > input_textlen)
        printpad (spaces, n_spaces, ncolumns - input_textlen);
    }
  else
    {
      const guint textlen = MIN (input_textlen, ncolumns - bar_min);
      const guint barlen = MIN (MAX_PROGRESSBAR_COLUMNS, ncolumns - (textlen + 1));

      if (textlen > 0)
        {
          fwrite (text, 1, textlen, stdout);
          fputc (' ', stdout);
        }

      {
        const guint nbraces = 2;
        const guint textpercent_len = 5;
        const guint bar_internal_len = barlen - nbraces - textpercent_len;
        const guint eqlen = bar_internal_len * (percentage / 100.0);
        const guint spacelen = bar_internal_len - eqlen;

        fputc ('[', stdout);
        printpad (equals, n_equals, eqlen);
        printpad (spaces, n_spaces, spacelen);
        fputc (']', stdout);
        fprintf (stdout, " %3d%%", percentage);
      }
    }

  fflush (stdout);
}

/**
 * glnx_console_progress_text_percent:
 * @text: Show this text before the progress bar
 * @percentage: An integer in the range of 0 to 100
 *
 * On a tty, print to the console @text followed by an ASCII art
 * progress bar whose percentage is @percentage.  If stdout is not a
 * tty, a more basic line by line change will be printed.
 *
 * You must have called glnx_console_lock() before invoking this
 * function.
 *
 */
void
glnx_console_progress_text_percent (const char *text,
                                    guint percentage)
{
  g_return_if_fail (percentage <= 100);

  text_percent_internal (text, percentage);
}

/**
 * glnx_console_progress_n_items:
 * @text: Show this text before the progress bar
 * @current: An integer for how many items have been processed
 * @total: An integer for how many items there are total
 *
 * On a tty, print to the console @text followed by [@current/@total],
 * then an ASCII art progress bar, like glnx_console_progress_text_percent().
 *
 * You must have called glnx_console_lock() before invoking this
 * function.
 */
void
glnx_console_progress_n_items (const char     *text,
                               guint           current,
                               guint           total)
{
  g_return_if_fail (current <= total);
  g_return_if_fail (total > 0);

  g_autofree char *newtext = g_strdup_printf ("%s (%u/%u)", text, current, total);
  /* Special case current == total to ensure we end at 100% */
  int percentage = (current == total) ? 100 : (((double)current) / total * 100);
  glnx_console_progress_text_percent (newtext, percentage);
}

void
glnx_console_text (const char *text)
{
  text_percent_internal (text, -1);
}

/**
 * glnx_console_unlock:
 *
 * Print a newline, and reset all cached console progress state.
 *
 * This function does nothing if stdout is not a tty.
 */
void
glnx_console_unlock (GLnxConsoleRef *console)
{
  g_return_if_fail (locked);
  g_return_if_fail (console->locked);

  if (console->is_tty)
    fputc ('\n', stdout);
      
  locked = console->locked = FALSE;
}