glances_curses.py 39.9 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
4
#
N
nicolargo 已提交
5
# Copyright (C) 2019 Nicolargo <nicolas@nicolargo.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

A
PEP 257  
Alessio Sergi 已提交
20
"""Curses interface class."""
N
nicolargo 已提交
21
from __future__ import unicode_literals
A
PEP 257  
Alessio Sergi 已提交
22

N
Nicolargo 已提交
23
import re
A
flake8  
Alessio Sergi 已提交
24
import sys
25

26
from glances.compat import to_ascii, nativestr, b, u, itervalues
A
Alessio Sergi 已提交
27
from glances.globals import MACOS, WINDOWS
28
from glances.logger import logger
29
from glances.events import glances_events
30 31
from glances.processes import glances_processes
from glances.timer import Timer
32

A
Alessio Sergi 已提交
33
# Import curses library for "normal" operating system
A
Alessio Sergi 已提交
34
if not WINDOWS:
35 36 37
    try:
        import curses
        import curses.panel
38
        from curses.textpad import Textbox
39
    except ImportError:
40
        logger.critical("Curses module not found. Glances cannot start in standalone mode.")
41
        sys.exit(1)
42 43


44
class _GlancesCurses(object):
45

A
PEP 257  
Alessio Sergi 已提交
46 47 48
    """This class manages the curses display (and key pressed).

    Note: It is a private class, use GlancesCursesClient or GlancesCursesBrowser.
49
    """
50

51 52 53 54 55
    _hotkeys = {
        '0': {'switch': 'disable_irix'},
        '1': {'switch': 'percpu'},
        '2': {'switch': 'disable_left_sidebar'},
        '3': {'switch': 'disable_quicklook'},
56
        '6': {'switch': 'meangpu'},
57 58 59 60
        '/': {'switch': 'process_short_name'},
        'A': {'switch': 'disable_amps'},
        'b': {'switch': 'byte'},
        'B': {'switch': 'diskio_iops'},
61
        'C': {'switch': 'disable_cloud'},
62
        'D': {'switch': 'disable_docker'},
63
        'd': {'switch': 'disable_diskio'},
64
        'F': {'switch': 'fs_free_space'},
65
        'g': {'switch': 'generate_graph'},
66
        'G': {'switch': 'disable_gpu'},
67 68 69 70 71
        'h': {'switch': 'help_tag'},
        'I': {'switch': 'disable_ip'},
        'l': {'switch': 'disable_alert'},
        'M': {'switch': 'reset_minmax_tag'},
        'n': {'switch': 'disable_network'},
N
nicolargo 已提交
72
        'N': {'switch': 'disable_now'},
73
        'P': {'switch': 'disable_ports'},
74
        'Q': {'switch': 'enable_irq'},
75 76
        'R': {'switch': 'disable_raid'},
        's': {'switch': 'disable_sensors'},
77
        'S': {'switch': 'sparkline'},
78 79 80 81 82 83 84 85 86 87
        'T': {'switch': 'network_sum'},
        'U': {'switch': 'network_cumul'},
        'W': {'switch': 'disable_wifi'},
        # Processes sort hotkeys
        'a': {'auto_sort': True, 'sort_key': 'cpu_percent'},
        'c': {'auto_sort': False, 'sort_key': 'cpu_percent'},
        'i': {'auto_sort': False, 'sort_key': 'io_counters'},
        'm': {'auto_sort': False, 'sort_key': 'memory_percent'},
        'p': {'auto_sort': False, 'sort_key': 'name'},
        't': {'auto_sort': False, 'sort_key': 'cpu_times'},
88
        'u': {'auto_sort': False, 'sort_key': 'username'},
89 90
    }

91 92 93
    _sort_loop = ['cpu_percent', 'memory_percent', 'username',
                  'cpu_times', 'io_counters', 'name']

N
nicolargo 已提交
94
    # Define top menu
N
nicolargo 已提交
95
    _top = ['quicklook', 'cpu', 'percpu', 'gpu', 'mem', 'memswap', 'load']
96
    _quicklook_max_width = 68
N
nicolargo 已提交
97 98

    # Define left sidebar
99
    _left_sidebar = ['network', 'connections', 'wifi', 'ports', 'diskio', 'fs',
100 101
                     'irq', 'folders', 'raid', 'sensors', 'now']
    _left_sidebar_min_width = 23
102
    _left_sidebar_max_width = 34
103

N
nicolargo 已提交
104 105 106
    # Define right sidebar
    _right_sidebar = ['docker', 'processcount', 'amps', 'processlist', 'alert']

107 108 109
    def __init__(self, config=None, args=None):
        # Init
        self.config = config
110
        self.args = args
N
Nicolas Hennion 已提交
111

112 113 114 115 116 117 118 119 120 121 122
        # Init windows positions
        self.term_w = 80
        self.term_h = 24

        # Space between stats
        self.space_between_column = 3
        self.space_between_line = 2

        # Init the curses screen
        self.screen = curses.initscr()
        if not self.screen:
A
Alessio Sergi 已提交
123
            logger.critical("Cannot init the curses library.\n")
N
Nicolas Hennion 已提交
124
            sys.exit(1)
125

126 127 128 129
        # Load the 'outputs' section of the configuration file
        # - Init the theme (default is black)
        self.theme = {'name': 'black'}

130 131 132
        # Load configuration file
        self.load_config(config)

133 134 135 136 137 138 139 140 141 142 143 144
        # Init cursor
        self._init_cursor()

        # Init the colors
        self._init_colors()

        # Init main window
        self.term_window = self.screen.subwin(0, 0)

        # Init edit filter tag
        self.edit_filter = False

