summaryrefslogtreecommitdiffstats
path: root/glances/outputs/glances_rich.py
blob: f6dcbeb100619790dc11a3318d2b1e0d01b40580 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2022 Nicolargo <nicolas@nicolargo.com>
#
# 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/>.

"""Stdout interface class."""

from pprint import pformat
import time
import sys

from glances.logger import logger
from glances.keyboard import KBHit
from glances.timer import Timer
from glances.compat import nativestr, u
from glances.processes import glances_processes, sort_processes_key_list

# Import curses library for "normal" operating system
try:
    from rich.panel import Panel
    from rich.panel import Padding
    from rich.measure import Measurement
    from rich.table import Table
    from rich.layout import Layout
    from rich.style import Style
    from rich.console import Console
    from rich.live import Live
except ImportError:
    logger.critical("Rich module not found. Glances cannot start in standalone mode.")
    sys.exit(1)

# Define plugins order in TUI menu
_top = [
    'quicklook',
    'cpu',
    'percpu',
    'gpu',
    'mem',
    'memswap',
    'load'
]

_middle_left = [
    'network',
    'connections',
    'wifi',
    'ports',
    'diskio',
    'fs',
    'irq',
    'folders',
    'raid',
    'smart',
    'sensors'
]
_middle_left_width = 34

_middle_right = [
    'docker',
    'processcount',
    'amps',
    'processlist',
    'alert'
]

_bottom = [
    'now'
]


