File: ui.cc

package info (click to toggle)
monotone 0.31-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 20,680 kB
  • ctags: 14,801
  • sloc: cpp: 87,711; ansic: 64,862; sh: 5,691; lisp: 954; perl: 783; makefile: 509; python: 265; sql: 98; sed: 16
file content (610 lines) | stat: -rw-r--r-- 15,225 bytes parent folder | download
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Copyright (C) 2002 Graydon Hoare <graydon@pobox.com>
//
// This program is made available under the GNU GPL version 2.0 or
// greater. See the accompanying file COPYING for details.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.

// this file contains a couple utilities to deal with the user
// interface. the global user_interface object 'ui' owns clog, so no
// writing to it directly!

#include "config.h"

#include "platform.hh"
#include "sanity.hh"
#include "ui.hh"
#include "charset.hh"
#include "simplestring_xform.hh"
#include "constants.hh"

#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <boost/lexical_cast.hpp>

#include <typeinfo>
#include <cstring>

// Add #ifdeffage here as appropriate for other compiler-specific ways to
// get this information.  Windows note: as best I can determine from poking
// around on MSDN, MSVC type_info.name() is already demangled, and there is
// no documented equivalent of __cxa_current_exception_type().
#ifdef HAVE_CXXABI_H
 #include <cxxabi.h>
 #ifdef HAVE___CXA_DEMANGLE
  inline char const * demangle_typename(char const * name)
  {
    int status = -1;
    char * dem = abi::__cxa_demangle(name, 0, 0, &status);
    if (status == 0)
      return dem;
    else
      return 0;
  }
 #else
  #define demangle_typename(x) 0
 #endif
 #ifdef HAVE___CXA_CURRENT_EXCEPTION_TYPE
  #define get_current_exception_type() abi::__cxa_current_exception_type()
 #else
  #define get_current_exception_type() 0
 #endif
#else
 #define demangle_typename(x) 0
 #define get_current_exception_type() 0
#endif

using std::clog;
using std::cout;
using std::endl;
using std::ios_base;
using std::locale;
using std::make_pair;
using std::map;
using std::max;
using std::ofstream;
using std::string;
using std::vector;

using boost::lexical_cast;

struct user_interface ui;

ticker::ticker(string const & tickname, string const & s, size_t mod,
    bool kilocount) :
  ticks(0),
  mod(mod),
  total(0),
  previous_total(0),
  kilocount(kilocount),
  use_total(false),
  keyname(tickname),
  name(_(tickname.c_str())),
  shortname(s),
  count_size(0)
{
  I(ui.tickers.find(keyname) == ui.tickers.end());
  ui.tickers.insert(make_pair(keyname, this));
}

ticker::~ticker()
{
  I(ui.tickers.find(keyname) != ui.tickers.end());
  if (ui.some_tick_is_dirty)
    {
      ui.write_ticks();
    }
  ui.tickers.erase(keyname);
  ui.finish_ticking();
}

void
ticker::operator++()
{
  I(ui.tickers.find(keyname) != ui.tickers.end());
  ticks++;
  ui.some_tick_is_dirty = true;
  if (ticks % mod == 0)
    ui.write_ticks();
}

void
ticker::operator+=(size_t t)
{
  I(ui.tickers.find(keyname) != ui.tickers.end());
  size_t old = ticks;

  ticks += t;
  if (t != 0)
    {
      ui.some_tick_is_dirty = true;
      if (ticks % mod == 0 || (ticks / mod) > (old / mod))
        ui.write_ticks();
    }
}


tick_write_count::tick_write_count() : last_tick_len(0)
{
}

tick_write_count::~tick_write_count()
{
}

