utils.py
Go to the documentation of this file.
1 # -*- Python -*-
2 # -*- coding: utf-8 -*-
3 
4 '''rtctree
5 
6 Copyright (C) 2009-2014
7  Geoffrey Biggs
8  RT-Synthesis Research Group
9  Intelligent Systems Research Institute,
10  National Institute of Advanced Industrial Science and Technology (AIST),
11  Japan
12  All rights reserved.
13 Licensed under the Eclipse Public License -v 1.0 (EPL)
14 http://www.opensource.org/licenses/eclipse-1.0.txt
15 
16 Objects and functions used to build and store a tree representing a hierarchy
17 of name servers, directories, managers and components.
18 
19 '''
20 
21 
22 from omniORB import any
23 import SDOPackage
24 import sys
25 
26 
27 
29 
30 
31 term_attributes = {'reset': '00',
32  'bold': '01',
33  'faint': '02',
34  'underline': '04',
35  'blink': '05',
36  'blinkfast': '06',
37  'negative': '07',
38  'normal': '22',
39  'nounderline': '24',
40  'noblink': '25',
41  'positive': '27',
42  'black': '30',
43  'red': '31',
44  'green': '32',
45  'brown': '33',
46  'blue': '34',
47  'purple': '35',
48  'cyan': '36',
49  'white': '37',
50  'bgblack': '40',
51  'bgred': '41',
52  'bggreen': '42',
53  'bgbrown': '43',
54  'bgblue': '44',
55  'bgpurple': '45',
56  'bgcyan': '46',
57  'bgwhite': '47',
58  }
59 
60 from traceback import extract_stack
61 
62 def build_attr_string(attrs, supported=True):
63  '''Build a string that will turn any ANSI shell output the desired
64  colour.
65 
66  attrs should be a list of keys into the term_attributes table.
67 
68  '''
69  if not supported:
70  return ''
71  if type(attrs) == str:
72  attrs = [attrs]
73  result = '\033['
74  for attr in attrs:
75  result += term_attributes[attr] + ';'
76  return result[:-1] + 'm'
77 
78 
79 def colour_supported(term):
80  if sys.platform == 'win32':
81  return False
82  return term.isatty()
83 
84 
85 def get_num_columns_and_rows(widths, gap_width, term_width):
86  '''Given a list of string widths, a width of the minimum gap to place
87  between them, and the maximum width of the output (such as a terminal
88  width), calculate the number of columns and rows, and the width of each
89  column, for the optimal layout.
90 
91  '''
92  def calc_longest_width(widths, gap_width, ncols):
93  longest = 0
94  rows = [widths[s:s + ncols] for s in range(0, len(widths), ncols)]
95  col_widths = rows[0] # Column widths start at the first row widths
96  for r in rows:
97  for ii, c in enumerate(r):
98  if c > col_widths[ii]:
99  col_widths[ii] = c
100  length = sum(col_widths) + gap_width * (ncols - 1)
101  if length > longest:
102  longest = length
103  return longest, col_widths
104 
105  def calc_num_rows(num_items, cols):
106  div, mod = divmod(num_items, cols)
107  return div + (mod != 0)
108 
109  # Start with one row
110  ncols = len(widths)
111  # Calculate the width of the longest row as the longest set of item widths
112  # ncols long and gap widths (gap_width * ncols - 1) that fits within the
113  # terminal width.
114  while ncols > 0:
115  longest_width, col_widths = calc_longest_width(widths, gap_width, ncols)
116  if longest_width < term_width:
117  # This number of columns fits
118  return calc_num_rows(len(widths), ncols), ncols, col_widths
119  else:
120  # This number of columns doesn't fit, so try one less
121  ncols -= 1
122  # If got here, it all has to go in one column
123  return len(widths), 1, 0
124 
125 
127  '''Finds the width of the terminal, or returns a suitable default value.'''
128  def read_terminal_size_by_ioctl(fd):
129  try:
130  import struct, fcntl, termios
131  cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ,
132  '0000'))
133  except ImportError:
134  return None
135  except IOError, e:
136  return None
137  return cr[1], cr[0]
138 
139  cr = read_terminal_size_by_ioctl(0) or \
140  read_terminal_size_by_ioctl(1) or \
141  read_terminal_size_by_ioctl(2)
142  if not cr:
143  try:
144  import os
145  fd = os.open(os.ctermid(), os.O_RDONLY)
146  cr = read_terminal_size_by_ioctl(fd)
147  os.close(fd)
148  except:
149  pass
150  if not cr:
151  import os
152  cr = [80, 25] # 25 rows, 80 columns is the default value
153  if os.getenv('ROWS'):
154  cr[1] = int(os.getenv('ROWS'))
155  if os.getenv('COLUMNS'):
156  cr[0] = int(os.getenv('COLUMNS'))
157 
158  return cr[1], cr[0]
159 
160 
161 def dict_to_nvlist(dict):
162  '''Convert a dictionary into a CORBA namevalue list.'''
163  result = []
164  for item in dict.keys() :
165  result.append(SDOPackage.NameValue(item, any.to_any(dict[item])))
166  return result
167 
168 
169 def nvlist_to_dict(nvlist):
170  '''Convert a CORBA namevalue list into a dictionary.'''
171  result = {}
172  for item in nvlist :
173  result[item.name] = item.value.value()
174  return result
175 
176 
177 def filtered(path, filter):
178  '''Check if a path is removed by a filter.
179 
180  Check if a path is in the provided set of paths, @ref filter. If
181  none of the paths in filter begin with @ref path, then True is
182  returned to indicate that the path is filtered out. If @ref path is
183  longer than the filter, and starts with the filter, it is
184  considered unfiltered (all paths below a filter are unfiltered).
185 
186  An empty filter ([]) is treated as not filtering any.
187 
188  '''
189  if not filter:
190  return False
191  for p in filter:
192  if len(path) > len(p):
193  if path[:len(p)] == p:
194  return False
195  else:
196  if p[:len(path)] == path:
197  return False
198  return True
199 
200 
201 def trim_filter(filter, levels=1):
202  '''Trim @ref levels levels from the front of each path in @filter.'''
203  trimmed = [f[levels:] for f in filter]
204  return [f for f in trimmed if f]
205 
206 
207 # vim: tw=79
208 
def colour_supported(term)
Definition: utils.py:79
def trim_filter(filter, levels=1)
Definition: utils.py:201
def filtered(path, filter)
Definition: utils.py:177
def get_num_columns_and_rows(widths, gap_width, term_width)
Definition: utils.py:85
def build_attr_string(attrs, supported=True)
Definition: utils.py:62
def dict_to_nvlist(dict)
Definition: utils.py:161
def get_terminal_size()
Definition: utils.py:126
def nvlist_to_dict(nvlist)
Definition: utils.py:169


rtctree
Author(s): Geoffrey Biggs
autogenerated on Mon Feb 28 2022 23:39:40