class GlancesRich(object):

    """This class manages the Rich display (it replaces Curses in Glances version 4 and higher)."""

    def __init__(self, config=None, args=None):
        # Init
        self.config = config
        self.args = args

        # Init keyboard
        self.kb = KBHit()

        # Init cursor
        self.args.cursor_position = 0

        # Init the screen
        self.console = Console(soft_wrap=True)
        self.layout = Layout()
        self.live = Live(console=self.console, screen=True, auto_refresh=False)

    def end(self):
        # Reset the keyboard
        self.kb.set_normal_term()

    def update(self, stats, duration=3):
        """Display stats to the Rich interface.

        Refresh every duration second.
        """
        # If the duration is < 0 (update + export time > refresh_time)
        # Then display the interface and log a message
        if duration <= 0:
            logger.warning('Update and export time higher than refresh_time.')
            duration = 0.1

        # Wait duration (in s) time
        isexitkey = False
        countdown = Timer(duration)

        self.update_layout(stats)
        while not countdown.finished() and not isexitkey:
            # Manage if a key was pressed
            if self.kb.kbhit():
                pressedkey = ord(self.kb.getch())
                isexitkey = pressedkey == ord('\x1b') or pressedkey == ord('q')
            else:
                pressedkey = -1
                isexitkey = False

            # if pressedkey == curses.KEY_F5:
            #     # Were asked to refresh
            #     return isexitkey

            # if isexitkey and self.args.help_tag:
            #     # Quit from help should return to main screen, not exit #1874
            #     self.args.help_tag = not self.args.help_tag
            #     isexitkey = False
            #     return isexitkey

            # Redraw display
            self.live.update(self.layout, refresh=True)
            # Overwrite the timeout with the countdown
            time.sleep(countdown.get())

        return isexitkey

    def update_layout(self, stats):
        """Update the layout with the stats"""
        # Get the stats and apply the Rich transformation
        stats_display = self.plugins_to_rich(stats)
        self._create_main_layout(stats_display)
        self._update_top_layout(stats, stats_display)
        self._update_middle_left_layout(stats, stats_display)
        self._update_middle_right_layout(stats, stats_display)
        self._update_bottom_layout(stats, stats_display)

    def _create_main_layout(self, stats_display):
        # Create the layout
        self.layout.split_column(
            Layout(name='top',
                   size=max([stats_display[p]['height'] if stats_display[p]['display'] else 0 for p in _top]),
                   renderable=False),
            Layout(name='middle',
                   renderable=False),
            Layout(name='bottom',
                   size=max([stats_display[p]['height'] if stats_display[p]['display'] else 0 for p in _bottom]),
                   renderable=False),
        )
        self.layout['middle'].split_row(
            Layout(name='middle_left',
                   size=_middle_left_width + 8,
                   renderable=False),
            Layout(name='middle_right',
                   renderable=False)
        )

    def _update_top_layout(self, stats, stats_display):
        """Update the top layout"""
        renderable = []
        for p in _top:
            # The quicklook plugin will be ignore...
            if stats_display[p]['display'] and len(stats_display[p]['content']) > 0:
                r = Layout(stats_display[p]['content_repr'],
                           size=stats_display[p]['width'],
                           name=p)
                renderable.append(r)
        self.layout['top'].split_row(*renderable)

    def _update_middle_left_layout(self, stats, stats_display):
        """Update the middle left layout"""
        self.layout['middle_left'].split_column(
            *[Layout(stats_display[p]['content_repr'],
                     size=stats_display[p]['height'],
                     name=p) for p in _middle_left
              if stats_display[p]['display'] and len(stats_display[p]['content']) > 0],
            Layout(Padding(''),
                   name='middle_left_padding')
        )

    def _update_middle_right_layout(self, stats, stats_display):
        """Update the middle right layout"""
        renderable = []
        for p in _middle_right:
            # The quicklook plugin will be ignore...
            if stats_display[p]['display'] and len(stats_display[p]['content']) > 0:
                r = Layout(Panel(stats_display[p]['content_repr'],
                                 title=stats_display[p]['title'],
                                 subtitle=stats_display[p]['subtitle']),
                           size=stats_display[p]['height'],
                           name=p)
                renderable.append(r)
        self.layout['middle_right'].split_column(*renderable)

    def _update_bottom_layout(self, stats, stats_display):
        """Update the bottom layout"""
        self.layout['bottom'].split_row(
            *[Layout(
                Panel(stats_display[p]['content_repr'],
                      title=stats_display[p]['title'],
                      subtitle=stats_display[p]['subtitle']),
                name=p) for p in _bottom
              if stats_display[p]['display'] and len(stats_display[p]['content']) > 0]
        )

    def plugins_to_rich(self, stats):
        """Get the 'Rich' stats from the plugins
        Return: a dict of dicts with:
            - key: plugin name
            - value: dict returned by _plugin_to_rich
        Ex: {'cpu': {'title': '', 'subtitle': '', 'content': '', 'width': 0, 'height': 0, 'display': False}, ... }
        """
        ret = {}
        # Some plugin should be processed after others
        after = ['quicklook', 'processlist']
        for p in [p for p in stats.getPluginsList(enable=False) if p not in after]:
            ret[p] = self._plugin_to_rich(stats, p)
        # It is time to process its
        for p in after:
            if p == 'processlist':
                height_but_processlist = max([ret[p]['height'] for p in _top if p in ret]) + \
                    sum([ret[p]['height'] for p in _middle_right if p in ret]) + \
                    max([ret[p]['height'] for p in _bottom if p in ret])
                glances_processes.max_processes = self.console.height - height_but_processlist
                ret[p] = self._plugin_to_rich(stats, p, max_width=None)
            else:
                width_but_after = sum([ret[p]['width']
                                      for p in _top if p in ret and len(ret[p]['content']) > 0 and ret[p]['display']])
                max_width = self.console.width - width_but_after - 13
                ret[p] = self._plugin_to_rich(stats, p, max_width=max_width)
        return ret

    def _plugin_to_rich(self, stats, plugin, max_width=None):
        """Return a dict: Rich representation of the plugin"""

        # Init the returned structure
        ret = {
            'title': '',
            'subtitle': '',
            'content': '',
            'width': 0,
            'height': 0,
            'display': False
        }

        if not stats.get_plugin(plugin):
            return ret

        if plugin in _middle_left:
            max_width = _middle_left_width

        if hasattr(stats.get_plugin(plugin), 'msg_for_human') and stats.get_plugin(plugin).get_template():
            # Grab the stats to display
            ret = stats.get_plugin(plugin).msg_for_human(args=self.args,
                                                         max_width=max_width)

            # TODO: Style should be moved in a dedicated class
            # decoration:
            #     DEFAULT: no decoration
            #     UNDERLINE: underline
            #     BOLD: bold