static string compose_count(ticker *tick, size_t ticks=0)
{
  string count;

  if (ticks == 0)
    {
      ticks = tick->ticks;
    }

  if (tick->kilocount && ticks)
    {
      // automatic unit conversion is enabled
      float div = 1.0;
      const char *message;

      if (ticks >= 1073741824)
        {
          div = 1073741824;
          // xgettext: gibibytes (2^30 bytes)
          message = N_("%.1f G");
        }
      else if (ticks >= 1048576)
        {
          div = 1048576;
          // xgettext: mebibytes (2^20 bytes)
          message = N_("%.1f M");
        }
      else if (ticks >= 1024)
        {
          div = 1024;
          // xgettext: kibibytes (2^10 bytes)
          message = N_("%.1f k");
        }
      else
        {
          div = 1;
          message = "%.0f";
        }
      // We reset the mod to the divider, to avoid spurious screen updates.
      tick->mod = max(static_cast<int>(div / 10.0), 1);
      count = (F(message) % (ticks / div)).str();
    }
  else if (tick->use_total)
    {
      count = (F("%d/%d") % ticks % tick->total).str();
    }
  else
    {
      // xgettext: bytes
      count = (F("%d") % ticks).str();
    }

  return count;
}

void tick_write_count::write_ticks()
{
  vector<size_t> tick_widths;
  vector<string> tick_title_strings;
  vector<string> tick_count_strings;

  for (map<string,ticker *>::const_iterator i = ui.tickers.begin();
       i != ui.tickers.end(); ++i)
    {
      ticker * tick = i->second;

      if ((tick->count_size == 0 && tick->kilocount)
          ||
          (tick->use_total && tick->previous_total != tick->total))
        {
          if (!tick->kilocount && tick->use_total)
            {
              // We know that we're going to eventually have 'total'
              // displayed twice on screen, plus a slash. So we should
              // pad out this field to that eventual size to avoid
              // spurious re-issuing of the tick titles as we expand to
              // the goal.
              tick->set_count_size(display_width(utf8(compose_count(tick,
                                                                    tick->total))));
              tick->previous_total = tick->total;
            }
          else
            {
              // To find out what the maximum size can be, choose one the
              // the dividers from compose_count, subtract one and have
              // compose_count create the count string for that.  Use the
              // size of the returned count string as an initial size for
              // this tick.
              tick->set_count_size(display_width(utf8(compose_count(tick,
                                                                    1048575))));
            }
        }

      string count(compose_count(tick));

      size_t title_width = display_width(utf8(tick->name));
      size_t count_width = display_width(utf8(count));

      if (count_width > tick->count_size)
        {
          tick->set_count_size(count_width);
        }

      size_t max_width = max(title_width, tick->count_size);

      string name;
      name.append(max_width - title_width, ' ');
      name.append(tick->name);

      string count2;
      count2.append(max_width - count_width, ' ');
      count2.append(count);

      tick_title_strings.push_back(name);
      tick_count_strings.push_back(count2);
      tick_widths.push_back(max_width);
    }

  string tickline1;
  bool write_tickline1 = !(ui.last_write_was_a_tick
                           && (tick_widths == last_tick_widths));
  if (write_tickline1)
    {
      // Reissue the titles if the widths have changed.
      tickline1 = ui.output_prefix();
      for (size_t i = 0; i < tick_widths.size(); ++i)
        {
          if (i != 0)
            tickline1.append(" | ");
          tickline1.append(idx(tick_title_strings, i));
        }
      last_tick_widths = tick_widths;
      write_tickline1 = true;
    }

  // Always reissue the counts.
  string tickline2 = ui.output_prefix();
  for (size_t i = 0; i < tick_widths.size(); ++i)
    {
      if (i != 0)
        tickline2.append(" | ");
      tickline2.append(idx(tick_count_strings, i));
    }

  if (!ui.tick_trailer.empty())
    {
      tickline2 += " ";
      tickline2 += ui.tick_trailer;
    }

  size_t curr_sz = display_width(utf8(tickline2));
  if (curr_sz < last_tick_len)
    tickline2.append(last_tick_len - curr_sz, ' ');
  last_tick_len = curr_sz;

  unsigned int tw = terminal_width();
  if(write_tickline1)
    {
      if (ui.last_write_was_a_tick)
        clog << "\n";

      if (tw && display_width(utf8(tickline1)) > tw)
        {
          // FIXME: may chop off more than necessary (because we chop by
          // bytes, not by characters)
          tickline1.resize(tw);
        }
      clog << tickline1 << "\n";
    }
  if (tw && display_width(utf8(tickline2)) > tw)
    {
      // FIXME: may chop off more than necessary (because we chop by
      // bytes, not by characters)
      tickline2.resize(tw);
    }
  clog << "\r" << tickline2;
  clog.flush();
}