145 146 147
        # Init the process min/max reset
        self.args.reset_minmax_tag = False

148
        # Catch key pressed with non blocking mode
149
        self.term_window.keypad(1)
150 151 152 153 154 155
        self.term_window.nodelay(1)
        self.pressedkey = -1

        # History tag
        self._init_history()

156
    def load_config(self, config):
157
        """Load the outputs section of the configuration file."""
158
        # Load the theme
159
        if config is not None and config.has_section('outputs'):
160 161
            logger.debug('Read the outputs section in the configuration file')
            self.theme['name'] = config.get_value('outputs', 'curse_theme', default='black')
162
            logger.debug('Theme for the curse interface: {}'.format(self.theme['name']))
163 164

    def is_theme(self, name):
165
        """Return True if the theme *name* should be used."""
166 167
        return getattr(self.args, 'theme_' + name) or self.theme['name'] == name

168
    def _init_history(self):
169
        """Init the history option."""
170 171 172 173

        self.reset_history_tag = False

    def _init_cursor(self):
174
        """Init cursors."""
175

176 177 178 179
        if hasattr(curses, 'noecho'):
            curses.noecho()
        if hasattr(curses, 'cbreak'):
            curses.cbreak()
N
Nicolargo 已提交
180
        self.set_cursor(0)
181

182
    def _init_colors(self):
183
        """Init the Curses color layout."""
184 185

        # Set curses options
186 187 188 189 190 191 192
        try:
            if hasattr(curses, 'start_color'):
                curses.start_color()
            if hasattr(curses, 'use_default_colors'):
                curses.use_default_colors()
        except Exception as e:
            logger.warning('Error initializing terminal color ({})'.format(e))
193

194
        # Init colors
195 196
        if self.args.disable_bold:
            A_BOLD = 0
197
            self.args.disable_bg = True
198 199
        else:
            A_BOLD = curses.A_BOLD
200 201 202 203 204 205 206

        self.title_color = A_BOLD
        self.title_underline_color = A_BOLD | curses.A_UNDERLINE
        self.help_color = A_BOLD

        if curses.has_colors():
            # The screen is compatible with a colored design
207
            if self.is_theme('white'):
208
                # White theme: black ==> white
N
Nicolargo 已提交
209 210 211
                curses.init_pair(1, curses.COLOR_BLACK, -1)
            else:
                curses.init_pair(1, curses.COLOR_WHITE, -1)
212
            if self.args.disable_bg:
213 214 215 216
                curses.init_pair(2, curses.COLOR_RED, -1)
                curses.init_pair(3, curses.COLOR_GREEN, -1)
                curses.init_pair(4, curses.COLOR_BLUE, -1)
                curses.init_pair(5, curses.COLOR_MAGENTA, -1)
217 218 219 220 221
            else:
                curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED)
                curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)
                curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)
                curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
222 223 224 225 226
            curses.init_pair(6, curses.COLOR_RED, -1)
            curses.init_pair(7, curses.COLOR_GREEN, -1)
            curses.init_pair(8, curses.COLOR_BLUE, -1)

            # Colors text styles
227 228 229 230
            if curses.COLOR_PAIRS > 8:
                try:
                    curses.init_pair(9, curses.COLOR_MAGENTA, -1)
                except Exception:
231
                    if self.is_theme('white'):
232 233 234 235 236 237
                        curses.init_pair(9, curses.COLOR_BLACK, -1)
                    else:
                        curses.init_pair(9, curses.COLOR_WHITE, -1)
                try:
                    curses.init_pair(10, curses.COLOR_CYAN, -1)
                except Exception:
238
                    if self.is_theme('white'):
239 240 241 242
                        curses.init_pair(10, curses.COLOR_BLACK, -1)
                    else:
                        curses.init_pair(10, curses.COLOR_WHITE, -1)

243 244
                self.ifWARNING_color2 = curses.color_pair(9) | A_BOLD
                self.ifCRITICAL_color2 = curses.color_pair(6) | A_BOLD
245 246
                self.filter_color = curses.color_pair(10) | A_BOLD

247
            self.no_color = curses.color_pair(1)
A
Alessio Sergi 已提交
248
            self.default_color = curses.color_pair(3) | A_BOLD
249 250
            self.nice_color = curses.color_pair(9)
            self.cpu_time_color = curses.color_pair(9)
251 252 253
            self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD
            self.ifWARNING_color = curses.color_pair(5) | A_BOLD
            self.ifCRITICAL_color = curses.color_pair(2) | A_BOLD
254
            self.default_color2 = curses.color_pair(7)
255
            self.ifCAREFUL_color2 = curses.color_pair(8) | A_BOLD
256

257
        else:
258 259
            # The screen is NOT compatible with a colored design
            # switch to B&W text styles
260 261
            self.no_color = curses.A_NORMAL
            self.default_color = curses.A_NORMAL
262
            self.nice_color = A_BOLD
263
            self.cpu_time_color = A_BOLD
264 265 266 267 268 269 270
            self.ifCAREFUL_color = curses.A_UNDERLINE
            self.ifWARNING_color = A_BOLD
            self.ifCRITICAL_color = curses.A_REVERSE
            self.default_color2 = curses.A_NORMAL
            self.ifCAREFUL_color2 = curses.A_UNDERLINE
            self.ifWARNING_color2 = A_BOLD
            self.ifCRITICAL_color2 = curses.A_REVERSE
