Creates a nice readily printable Table for a list of modes.
            Used in `displays list' and the candidates list
            in `displays set'.

def format_modes(modes, full_modes=False, current_mode=None):
        """ Creates a nice readily printable Table for a list of modes.
            Used in `displays list' and the candidates list
            in `displays set'. """
        t = table.Table(((
                '*' if mode == current_mode else '',                         # 0
                str(Q.CGDisplayModeGetWidth(mode)),                          # 1
                str(Q.CGDisplayModeGetHeight(mode)),                         # 2
                '@'+shorter_float_str(Q.CGDisplayModeGetRefreshRate(mode)),  # 3
                format_pixelEncoding(
                                Q.CGDisplayModeCopyPixelEncoding(mode)))     # 4
                        for mode in modes))
        t.set_key(2, 'height')
        t.set_key(3, 'rate')
        t.set_key(4, 'depth')
        t.set_alignment('height', 'l')
        t.set_alignment('rate', 'l')
        t.set_separator('height', ' x ')
        created_flags_col = False
        if full_modes:
                t.append_col(tuple((' '.join(get_flags_of_mode(mode))
                                        for mode in modes)), key='flags')
                created_flags_col = True
        else:
                # Remove refresh rate and bit depth if they are all the same
                if len(frozenset(t.get_col('rate'))) == 1:
                        t.del_col('rate')
                if len(frozenset(t.get_col('depth'))) == 1:
                        t.del_col('depth')

                # Show distinct IO flags when several modes appear the same
                lut = {}
                for i, row in enumerate(t):
                        row = tuple(row)
                        if row not in lut:
                                lut[row] = []
                        elif not created_flags_col:
                                t.append_col(('',) * len(modes), key='flags')
                        lut[row].append(i)
                for rw, indices in lut.iteritems():
                        if len(indices) == 1:
                                continue
                        flags = {}
                        for i in indices:
                                flags[i] = get_flags_of_mode(modes[i])
                        common_flags = reduce(lambda x, y: x.intersection(y),
                                        map(frozenset, flags.itervalues()))
                        for i in indices:
                                t[i, 'flags'] = ' '.join(frozenset(flags[i])
                                                        - common_flags)
        if created_flags_col:
                t.set_alignment('flags', 'l')
        return t