void tick_write_count::clear_line()
{
  clog << endl;
}


tick_write_dot::tick_write_dot()
{
}

tick_write_dot::~tick_write_dot()
{
}

void tick_write_dot::write_ticks()
{
  static const string tickline_prefix = ui.output_prefix();
  string tickline1, tickline2;
  bool first_tick = true;

  if (ui.last_write_was_a_tick)
    {
      tickline1 = "";
      tickline2 = "";
    }
  else
    {
      tickline1 = ui.output_prefix() + "ticks: ";
      tickline2 = "\n" + tickline_prefix;
      chars_on_line = tickline_prefix.size();
    }

  for (map<string,ticker *>::const_iterator i = ui.tickers.begin();
       i != ui.tickers.end(); ++i)
    {
      map<string,size_t>::const_iterator old = last_ticks.find(i->first);

      if (!ui.last_write_was_a_tick)
        {
          if (!first_tick)
            tickline1 += ", ";

          tickline1 +=
            i->second->shortname + "=\"" + i->second->name + "\""
            + "/" + lexical_cast<string>(i->second->mod);
          first_tick = false;
        }

      if (old == last_ticks.end()
          || ((i->second->ticks / i->second->mod)
              > (old->second / i->second->mod)))
        {
          chars_on_line += i->second->shortname.size();
          if (chars_on_line > guess_terminal_width())
            {
              chars_on_line = tickline_prefix.size() + i->second->shortname.size();
              tickline2 += "\n" + tickline_prefix;
            }
          tickline2 += i->second->shortname;

          if (old == last_ticks.end())
            last_ticks.insert(make_pair(i->first, i->second->ticks));
          else
            last_ticks[i->first] = i->second->ticks;
        }
    }

  clog << tickline1 << tickline2;
  clog.flush();
}

void tick_write_dot::clear_line()
{
  clog << endl;
}

// user_interface has both constructor/destructor and initialize/
// deinitialize because there's only one of these objects, it's
// global, and we don't want global constructors/destructors doing
// any real work.  see monotone.cc for how this is handled.

user_interface::user_interface() :
  prog_name("?"),
  last_write_was_a_tick(false),
  t_writer(0)
{}

void user_interface::initialize()
{
  cout.exceptions(ios_base::badbit);
#ifdef SYNC_WITH_STDIO_WORKS
  clog.sync_with_stdio(false);
#endif
  clog.unsetf(ios_base::unitbuf);
  if (have_smart_terminal())
    set_tick_writer(new tick_write_count);
  else
    set_tick_writer(new tick_write_dot);
}

user_interface::~user_interface()
{}

void user_interface::deinitialize()
{
  delete t_writer;
}

void
user_interface::finish_ticking()
{
  if (tickers.size() == 0 &&
      last_write_was_a_tick)
    {
      tick_trailer = "";
      t_writer->clear_line();
      last_write_was_a_tick = false;
    }
}

void
user_interface::set_tick_trailer(string const & t)
{
  tick_trailer = t;
}

void
user_interface::set_tick_writer(tick_writer * t)
{
  if (t_writer != 0)
    delete t_writer;
  t_writer = t;
}

void
user_interface::write_ticks()
{
  t_writer->write_ticks();
  last_write_was_a_tick = true;
  some_tick_is_dirty = false;
}

