Update copyright years
[pysize.git] / pysize / ui / utils.py
blob8286bfc3ea6b5f13b84fb89e6472f3dc767e43c1
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2006, 2007, 2008 Guillaume Chazarain <guichaz@yahoo.fr>
19 import re
20 import time
22 UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
24 def human_unit(size):
25 """Return a string of the form '12.34 MiB' given a size in bytes."""
26 for i in xrange(len(UNITS) - 1, 0, -1):
27 base = 1 << (10 * i)
28 if 2 * base < size:
29 return '%.2f %s' % ((float(size) / base), UNITS[i])
30 return str(size) + ' ' + UNITS[0]
32 def sanitize_string(string, max_length=None):
33 try:
34 decoded = string.decode('UTF-8')
35 except UnicodeDecodeError:
36 def robust_char_decode(c):
37 try:
38 return c.decode('UTF-8')
39 except UnicodeDecodeError:
40 return '?'
41 decoded = ''.join(map(robust_char_decode, string))
42 if max_length is not None and len(decoded) > max_length:
43 nr_dots = max(0, min(3, max_length - 1))
44 decoded = decoded[:max_length - nr_dots] + '.' * nr_dots
45 for c in decoded:
46 if c.isspace() and c != ' ':
47 def clean_blank(c):
48 if c.isspace() and c != ' ':
49 c = '?'
50 return c
51 return ''.join(map(clean_blank, decoded))
52 return decoded
54 PROGRESS_CHARS = ['/', '-', '\\', '|']
55 last_progress_char = 0
56 last_progress_time = time.time()
58 def update_progress():
59 global last_progress_char, last_progress_time
60 now = time.time()
61 if now - last_progress_time > 0.04:
62 last_progress_char = (last_progress_char + 1) % len(PROGRESS_CHARS)
63 last_progress_time = now
64 return PROGRESS_CHARS[last_progress_char]
66 class UINotAvailableException(Exception):
67 pass