N
Nicolargo 已提交
271
            self.filter_color = A_BOLD
272 273

        # Define the colors list (hash table) for stats
274
        self.colors_list = {
275 276 277
            'DEFAULT': self.no_color,
            'UNDERLINE': curses.A_UNDERLINE,
            'BOLD': A_BOLD,
278
            'SORT': A_BOLD,
279
            'OK': self.default_color2,
280
            'MAX': self.default_color2 | curses.A_BOLD,
N
Nicolargo 已提交
281
            'FILTER': self.filter_color,
282
            'TITLE': self.title_color,
283 284
            'PROCESS': self.default_color2,
            'STATUS': self.default_color2,
285
            'NICE': self.nice_color,
286
            'CPU_TIME': self.cpu_time_color,
287 288 289 290 291 292
            'CAREFUL': self.ifCAREFUL_color2,
            'WARNING': self.ifWARNING_color2,
            'CRITICAL': self.ifCRITICAL_color2,
            'OK_LOG': self.default_color,
            'CAREFUL_LOG': self.ifCAREFUL_color,
            'WARNING_LOG': self.ifWARNING_color,
293 294
            'CRITICAL_LOG': self.ifCRITICAL_color,
            'PASSWORD': curses.A_PROTECT
295 296
        }

N
Nicolargo 已提交
297
    def set_cursor(self, value):
A
PEP 257  
Alessio Sergi 已提交
298 299 300 301 302 303
        """Configure the curse cursor apparence.

        0: invisible
        1: visible
        2: very visible
        """
N
Nicolargo 已提交
304 305 306 307 308 309
        if hasattr(curses, 'curs_set'):
            try:
                curses.curs_set(value)
            except Exception:
                pass

310 311 312 313 314 315 316 317 318 319 320 321 322 323
    # def get_key(self, window):
    #     # Catch ESC key AND numlock key (issue #163)
    #     keycode = [0, 0]
    #     keycode[0] = window.getch()
    #     keycode[1] = window.getch()
    #
    #     if keycode != [-1, -1]:
    #         logger.debug("Keypressed (code: %s)" % keycode)
    #
    #     if keycode[0] == 27 and keycode[1] != -1:
    #         # Do not escape on specials keys
    #         return -1
    #     else:
    #         return keycode[0]
N
Nicolargo 已提交
324

325 326 327 328 329
    def get_key(self, window):
        # @TODO: Check issue #163
        ret = window.getch()
        logger.debug("Keypressed (code: %s)" % ret)
        return ret
330

N
Nicolargo 已提交
331
    def __catch_key(self, return_to_browser=False):
A
PEP 257  
Alessio Sergi 已提交
332
        # Catch the pressed key
333
        self.pressedkey = self.get_key(self.term_window)
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        # Actions (available in the global hotkey dict)...
        for hotkey in self._hotkeys:
            if self.pressedkey == ord(hotkey) and 'switch' in self._hotkeys[hotkey]:
                setattr(self.args,
                        self._hotkeys[hotkey]['switch'],
                        not getattr(self.args,
                                    self._hotkeys[hotkey]['switch']))
            if self.pressedkey == ord(hotkey) and 'auto_sort' in self._hotkeys[hotkey]:
                setattr(glances_processes,
                        'auto_sort',
                        self._hotkeys[hotkey]['auto_sort'])
            if self.pressedkey == ord(hotkey) and 'sort_key' in self._hotkeys[hotkey]:
                setattr(glances_processes,
                        'sort_key',
                        self._hotkeys[hotkey]['sort_key'])

        # Other actions...
352 353
        if self.pressedkey == ord('\x1b') or self.pressedkey == ord('q'):
            # 'ESC'|'q' > Quit
N
Nicolargo 已提交
354 355 356
            if return_to_browser:
                logger.info("Stop Glances client and return to the browser")
            else:
357
                logger.info("Stop Glances (keypressed: {})".format(self.pressedkey))
358
        elif self.pressedkey == ord('\n'):
N
Nicolargo 已提交
359 360
            # 'ENTER' > Edit the process filter
            self.edit_filter = not self.edit_filter
N
nicolargo 已提交
361
        elif self.pressedkey == ord('4'):
N
nicolargo 已提交
362
            self.args.full_quicklook = not self.args.full_quicklook
N
nicolargo 已提交
363 364 365 366 367
            if self.args.full_quicklook:
                self.enable_fullquicklook()
            else:
                self.disable_fullquicklook()
        elif self.pressedkey == ord('5'):
N
nicolargo 已提交
368
            self.args.disable_top = not self.args.disable_top
N
nicolargo 已提交
369 370 371 372
            if self.args.disable_top:
                self.disable_top()
            else:
                self.enable_top()
373 374 375 376 377 378 379
        elif self.pressedkey == ord('e'):
            # 'e' > Enable/Disable process extended
            self.args.enable_process_extended = not self.args.enable_process_extended
            if not self.args.enable_process_extended:
                glances_processes.disable_extended()
            else:
                glances_processes.enable_extended()
380 381 382
        elif self.pressedkey == ord('E'):
            # 'E' > Erase the process filter
            glances_processes.process_filter = None
383 384 385
        elif self.pressedkey == ord('f'):
            # 'f' > Show/hide fs / folder stats
            self.args.disable_fs = not self.args.disable_fs
N
nicolargo 已提交
386
            self.args.disable_folders = not self.args.disable_folders
387 388
        elif self.pressedkey == ord('w'):
            # 'w' > Delete finished warning logs
389
            glances_events.clean()
390 391
        elif self.pressedkey == ord('x'):
            # 'x' > Delete finished warning and critical logs
392
            glances_events.clean(critical=True)
393
        elif self.pressedkey == ord('z'):
394
            # 'z' > Enable or disable processes
395 396 397 398 399
            self.args.disable_process = not self.args.disable_process
            if self.args.disable_process:
                glances_processes.disable()
            else:
                glances_processes.enable()
400 401 402 403 404 405 406 407 408 409
        elif self.pressedkey == curses.KEY_LEFT:
            # "<" (left arrow) navigation through process sort
            setattr(glances_processes, 'auto_sort', False)
            next_sort = (self.loop_position() - 1) % len(self._sort_loop)
            glances_processes.sort_key = self._sort_loop[next_sort]
        elif self.pressedkey == curses.KEY_RIGHT:
            # ">" (right arrow) navigation through process sort
            setattr(glances_processes, 'auto_sort', False)
            next_sort = (self.loop_position() + 1) % len(self._sort_loop)
            glances_processes.sort_key = self._sort_loop[next_sort]
410

411 412 413
        # Return the key code
        return self.pressedkey

414 415 416 417 418 419 420
    def loop_position(self):
        """Return the current sort in the loop"""
        for i, v in enumerate(self._sort_loop):
            if v == glances_processes.sort_key:
                return i
        return 0

421 422
    def disable_top(self):
        """Disable the top panel"""
423 424
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap', 'load']:
            setattr(self.args, 'disable_' + p, True)
425 426 427

    def enable_top(self):
        """Enable the top panel"""
428 429
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap', 'load']:
            setattr(self.args, 'disable_' + p, False)
430 431 432

    def disable_fullquicklook(self):
        """Disable the full quicklook mode"""
433 434
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap']:
            setattr(self.args, 'disable_' + p, False)
435 436 437 438

    def enable_fullquicklook(self):
        """Disable the full quicklook mode"""
        self.args.disable_quicklook = False
439 440
        for p in ['cpu', 'gpu', 'mem', 'memswap']:
            setattr(self.args, 'disable_' + p, True)
441

442
    def end(self):
443
        """Shutdown the curses window."""
N
Nicolas Hennion 已提交
444 445 446 447 448 449 450 451 452
        if hasattr(curses, 'echo'):
            curses.echo()
        if hasattr(curses, 'nocbreak'):
            curses.nocbreak()
        if hasattr(curses, 'curs_set'):
            try:
                curses.curs_set(1)
            except Exception:
                pass
453
        curses.endwin()
454

455
    def init_line_column(self):
456
        """Init the line and column position for the curses interface."""
457 458
        self.init_line()
        self.init_column()
459 460

    def init_line(self):
461
        """Init the line position for the curses interface."""
462 463 464 465
        self.line = 0
        self.next_line = 0

    def init_column(self):
466
        """Init the column position for the curses interface."""
467 468 469 470
        self.column = 0
        self.next_column = 0

    def new_line(self):
A
PEP 257  
Alessio Sergi 已提交
471
        """New line in the curses interface."""
472 473 474
        self.line = self.next_line

    def new_column(self):
A
PEP 257  
Alessio Sergi 已提交
475
        """New column in the curses interface."""
476 477
        self.column = self.next_column

478 479 480 481 482 483 484 485
    def __get_stat_display(self, stats, layer):
        """Return a dict of dict with all the stats display.
        stats: Global stats dict
        layer: ~ cs_status
            "None": standalone or server mode
            "Connected": Client is connected to a Glances server
            "SNMP": Client is connected to a SNMP server
            "Disconnected": Client is disconnected from the server
486 487

        :returns: dict of dict
488 489
            * key: plugin name
            * value: dict returned by the get_stats_display Plugin method
490
        """
N
nicolargo 已提交
491
        ret = {}
492

N
nicolargo 已提交
493
        for p in stats.getPluginsList(enable=False):
494 495 496
            if p == 'quicklook' or p == 'processlist':
                # processlist is done later
                # because we need to know how many processes could be displayed
497
                continue
498 499 500 501 502 503 504 505 506 507 508 509 510

            # Compute the plugin max size
            plugin_max_width = None
            if p in self._left_sidebar:
                plugin_max_width = max(self._left_sidebar_min_width,
                                       self.screen.getmaxyx()[1] - 105)
                plugin_max_width = min(self._left_sidebar_max_width,
                                       plugin_max_width)

            # Get the view
            ret[p] = stats.get_plugin(p).get_stats_display(args=self.args,
                                                           max_width=plugin_max_width)

N
nicolargo 已提交
511 512
        return ret

513
    def display(self, stats, cs_status=None):
A
PEP 257  
Alessio Sergi 已提交
514
        """Display stats on the screen.
515

516 517 518
        stats: Stats database to display
        cs_status:
            "None": standalone or server mode
519 520
            "Connected": Client is connected to a Glances server
            "SNMP": Client is connected to a SNMP server
521
            "Disconnected": Client is disconnected from the server
522 523 524 525

        Return:
            True if the stats have been displayed
            False if the help have been displayed
526
        """
527 528
        # Init the internal line/column for Glances Curses
        self.init_line_column()
529

530 531 532
        # Update the stats messages
        ###########################

533
        # Get all the plugins but quicklook and proceslist
534
        self.args.cs_status = cs_status
535
        __stat_display = self.__get_stat_display(stats, layer=cs_status)
536

537
        # Adapt number of processes to the available space
538 539
        max_processes_displayed = (
            self.screen.getmaxyx()[0] - 11 -
540
            (0 if 'docker' not in __stat_display else
N
nicolargo 已提交
541 542 543 544 545 546 547
                self.get_stats_display_height(__stat_display["docker"])) -
            (0 if 'processcount' not in __stat_display else
                self.get_stats_display_height(__stat_display["processcount"])) -
            (0 if 'amps' not in __stat_display else
                self.get_stats_display_height(__stat_display["amps"])) -
            (0 if 'alert' not in __stat_display else
                self.get_stats_display_height(__stat_display["alert"])))
548

549
        try:
N
nicolargo 已提交
550
            if self.args.enable_process_extended:
551 552 553
                max_processes_displayed -= 4
        except AttributeError:
            pass
554
        if max_processes_displayed < 0:
555
            max_processes_displayed = 0
556 557
        if (glances_processes.max_processes is None or
                glances_processes.max_processes != max_processes_displayed):
558
            logger.debug("Set number of displayed processes to {}".format(max_processes_displayed))
559
            glances_processes.max_processes = max_processes_displayed
560

561
        # Get the processlist
N
nicolargo 已提交
562
        __stat_display["processlist"] = stats.get_plugin(
563
            'processlist').get_stats_display(args=self.args)
564

565 566 567 568
        # Display the stats on the curses interface
        ###########################################

        # Help screen (on top of the other stats)
569
        if self.args.help_tag:
570
            # Display the stats...
571 572
            self.display_plugin(
                stats.get_plugin('help').get_stats_display(args=self.args))
573 574 575
            # ... and exit
            return False

576 577
        # =====================================
        # Display first line (system+ip+uptime)
578
        # Optionnaly: Cloud on second line
579
        # =====================================
N
nicolargo 已提交
580
        self.__display_header(__stat_display)
581 582 583 584

        # ==============================================================
        # Display second line (<SUMMARY>+CPU|PERCPU+<GPU>+LOAD+MEM+SWAP)
        # ==============================================================
N
nicolargo 已提交
585
        self.__display_top(__stat_display, stats)
586 587 588 589 590 591 592 593 594 595 596

        # ==================================================================
        # Display left sidebar (NETWORK+PORTS+DISKIO+FS+SENSORS+Current time)
        # ==================================================================
        self.__display_left(__stat_display)

        # ====================================
        # Display right stats (process and co)
        # ====================================
        self.__display_right(__stat_display)

597 598 599 600
        # =====================
        # Others popup messages
        # =====================

601 602 603 604 605 606 607 608
        # Display edit filter popup
        # Only in standalone mode (cs_status is None)
        if self.edit_filter and cs_status is None:
            new_filter = self.display_popup(
                'Process filter pattern: \n\n' +
                'Examples:\n' +
                '- python\n' +
                '- .*python.*\n' +
N
nicolargo 已提交
609
                '- /usr/lib.*\n' +
610 611 612 613 614 615 616 617 618 619 620
                '- name:.*nautilus.*\n' +
                '- cmdline:.*glances.*\n' +
                '- username:nicolargo\n' +
                '- username:^root        ',
                is_input=True,
                input_value=glances_processes.process_filter_input)
            glances_processes.process_filter = new_filter
        elif self.edit_filter and cs_status is not None:
            self.display_popup('Process filter only available in standalone mode')
        self.edit_filter = False

621 622 623 624
        # Display graph generation popup
        if self.args.generate_graph:
            self.display_popup('Generate graph in {}'.format(self.args.export_graph_path))

625 626
        return True

N
nicolargo 已提交
627 628
    def __display_header(self, stat_display):
        """Display the firsts lines (header) in the Curses interface.
629 630

        system + ip + uptime
N
nicolargo 已提交
631
        (cloud)
632
        """
N
nicolargo 已提交
633
        # First line
634
        self.new_line()
N
nicolargo 已提交
635
        self.space_between_column = 0
636 637 638 639
        l_uptime = 1
        for i in ['system', 'ip', 'uptime']:
            if i in stat_display:
                l_uptime += self.get_stats_display_width(stat_display[i])
640
        self.display_plugin(
641 642
            stat_display["system"],
            display_optional=(self.screen.getmaxyx()[1] >= l_uptime))
N
nicolargo 已提交
643
        self.space_between_column = 3
644
        self.new_column()
645
        self.display_plugin(stat_display["ip"])
646
        self.new_column()
N
nicolargo 已提交
647 648
        self.display_plugin(
            stat_display["uptime"],
N
nicolargo 已提交
649
            add_space=-(self.get_stats_display_width(stat_display["cloud"]) != 0))
N
nicolargo 已提交
650
        # Second line (optional)
651 652 653
        self.init_column()
        self.new_line()
        self.display_plugin(stat_display["cloud"])
A
Alessio Sergi 已提交
654

N
nicolargo 已提交
655
    def __display_top(self, stat_display, stats):
656 657 658 659
        """Display the second line in the Curses interface.

        <QUICKLOOK> + CPU|PERCPU + <GPU> + MEM + SWAP + LOAD
        """
660
        self.init_column()
661
        self.new_line()
662

N
Nicolargo 已提交
663
        # Init quicklook
664
        stat_display['quicklook'] = {'msgdict': []}
665

666
        # Dict for plugins width
N
nicolargo 已提交
667 668 669
        plugin_widths = {}
        for p in self._top:
            plugin_widths[p] = self.get_stats_display_width(stat_display.get(p, 0)) if hasattr(self.args, 'disable_' + p) else 0
670

671 672
        # Width of all plugins
        stats_width = sum(itervalues(plugin_widths))
673 674

        # Number of plugin but quicklook
N
nicolargo 已提交
675
        stats_number = sum([int(stat_display[p]['msgdict'] != []) for p in self._top if not getattr(self.args, 'disable_' + p)])
676 677 678

        if not self.args.disable_quicklook:
            # Quick look is in the place !
679
            if self.args.full_quicklook:
680
                quicklook_width = self.screen.getmaxyx()[1] - (stats_width + 8 + stats_number * self.space_between_column)
681
            else:
N
nicolargo 已提交
682
                quicklook_width = min(self.screen.getmaxyx()[1] - (stats_width + 8 + stats_number * self.space_between_column),
683
                                      self._quicklook_max_width - 5)
N
Nicolargo 已提交
684
            try:
685
                stat_display["quicklook"] = stats.get_plugin(
N
Nicolargo 已提交
686 687 688 689
                    'quicklook').get_stats_display(max_width=quicklook_width, args=self.args)
            except AttributeError as e:
                logger.debug("Quicklook plugin not available (%s)" % e)
            else:
690 691
                plugin_widths['quicklook'] = self.get_stats_display_width(stat_display["quicklook"])
                stats_width = sum(itervalues(plugin_widths)) + 1
692
            self.space_between_column = 1
693
            self.display_plugin(stat_display["quicklook"])
694 695 696 697
            self.new_column()

        # Compute spaces between plugins
        # Note: Only one space between Quicklook and others
698
        plugin_display_optional = {}
N
nicolargo 已提交
699
        for p in self._top:
700
            plugin_display_optional[p] = True
701
        if stats_number > 1:
702
            self.space_between_column = max(1, int((self.screen.getmaxyx()[1] - stats_width) / (stats_number - 1)))
703 704 705 706 707 708 709
            for p in ['mem', 'cpu']:
                # No space ? Remove optional stats
                if self.space_between_column < 3:
                    plugin_display_optional[p] = False
                    plugin_widths[p] = self.get_stats_display_width(stat_display[p], without_option=True) if hasattr(self.args, 'disable_' + p) else 0
                    stats_width = sum(itervalues(plugin_widths)) + 1
                    self.space_between_column = max(1, int((self.screen.getmaxyx()[1] - stats_width) / (stats_number - 1)))
710 711 712 713
        else:
            self.space_between_column = 0

        # Display CPU, MEM, SWAP and LOAD
N
nicolargo 已提交
714 715 716
        for p in self._top:
            if p == 'quicklook':
                continue
N
nicolargo 已提交
717 718 719
            if p in stat_display:
                self.display_plugin(stat_display[p],
                                    display_optional=plugin_display_optional[p])
720 721 722
            if p is not 'load':
                # Skip last column
                self.new_column()
723

724 725 726
        # Space between column
        self.space_between_column = 3

727 728 729
        # Backup line position
        self.saved_line = self.next_line

730
    def __display_left(self, stat_display):
731
        """Display the left sidebar in the Curses interface."""
732
        self.init_column()
N
nicolargo 已提交
733 734 735 736

        if self.args.disable_left_sidebar:
            return

737 738
        for p in self._left_sidebar:
            if ((hasattr(self.args, 'enable_' + p) or
739
                 hasattr(self.args, 'disable_' + p)) and p in stat_display):
N
nicolargo 已提交
740
                self.new_line()
741
                self.display_plugin(stat_display[p])
742

743 744 745 746 747
    def __display_right(self, stat_display):
        """Display the right sidebar in the Curses interface.

        docker + processcount + amps + processlist + alert
        """
N
nicolargo 已提交
748 749 750
        # Do not display anything if space is not available...
        if self.screen.getmaxyx()[1] < self._left_sidebar_min_width:
            return
751

N
nicolargo 已提交
752 753 754 755 756 757
        # Restore line position
        self.next_line = self.saved_line

        # Display right sidebar
        self.new_column()
        for p in self._right_sidebar:
758 759 760 761 762 763 764 765 766 767 768 769 770
            if ((hasattr(self.args, 'enable_' + p) or
                 hasattr(self.args, 'disable_' + p)) and p in stat_display):
                if p not in p:
                    # Catch for issue #1470
                    continue
                self.new_line()
                if p == 'processlist':
                    self.display_plugin(stat_display['processlist'],
                                        display_optional=(self.screen.getmaxyx()[1] > 102),
                                        display_additional=(not MACOS),
                                        max_y=(self.screen.getmaxyx()[0] - self.get_stats_display_height(stat_display['alert']) - 2))
                else:
                    self.display_plugin(stat_display[p])
771

772 773
    def display_popup(self, message,
                      size_x=None, size_y=None,
N
Nicolargo 已提交
774 775
                      duration=3,
                      is_input=False,
N
Nicolargo 已提交
776
                      input_size=30,
N
Nicolargo 已提交
777
                      input_value=None):
778
        """
A
PEP 257  
Alessio Sergi 已提交
779 780
        Display a centered popup.

N
Nicolargo 已提交
781 782 783 784 785
        If is_input is False:
         Display a centered popup with the given message during duration seconds
         If size_x and size_y: set the popup size
         else set it automatically
         Return True if the popup could be displayed
A
PEP 257  
Alessio Sergi 已提交
786

N
Nicolargo 已提交
787 788 789 790
        If is_input is True:
         Display a centered popup with the given message and a input field
         If size_x and size_y: set the popup size
         else set it automatically
791
         Return the input string or None if the field is empty
792 793
        """
        # Center the popup
N
Nicolargo 已提交
794
        sentence_list = message.split('\n')
795
        if size_x is None:
N
Nicolargo 已提交
796
            size_x = len(max(sentence_list, key=len)) + 4
N
Nicolargo 已提交
797 798 799
            # Add space for the input field
            if is_input:
                size_x += input_size
800
        if size_y is None:
N
Nicolargo 已提交
801
            size_y = len(sentence_list) + 4
802 803 804 805
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if size_x > screen_x or size_y > screen_y:
            # No size to display the popup => abord
806
            return False
807 808
        pos_x = int((screen_x - size_x) / 2)
        pos_y = int((screen_y - size_y) / 2)
809 810 811

        # Create the popup
        popup = curses.newwin(size_y, size_x, pos_y, pos_x)
812

813 814 815 816
        # Fill the popup
        popup.border()

        # Add the message
N
nicolargo 已提交
817
        for y, m in enumerate(message.split('\n')):
818 819
            popup.addnstr(2 + y, 2, m, len(m))

A
Alessio Sergi 已提交
820
        if is_input and not WINDOWS:
N
Nicolargo 已提交
821 822
            # Create a subwindow for the text field
            subpop = popup.derwin(1, input_size, 2, 2 + len(m))
823
            subpop.attron(self.colors_list['FILTER'])
N
Nicolargo 已提交
824 825 826 827 828 829 830 831
            # Init the field with the current value
            if input_value is not None:
                subpop.addnstr(0, 0, input_value, len(input_value))
            # Display the popup
            popup.refresh()
            subpop.refresh()
            # Create the textbox inside the subwindows
            self.set_cursor(2)
832
            self.term_window.keypad(1)
A
Alessio Sergi 已提交
833
            textbox = GlancesTextbox(subpop, insert_mode=False)
N
Nicolargo 已提交
834 835
            textbox.edit()
            self.set_cursor(0)
836
            self.term_window.keypad(0)
N
Nicolargo 已提交
837
            if textbox.gather() != '':
N
Nicolargo 已提交
838
                logger.debug(
839
                    "User enters the following string: %s" % textbox.gather())
N
Nicolargo 已提交
840 841
                return textbox.gather()[:-1]
            else:
842
                logger.debug("User centers an empty string")
N
Nicolargo 已提交
843 844 845 846
                return None
        else:
            # Display the popup
            popup.refresh()
847
            self.wait(duration * 1000)
N
Nicolargo 已提交
848
            return True
849

850
    def display_plugin(self, plugin_stats,
851
                       display_optional=True,
852
                       display_additional=True,
853
                       max_y=65535,
N
nicolargo 已提交
854
                       add_space=0):
A
PEP 257  
Alessio Sergi 已提交
855 856
        """Display the plugin_stats on the screen.

857 858
        If display_optional=True display the optional stats
        If display_additional=True display additionnal stats
N
nicolargo 已提交
859 860
        max_y: do not display line > max_y
        add_space: add x space (line) after the plugin
861
        """
862 863 864
        # Exit if:
        # - the plugin_stats message is empty
        # - the display tag = False
865
        if plugin_stats is None or not plugin_stats['msgdict'] or not plugin_stats['display']:
866
            # Exit
867 868 869 870 871 872 873
            return 0

        # Get the screen size
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]

        # Set the upper/left position of the message
874
        if plugin_stats['align'] == 'right':
875
            # Right align (last column)
876
            display_x = screen_x - self.get_stats_display_width(plugin_stats)
877
        else:
878
            display_x = self.column
879
        if plugin_stats['align'] == 'bottom':
880
            # Bottom (last line)
881
            display_y = screen_y - self.get_stats_display_height(plugin_stats)
882
        else:
883
            display_y = self.line
884

885 886
        # Display
        x = display_x
887
        x_max = x
888 889 890
        y = display_y
        for m in plugin_stats['msgdict']:
            # New line
891
            if m['msg'].startswith('\n'):
892
                # Go to the next line
893
                y += 1
894 895 896 897
                # Return to the first column
                x = display_x
                continue
            # Do not display outside the screen
898
            if x < 0:
899
                continue
900
            if not m['splittable'] and (x + len(m['msg']) > screen_x):
901
                continue
902
            if y < 0 or (y + 1 > screen_y) or (y > max_y):
903 904
                break
            # If display_optional = False do not display optional stats
905
            if not display_optional and m['optional']:
906
                continue
907 908 909
            # If display_additional = False do not display additional stats
            if not display_additional and m['additional']:
                continue
910 911 912
            # Is it possible to display the stat with the current screen size
            # !!! Crach if not try/except... Why ???
            try:
A
Alessio Sergi 已提交
913 914
                self.term_window.addnstr(y, x,
                                         m['msg'],
915 916
                                         # Do not disply outside the screen
                                         screen_x - x,
917
                                         self.colors_list[m['decoration']])
A
Alessio Sergi 已提交
918
            except Exception:
919 920 921
                pass
            else:
                # New column
A
Alessio Sergi 已提交
922 923 924 925
                # Python 2: we need to decode to get real screen size because
                # UTF-8 special tree chars occupy several bytes.
                # Python 3: strings are strings and bytes are bytes, all is
                # good.
N
Nicolargo 已提交
926 927 928 929 930
                try:
                    x += len(u(m['msg']))
                except UnicodeDecodeError:
                    # Quick and dirty hack for issue #745
                    pass
931 932
                if x > x_max:
                    x_max = x
933 934

        # Compute the next Glances column/line position
N
Nicolargo 已提交
935 936
        self.next_column = max(
            self.next_column, x_max + self.space_between_column)
937
        self.next_line = max(self.next_line, y + self.space_between_line)
938

N
nicolargo 已提交
939 940
        # Have empty lines after the plugins
        self.next_line += add_space
941

942
    def erase(self):
A
PEP 257  
Alessio Sergi 已提交
943
        """Erase the content of the screen."""
944 945
        self.term_window.erase()

946
    def flush(self, stats, cs_status=None):
A
PEP 257  
Alessio Sergi 已提交
947 948
        """Clear and update the screen.

949 950 951 952 953 954 955
        stats: Stats database to display
        cs_status:
            "None": standalone or server mode
            "Connected": Client is connected to the server
            "Disconnected": Client is disconnected from the server
        """
        self.erase()
956
        self.display(stats, cs_status=cs_status)
957

958 959 960 961 962
    def update(self,
               stats,
               duration=3,
               cs_status=None,
               return_to_browser=False):
A
PEP 257  
Alessio Sergi 已提交
963 964
        """Update the screen.

N
Nicolargo 已提交
965
        INPUT
966
        stats: Stats database to display
967
        duration: duration of the loop
968 969 970 971
        cs_status:
            "None": standalone or server mode
            "Connected": Client is connected to the server
            "Disconnected": Client is disconnected from the server
N
Nicolargo 已提交
972 973 974 975
        return_to_browser:
            True: Do not exist, return to the browser list
            False: Exit and return to the shell

976
        OUTPUT
N
Nicolargo 已提交
977 978
        True: Exit key has been pressed
        False: Others cases...
979 980
        """
        # Flush display
981
        self.flush(stats, cs_status=cs_status)
982

983 984 985
        # If the duration is < 0 (update + export time > refresh_time)
        # Then display the interface and log a message
        if duration <= 0:
986
            logger.warning('Update and export time higher than refresh_time.')
987 988
            duration = 0.1

989
        # Wait duration (in s) time
N
Nicolargo 已提交
990
        exitkey = False
991
        countdown = Timer(duration)
992 993
        # Set the default timeout (in ms) for the getch method
        self.term_window.timeout(int(duration * 1000))
N
Nicolargo 已提交
994
        while not countdown.finished() and not exitkey:
995
            # Getkey
N
Nicolargo 已提交
996 997 998 999
            pressedkey = self.__catch_key(return_to_browser=return_to_browser)
            # Is it an exit key ?
            exitkey = (pressedkey == ord('\x1b') or pressedkey == ord('q'))
            if not exitkey and pressedkey > -1:
1000
                # Redraw display
1001
                self.flush(stats, cs_status=cs_status)
N
nicolargo 已提交
1002 1003
                # Overwrite the timeout with the countdown
                self.term_window.timeout(int(countdown.get() * 1000))
1004

N
Nicolargo 已提交
1005 1006
        return exitkey

1007 1008 1009 1010
    def wait(self, delay=100):
        """Wait delay in ms"""
        curses.napms(100)

1011
    def get_stats_display_width(self, curse_msg, without_option=False):
N
nicolargo 已提交
1012
        """Return the width of the formatted curses message."""
1013
        try:
1014
            if without_option:
1015
                # Size without options
1016
                c = len(max(''.join([(u(u(nativestr(i['msg'])).encode('ascii', 'replace')) if not i['optional'] else "")
1017
                                     for i in curse_msg['msgdict']]).split('\n'), key=len))
1018 1019
            else:
                # Size with all options
1020
                c = len(max(''.join([u(u(nativestr(i['msg'])).encode('ascii', 'replace'))
1021
                                     for i in curse_msg['msgdict']]).split('\n'), key=len))
1022 1023
        except Exception as e:
            logger.debug('ERROR: Can not compute plugin width ({})'.format(e))
1024 1025 1026 1027
            return 0
        else:
            return c

1028
    def get_stats_display_height(self, curse_msg):
A
PEP 257  
Alessio Sergi 已提交
1029
        r"""Return the height of the formatted curses message.
1030

A
PEP 257  
Alessio Sergi 已提交
1031 1032
        The height is defined by the number of '\n' (new line).
        """
1033
        try:
A
Alessio Sergi 已提交
1034
            c = [i['msg'] for i in curse_msg['msgdict']].count('\n')
1035 1036
        except Exception as e:
            logger.debug('ERROR: Can not compute plugin height ({})'.format(e))
1037 1038 1039
            return 0
        else:
            return c + 1
N
Nicolargo 已提交
1040

1041

1042 1043
class GlancesCursesStandalone(_GlancesCurses):

A
PEP 257  
Alessio Sergi 已提交
1044
    """Class for the Glances curse standalone."""
1045 1046 1047 1048

    pass


1049 1050
class GlancesCursesClient(_GlancesCurses):

A
PEP 257  
Alessio Sergi 已提交
1051
    """Class for the Glances curse client."""
1052 1053 1054 1055

    pass


A
Alessio Sergi 已提交
1056
if not WINDOWS:
1057
    class GlancesTextbox(Textbox, object):
1058

1059 1060
        def __init__(self, *args, **kwargs):
            super(GlancesTextbox, self).__init__(*args, **kwargs)
1061

N
Nicolargo 已提交
1062
        def do_command(self, ch):
1063
            if ch == 10:  # Enter
N
Nicolargo 已提交
1064
                return 0
1065
            if ch == 127:  # Back
N
Nicolargo 已提交
1066
                return 8
1067
            return super(GlancesTextbox, self).do_command(ch)