1# This file is part of ranger, the console file manager.
2# License: GNU GPL version 3, see the file "AUTHORS" for details.
3
4"""Contains abbreviations to curses color/attribute constants.
5
6Multiple attributes can be combined with the | (or) operator, toggled
7with ^ (xor) and checked for with & (and). Examples:
8
9attr = bold | underline
10attr |= reverse
11bool(attr & reverse) # => True
12attr ^= reverse
13bool(attr & reverse) # => False
14"""
15
16from __future__ import (absolute_import, division, print_function)
17
18import curses
19
20DEFAULT_FOREGROUND = curses.COLOR_WHITE
21DEFAULT_BACKGROUND = curses.COLOR_BLACK
22COLOR_PAIRS = {10: 0}
23
24
25def get_color(fg, bg):
26    """Returns the curses color pair for the given fg/bg combination."""
27
28    key = (fg, bg)
29    if key not in COLOR_PAIRS:
30        size = len(COLOR_PAIRS)
31        try:
32            curses.init_pair(size, fg, bg)
33        except curses.error:
34            # If curses.use_default_colors() failed during the initialization
35            # of curses, then using -1 as fg or bg will fail as well, which
36            # we need to handle with fallback-defaults:
37            if fg == -1:  # -1 is the "default" color
38                fg = DEFAULT_FOREGROUND
39            if bg == -1:  # -1 is the "default" color
40                bg = DEFAULT_BACKGROUND
41
42            try:
43                curses.init_pair(size, fg, bg)
44            except curses.error:
45                # If this fails too, colors are probably not supported
46                pass
47        COLOR_PAIRS[key] = size
48
49    return COLOR_PAIRS[key]
50
51
52# pylint: disable=invalid-name,bad-whitespace
53black      = curses.COLOR_BLACK
54blue       = curses.COLOR_BLUE
55cyan       = curses.COLOR_CYAN
56green      = curses.COLOR_GREEN
57magenta    = curses.COLOR_MAGENTA
58red        = curses.COLOR_RED
59white      = curses.COLOR_WHITE
60yellow     = curses.COLOR_YELLOW
61default    = -1
62
63normal     = curses.A_NORMAL
64bold       = curses.A_BOLD
65blink      = curses.A_BLINK
66reverse    = curses.A_REVERSE
67underline  = curses.A_UNDERLINE
68invisible  = curses.A_INVIS
69dim = curses.A_DIM
70
71default_colors = (default, default, normal)
72# pylint: enable=invalid-name,bad-whitespace
73
74curses.setupterm()
75# Adding BRIGHT to a color achieves what `bold` was used for.
76BRIGHT = 8 if curses.tigetnum('colors') >= 16 else 0
77