void
user_interface::warn(string const & warning)
{
  if (issued_warnings.find(warning) == issued_warnings.end())
    {
      string message;
      prefix_lines_with(_("warning: "), warning, message);
      inform(message);
    }
  issued_warnings.insert(warning);
}

// this message should be kept consistent with unix/main.cc and
// win32/main.cc ::bug_report_message (it is not exactly the same)
void
user_interface::fatal(string const & fatal)
{
  inform(F("fatal: %s\n"
           "this is almost certainly a bug in monotone.\n"
           "please send this error message, the output of '%s --full-version',\n"
           "and a description of what you were doing to %s.")
         % fatal % prog_name % PACKAGE_BUGREPORT);
  global_sanity.dump_buffer();
}

// Report what we can about a fatal exception (caught in the outermost catch
// handlers) which is from the std::exception hierarchy.  In this case we
// can access the exception object.
void
user_interface::fatal_exception(std::exception const & ex)
{
  using std::strcmp;
  using std::strncmp;
  char const * ex_name = typeid(ex).name();
  char const * ex_dem  = demangle_typename(ex_name);
  char const * ex_what = ex.what();

  if (ex_dem == 0)
    ex_dem = ex_name;

  // some demanglers stick "class" at the beginning of their output,
  // which looks dumb in this context
  if (!strncmp(ex_dem, "class ", 6))
    ex_dem += 6;

  // only print what() if it's interesting, i.e. nonempty and different
  // from the name (mangled or otherwise) of the exception type.
  if (ex_what == 0 || ex_what[0] == 0
      || !strcmp(ex_what, ex_name)
      || !strcmp(ex_what, ex_dem))
    this->fatal(ex_dem);
  else
    this->fatal(i18n_format("%s: %s") % ex_dem % ex_what);
}

// Report what we can about a fatal exception (caught in the outermost catch
// handlers) which is of unknown type.  If we have the <cxxabi.h> interfaces,
// we can at least get the type_info object.
void
user_interface::fatal_exception()
{
  std::type_info *ex_type = get_current_exception_type();
  if (ex_type)
    {
      char const * ex_name = ex_type->name();
      char const * ex_dem  = demangle_typename(ex_name);
      if (ex_dem == 0)
        ex_dem = ex_name;
      this->fatal(ex_dem);
    }
  else
    this->fatal("exception of unknown type");
}

string
user_interface::output_prefix()
{
  if (prog_name.empty()) {
    return "?: ";
  }
  return prog_name + ": ";
}

static inline string
sanitize(string const & line)
{
  // FIXME: you might want to adjust this if you're using a charset
  // which has safe values in the sub-0x20 range. ASCII, UTF-8,
  // and most ISO8859-x sets do not.
  string tmp;
  tmp.reserve(line.size());
  for (size_t i = 0; i < line.size(); ++i)
    {
      if ((line[i] == '\n')
          || (static_cast<unsigned char>(line[i]) >= static_cast<unsigned char>(0x20)
              && line[i] != static_cast<char>(0x7F)))
        tmp += line[i];
      else
        tmp += ' ';
    }
  return tmp;
}

void
user_interface::ensure_clean_line()
{
  if (last_write_was_a_tick)
    {
      write_ticks();
      t_writer->clear_line();
    }
  last_write_was_a_tick = false;
}

void
user_interface::redirect_log_to(system_path const & filename)
{
  static ofstream filestr;
  if (filestr.is_open())
    filestr.close();
  filestr.open(filename.as_external().c_str(), ofstream::out | ofstream::app);
  E(filestr.is_open(), F("failed to open log file '%s'") % filename);
  clog.rdbuf(filestr.rdbuf());
}

void
user_interface::inform(string const & line)
{
  string prefixedLine;
  prefix_lines_with(output_prefix(), line, prefixedLine);
  ensure_clean_line();
  clog << sanitize(prefixedLine) << endl;
  clog.flush();
}

unsigned int
guess_terminal_width()
{
  unsigned int w = terminal_width();
  if (!w)
    w = constants::default_terminal_width;
  return w;
}

// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s: