├── MANIFEST.in ├── art ├── logo.png ├── austin-tui.gif ├── austin-tui-save.png ├── austin-tui-vscode.gif ├── austin-tui-full-mode.png ├── austin-tui-threshold.png ├── austin-tui-flamegraph.gif └── austin-tui-normal-mode.png ├── .github ├── FUNDING.yml └── workflows │ ├── release.yml │ ├── checks.yml │ └── tests.yml ├── tests ├── target.py ├── mcurses.py ├── test_cli.py ├── test_point.py ├── test_view.py └── test_widgets.py ├── .flake8 ├── ISSUE_TEMPLATE.md ├── .travis.yml ├── CONTRIBUTING.md ├── .gitignore ├── PULL_REQUEST_TEMPLATE.md ├── austin_tui ├── widgets │ ├── command_bar.py │ ├── catalog.py │ ├── selector.py │ ├── table.py │ ├── window.py │ ├── box.py │ ├── graph.py │ ├── markup.py │ ├── scroll.py │ ├── __init__.py │ └── label.py ├── __init__.py ├── view │ ├── palette.py │ ├── austin.py │ ├── __init__.py │ └── tui.austinui ├── model │ ├── __init__.py │ ├── system.py │ └── austin.py ├── __main__.py ├── controller.py └── adapters.py ├── CODE-OF-CONDUCT.md ├── pyproject.toml ├── README.md └── LICENSE.md /MANIFEST.in: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /art/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/logo.png -------------------------------------------------------------------------------- /art/austin-tui.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui.gif -------------------------------------------------------------------------------- /art/austin-tui-save.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-save.png -------------------------------------------------------------------------------- /art/austin-tui-vscode.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-vscode.gif -------------------------------------------------------------------------------- /art/austin-tui-full-mode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-full-mode.png -------------------------------------------------------------------------------- /art/austin-tui-threshold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-threshold.png -------------------------------------------------------------------------------- /art/austin-tui-flamegraph.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-flamegraph.gif -------------------------------------------------------------------------------- /art/austin-tui-normal-mode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/P403n1x87/austin-tui/HEAD/art/austin-tui-normal-mode.png -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: p403n1x87 2 | patreon: P403n1x87 3 | custom: ["https://www.buymeacoffee.com/Q9C1Hnm28", "https://www.paypal.me/gtornetta/1"] 4 | -------------------------------------------------------------------------------- /tests/target.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | def fibonacci(n): 5 | if n == 0: 6 | return 1 7 | if n == 1: 8 | return 1 9 | return fibonacci(n - 1) + fibonacci(n - 2) 10 | 11 | 12 | for i in range(10, 18): 13 | fibonacci(i << 1) 14 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | select = ANN,B,B9,C,D,E,F,W,I 3 | ignore = ANN101,ANN102,ANN401,B950,D100,D104,D107,E203,E402,E501,F401,W503,W606 4 | max-line-length = 80 5 | docstring-convention = google 6 | application-import-names = austin_tui 7 | import-order-style = google 8 | per-file-ignores = 9 | test/*:ANN,D 10 | noxfile.py:ANN,D 11 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | 13 | - uses: actions/setup-python@v4 14 | with: 15 | python-version: '3.12' 16 | 17 | - run: | 18 | pip install hatch hatch-vcs 19 | hatch build 20 | hatch publish --user=__token__ --auth=${{ secrets.PYPI_TOKEN }} 21 | -------------------------------------------------------------------------------- /tests/mcurses.py: -------------------------------------------------------------------------------- 1 | class MWindow: 2 | def __init__(self, width, height): 3 | self.x = width 4 | self.y = height 5 | 6 | def getmaxyx(self): 7 | return (self.y, self.x) 8 | 9 | def addstr(self, *args, **kwargs): 10 | pass 11 | 12 | def refresh(self): 13 | pass 14 | 15 | def resize(self, *args, **kwargs): 16 | pass 17 | 18 | def clear(self): 19 | pass 20 | 21 | def vline(self, *args, **kwargs): 22 | pass 23 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from contextlib import contextmanager 3 | 4 | import pytest 5 | 6 | from austin_tui.__main__ import main 7 | 8 | 9 | @contextmanager 10 | def override_argv(args): 11 | original_argv = sys.argv 12 | sys.argv = args 13 | try: 14 | yield 15 | finally: 16 | sys.argv = original_argv 17 | 18 | 19 | def test_main_no_args(capsys): 20 | with pytest.raises(SystemExit) as e, override_argv(["austin-tui"]): 21 | main() 22 | assert e.value.code == -1 23 | assert "No PID" in capsys.readouterr().err 24 | -------------------------------------------------------------------------------- /tests/test_point.py: -------------------------------------------------------------------------------- 1 | from austin_tui.widgets import Point 2 | 3 | 4 | def test_point_along(): 5 | assert Point(5 + 4j).along(1) == 5 6 | assert Point(5 + 4j).along(1j) == 4j 7 | assert Point(5 + 4j).along(2j) == 4j 8 | 9 | 10 | def test_point_tuple(): 11 | assert Point(3 + 4j).to_tuple == (3, 4) 12 | assert Point(3 + 4j).along(1).to_tuple == (3, 0) 13 | assert Point(3 + 4j).along(1j).to_tuple == (0, 4) 14 | 15 | 16 | def test_point_perp(): 17 | size = Point(10, 20) 18 | dir = 1 + 0j 19 | perp = size.along(1j * dir.conjugate()) 20 | assert perp == Point(20j) 21 | 22 | assert Point(perp + 5 * dir) == Point(5 + 20j) 23 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | 3 | [Description of the issue] 4 | 5 | ### Steps to Reproduce 6 | 7 | 1. [First Step] 8 | 2. [Second Step] 9 | 3. [and so on...] 10 | 11 | **Expected behavior:** [What you expect to happen] 12 | 13 | **Actual behavior:** [What actually happens] 14 | 15 | **Reproduces how often:** [What percentage of the time does it reproduce?] 16 | 17 | ### Versions 18 | 19 | You can get this information from copy and pasting the output of `austin 20 | --version` from the command line. Also, please include the OS and what version 21 | of the OS you're running. 22 | 23 | ### Additional Information 24 | 25 | Any additional information, configuration or data that might be necessary to 26 | reproduce the issue. 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | os: linux 3 | 4 | git: 5 | depth: 1 6 | 7 | osx_image: xcode10 8 | 9 | dist: bionic 10 | 11 | jobs: 12 | include: 13 | # Linux 14 | - os: linux 15 | 16 | before_script: 17 | # Install required Python versions 18 | - sudo add-apt-repository ppa:deadsnakes/ppa -y 19 | - sudo apt-get install -y python3.{6..9} python3.{6..9}-dev python3.9-venv; 20 | 21 | # Clone Austin development branch 22 | - git clone --branch devel --depth 1 https://github.com/P403n1x87/austin.git ../austin 23 | 24 | # Compile Austin 25 | - cd ../austin 26 | - gcc -Wall -O3 -Os -s -pthread src/*.c -o src/austin 27 | - cd - 28 | 29 | - pip install nox 30 | - pip install poetry 31 | 32 | script: 33 | - export PATH="../austin/src:$PATH" 34 | - nox 35 | # nox -rs coverage 36 | -------------------------------------------------------------------------------- /.github/workflows/checks.yml: -------------------------------------------------------------------------------- 1 | name: Checks 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | typing: 11 | runs-on: "ubuntu-latest" 12 | 13 | name: Type checking 14 | steps: 15 | - uses: actions/checkout@v4 16 | 17 | - uses: actions/setup-python@v4 18 | with: 19 | python-version: "3.12" 20 | 21 | - run: | 22 | pip install hatch 23 | hatch -e checks run typing 24 | 25 | linting: 26 | runs-on: "ubuntu-latest" 27 | 28 | name: Linting 29 | steps: 30 | - uses: actions/checkout@v4 31 | 32 | - uses: actions/setup-python@v4 33 | with: 34 | python-version: "3.12" 35 | 36 | - run: | 37 | pip install hatch 38 | hatch -e checks run linting 39 | -------------------------------------------------------------------------------- /tests/test_view.py: -------------------------------------------------------------------------------- 1 | from austin_tui.view import ViewBuilder 2 | from austin_tui.view.austin import AustinView 3 | from austin_tui.widgets import Point 4 | from austin_tui.widgets import Rect 5 | from tests.mcurses import MWindow 6 | 7 | 8 | def test_austin_view(): 9 | view_builder = ViewBuilder.from_resource("austin_tui.view", "tui.austinui") 10 | 11 | view = view_builder.build() # type: ignore[assignment] 12 | 13 | root = view.root_widget 14 | root._win = MWindow(80, 32) 15 | root.resize(Rect(0, root.get_size())) 16 | 17 | assert view.main.rect == Rect(0, 80 + 32j) 18 | assert view.main_box.rect == Rect(0, 80 + 32j) 19 | assert view.info_box.rect == Rect(0, 80 + 4j) 20 | 21 | assert view.dataview_selector.rect == Rect(4j, 80 + 27j) 22 | 23 | view.dataview_selector.select(1) 24 | root.resize(Rect(0, root.get_size())) 25 | 26 | assert view.dataview_selector.rect == Rect(4j, 80 + 27j) 27 | assert view.flame_view.rect == Rect(5j, 80 + 26j) 28 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Austin 2 | 3 | Thanks for taking the time to contribute or considering doing so. 4 | 5 | The following is a set of guidelines for contributing to Austin TUI. 6 | 7 | ## Preamble 8 | 9 | TBD 10 | 11 | 12 | ## The Coding Style 13 | 14 | TBD 15 | 16 | 17 | ## Opening PRs 18 | 19 | Everybody is more than welcome to open a PR to fix a bug/propose enhancements/ 20 | implement missing features. If you do, please adhere to the following 21 | styleguides as much as possible. 22 | 23 | 24 | ### Git Commit Messages 25 | 26 | This styleguide is taken from the Atom project. 27 | 28 | * Use the present tense ("Add feature" not "Added feature") 29 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...") 30 | * Limit the first line to 72 characters or less 31 | * Reference issues and pull requests liberally after the first line 32 | 33 | 34 | ### Labels 35 | 36 | When opening a new PR, please apply a label to them. Try to use existing labels 37 | as much as possible and only create a new one if the current ones are not 38 | applicable. 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Sphinx documentation 59 | docs/_build/ 60 | 61 | # Environments 62 | .env 63 | .venv 64 | env/ 65 | venv/ 66 | ENV/ 67 | env.bak/ 68 | venv.bak/ 69 | 70 | # mypy 71 | .mypy_cache/ 72 | .dmypy.json 73 | dmypy.json 74 | 75 | # Pyre type checker 76 | .pyre/ 77 | 78 | # pytype static type analyzer 79 | .pytype/ 80 | 81 | # Nox 82 | .nox 83 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Requirements for Adding, Changing, Fixing or Removing a Feature 2 | 3 | Fill out the template below. Any pull request that does not include enough 4 | information to be reviewed in a timely manner may be closed at the maintainers' 5 | discretion. 6 | 7 | 8 | ### Description of the Change 9 | 10 | 16 | 17 | ### Alternate Designs 18 | 19 | 21 | 22 | ### Regressions 23 | 24 | 29 | 30 | ### Verification Process 31 | 32 | 42 | -------------------------------------------------------------------------------- /austin_tui/widgets/command_bar.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from austin_tui.widgets.box import Box 24 | 25 | 26 | class CommandBar(Box): 27 | """A command bar that spans the whole width of the parent container.""" 28 | 29 | def __init__(self, name: str) -> None: 30 | super().__init__(name, flow="h") 31 | 32 | def draw(self) -> bool: 33 | """Draw the command bar.""" 34 | try: 35 | return super().draw() 36 | finally: 37 | self.win.get_win().clrtoeol() 38 | -------------------------------------------------------------------------------- /austin_tui/widgets/catalog.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from austin_tui.widgets.box import Box 24 | from austin_tui.widgets.command_bar import CommandBar 25 | from austin_tui.widgets.graph import FlameGraph 26 | from austin_tui.widgets.label import BarPlot 27 | from austin_tui.widgets.label import Label 28 | from austin_tui.widgets.label import Line 29 | from austin_tui.widgets.label import ToggleLabel 30 | from austin_tui.widgets.scroll import ScrollView 31 | from austin_tui.widgets.selector import Selector 32 | from austin_tui.widgets.table import Table 33 | from austin_tui.widgets.window import Window 34 | -------------------------------------------------------------------------------- /austin_tui/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import os 24 | import sys 25 | from enum import Enum 26 | from traceback import format_exception 27 | 28 | 29 | class AustinProfileMode(Enum): 30 | """Austin profile modes.""" 31 | 32 | TIME = "Time" 33 | MEMORY = "Memory" 34 | 35 | 36 | if os.environ.get("AUSTIN_TUI_DEBUG"): 37 | _original_excepthook = sys.excepthook 38 | 39 | def _excepthook(exc_type, exc, tb): 40 | try: 41 | os.remove("austin-tui.exc") 42 | except Exception: 43 | pass 44 | with open("austin-tui.exc", "w") as fout: 45 | fout.writelines(format_exception(exc_type, exc, tb)) 46 | _original_excepthook(exc_type, exc, tb) 47 | 48 | sys.excepthook = _excepthook 49 | -------------------------------------------------------------------------------- /austin_tui/view/palette.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | 24 | import curses 25 | from typing import Dict 26 | from typing import Tuple 27 | 28 | 29 | class PaletteError(Exception): 30 | """Palette generic error.""" 31 | 32 | pass 33 | 34 | 35 | class Palette: 36 | """Palette object. 37 | 38 | This is essentially a wrapper around the concept of curses color pairs. 39 | """ 40 | 41 | def __init__(self) -> None: 42 | self._colors = {"default": 0} 43 | self._color_pairs: Dict[int, Tuple[int, int]] = {} 44 | 45 | def add_color(self, name: str, fg: int = -1, bg: int = -1) -> None: 46 | """Add a color pair to the palette.""" 47 | color_id = len(self._colors) 48 | self._colors[name] = color_id 49 | self._color_pairs[color_id] = (int(fg), int(bg)) 50 | 51 | def get_color(self, name: str) -> int: 52 | """Get the color by name.""" 53 | try: 54 | return getattr(self, name) 55 | except KeyError: 56 | raise PaletteError(f"The palette has no color '{name}'") from None 57 | 58 | def __getattr__(self, name: str) -> int: 59 | """Convenience accessor for colors from the palette.""" 60 | return self._colors[name] 61 | 62 | def init(self) -> None: 63 | """Initialise the curses color pairs.""" 64 | try: 65 | for cid, pair in self._color_pairs.items(): 66 | curses.init_pair(cid, *pair) 67 | except curses.error: 68 | curses.use_default_colors() 69 | -------------------------------------------------------------------------------- /austin_tui/model/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from typing import Optional 24 | 25 | from austin_tui.model.austin import AustinModel 26 | from austin_tui.model.system import FrozenSystemModel 27 | from austin_tui.model.system import SystemModel 28 | 29 | 30 | class Model: 31 | """The application model.""" 32 | 33 | __slots__ = ("austin", "system", "frozen_austin", "frozen_system", "frozen") 34 | 35 | _instance: Optional["Model"] = None 36 | 37 | @classmethod 38 | def get(cls) -> "Model": 39 | """Get the single model instance.""" 40 | if cls._instance is not None: 41 | return cls._instance 42 | 43 | model = cls._instance = cls() 44 | return model 45 | 46 | def __init__(self) -> None: 47 | self.austin = AustinModel() 48 | self.system = SystemModel() 49 | self.frozen_austin: Optional[AustinModel] = None 50 | self.frozen_system: Optional[FrozenSystemModel] = None 51 | self.frozen = False 52 | 53 | def toggle_freeze(self) -> None: 54 | """Toggle the freeze status.""" 55 | if self.frozen: 56 | self.unfreeze() 57 | else: 58 | self.freeze() 59 | 60 | def freeze(self) -> None: 61 | """Freeze the model.""" 62 | self.frozen_austin = self.austin.freeze() 63 | self.frozen_system = self.system.freeze() 64 | self.frozen = True 65 | 66 | def unfreeze(self) -> None: 67 | """Unfreeze the model.""" 68 | self.frozen_austin = None 69 | self.frozen_system = None 70 | self.frozen = False 71 | -------------------------------------------------------------------------------- /austin_tui/model/system.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import time 24 | 25 | from psutil import NoSuchProcess 26 | from psutil import Process 27 | 28 | 29 | Seconds = float 30 | Percentage = float 31 | Bytes = int 32 | 33 | 34 | class FrozenSystemModel: 35 | """Frozen system model data.""" 36 | 37 | __slots__ = ("duration", "max_memory") 38 | 39 | def __init__(self, duration: Seconds, max_memory: Bytes) -> None: 40 | self.duration = duration 41 | self.max_memory = max_memory 42 | 43 | 44 | class SystemModel: 45 | """System statistics model.""" 46 | 47 | def __init__(self) -> None: 48 | self._start_time: Seconds = 0 49 | self._end_time: Seconds = 0 50 | 51 | self._max_mem: Bytes = 0 52 | 53 | self.child_process = None 54 | 55 | def start(self) -> None: 56 | """Start the model.""" 57 | self._start_time = time.time() 58 | 59 | def stop(self) -> None: 60 | """Stop the model.""" 61 | self._end_time = time.time() 62 | 63 | @property 64 | def duration(self) -> Seconds: 65 | """Get the sampling duration.""" 66 | return ( 67 | (self._end_time or time.time()) - self._start_time 68 | if self._start_time 69 | else 0 70 | ) 71 | 72 | def set_child_process(self, child_process: Process) -> None: 73 | """Set the child process.""" 74 | self.child_process = child_process 75 | 76 | def get_cpu(self, process: Process) -> Percentage: 77 | """Get the process CPU usage.""" 78 | try: 79 | return int(process.cpu_percent()) 80 | except NoSuchProcess: 81 | return 0 82 | 83 | def get_memory(self, process: Process) -> Bytes: 84 | """Get the process memory.""" 85 | try: 86 | mem = process.memory_full_info()[0] 87 | self._max_mem = max(mem, self._max_mem) 88 | return mem 89 | except NoSuchProcess: 90 | return 0 91 | 92 | @property 93 | def max_memory(self) -> Bytes: 94 | """Return the maximum memory usage seen so far.""" 95 | return self._max_mem 96 | 97 | def freeze(self) -> FrozenSystemModel: 98 | """Freeze the model data.""" 99 | return FrozenSystemModel(self.duration, self.max_memory) 100 | -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | -------------------------------------------------------------------------------- /austin_tui/widgets/selector.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2022 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from typing import Optional 24 | 25 | from austin_tui.widgets import BaseContainer 26 | from austin_tui.widgets import Rect 27 | from austin_tui.widgets import Widget 28 | 29 | 30 | class SelectorError(Exception): 31 | """Generic selector error.""" 32 | 33 | pass 34 | 35 | 36 | class Selector(BaseContainer): 37 | """Selector widget. 38 | 39 | Allows toggling between a set of widgets to display at a time. 40 | """ 41 | 42 | def __init__(self, name: str) -> None: 43 | super().__init__(name) 44 | self._selected = 0 45 | 46 | @property 47 | def selected(self) -> Optional[Widget]: 48 | """Get the selected widget.""" 49 | try: 50 | return self._children[self._selected] 51 | except IndexError as e: 52 | raise SelectorError("Invalid selection") from e 53 | 54 | def select(self, index: int) -> None: 55 | """Select the widget to display.""" 56 | if not (0 <= index < len(self._children)): 57 | raise SelectorError(f"Invalid selector index: {index}") 58 | 59 | if self._selected != index: 60 | self.hide() 61 | self._selected = index 62 | self.show() 63 | self.selected.resize(self.rect) 64 | self.draw() 65 | self.refresh() 66 | 67 | def show(self) -> None: 68 | """Show the selected widget.""" 69 | try: 70 | self.selected.show() 71 | except SelectorError: 72 | pass 73 | 74 | def hide(self) -> None: 75 | """Hide the selected widget.""" 76 | try: 77 | self.selected.hide() 78 | except SelectorError: 79 | pass 80 | 81 | def draw(self) -> bool: 82 | """Draw the selected widget.""" 83 | try: 84 | return self.selected.draw() 85 | except SelectorError: 86 | return False 87 | 88 | def resize(self, rect: Rect) -> bool: 89 | """Resize the selected widget.""" 90 | if self.rect == rect: 91 | return False 92 | 93 | self.rect = rect 94 | 95 | try: 96 | return self.selected.resize(rect) 97 | except SelectorError: 98 | return False 99 | 100 | def refresh(self) -> None: 101 | """Refresh the selected widget.""" 102 | super().refresh() 103 | 104 | try: 105 | self.selected.refresh() 106 | except SelectorError: 107 | pass 108 | -------------------------------------------------------------------------------- /austin_tui/widgets/table.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from typing import Any 24 | from typing import List 25 | 26 | from austin_tui.widgets import Rect 27 | from austin_tui.widgets import Widget 28 | from austin_tui.widgets.markup import Writable 29 | 30 | 31 | TableData = List[List[Any]] 32 | 33 | 34 | class Table(Widget): 35 | """Table widget. 36 | 37 | Requires a number of colums. 38 | """ 39 | 40 | def __init__(self, name: str, columns: Any) -> None: 41 | super().__init__(name) 42 | 43 | self._cols = int(columns) 44 | self._data: TableData = [] 45 | 46 | def _show_empty(self) -> bool: 47 | win = self.win.get_win() 48 | if not win: 49 | return False 50 | 51 | win.clear() 52 | 53 | return True 54 | 55 | def _draw_row(self, i: int, row: List[Any]) -> None: 56 | x = 0 57 | available = self.rect.size.x - 1 58 | win = self.win.get_win() 59 | for j in range(self._cols): 60 | if available <= x: 61 | break 62 | text = row[j] 63 | if isinstance(row[j], Writable): 64 | delta = text.write(win, i, x, available - x) 65 | else: 66 | text = row[j] 67 | win.addstr(i, x, text[: available - x], 0) 68 | delta = min(available - x, len(text)) 69 | x += delta 70 | 71 | def set_data(self, data: TableData) -> bool: 72 | """Set the table data. 73 | 74 | The format is a list of rows, with each row representing the content of 75 | each cell. 76 | """ 77 | if data != self._data: 78 | self._data = data 79 | self._height = len(data) 80 | self.parent.resize(self.parent.rect) 81 | return True 82 | 83 | return False 84 | 85 | def resize(self, rect: Rect) -> bool: 86 | """Resize the table.""" 87 | if self.rect == rect: 88 | return False 89 | 90 | self.rect = rect 91 | 92 | self.draw() 93 | 94 | return True 95 | 96 | def draw(self) -> bool: 97 | """Draw the table.""" 98 | super().draw() 99 | 100 | if not self.win: 101 | return False 102 | 103 | if not self._data: 104 | return self._show_empty() 105 | else: 106 | win = self.win.get_win() 107 | if not win: 108 | return False 109 | win.clear() 110 | for i, e in enumerate(self._data, self.pos.y): 111 | self._draw_row(i, e) 112 | 113 | return True 114 | -------------------------------------------------------------------------------- /austin_tui/widgets/window.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from typing import Optional 25 | from typing import Tuple 26 | 27 | from austin_tui.widgets import Container 28 | from austin_tui.widgets import Point 29 | from austin_tui.widgets import Rect 30 | 31 | 32 | class Window(Container): 33 | """Window container. 34 | 35 | This is, essentially, a wrapper around the ``curses.win`` object. 36 | """ 37 | 38 | def __init__(self, name: str) -> None: 39 | super().__init__(name) 40 | self.win = self 41 | 42 | async def on_resize(self) -> bool: 43 | """The resize event handler.""" 44 | return self.resize(Rect(pos=0, size=self.get_size())) 45 | 46 | def resize(self, rect: Rect) -> bool: 47 | """Resize the window. 48 | 49 | This is effectively resizing just the child widget, as the window itself 50 | is just a logical container. 51 | """ 52 | super().resize(rect) 53 | 54 | if self.rect == rect: 55 | return False 56 | 57 | self.rect = rect 58 | 59 | if not self._children: 60 | return False 61 | 62 | (child,) = self._children 63 | 64 | if child.resize(rect): 65 | self.refresh() 66 | return True 67 | 68 | return False 69 | 70 | def show(self) -> None: 71 | """Show the window on screen.""" 72 | if self._win is not None: 73 | return 74 | 75 | self._win = curses.initscr() 76 | try: 77 | curses.noecho() 78 | curses.cbreak() 79 | self._win.keypad(True) 80 | try: 81 | curses.start_color() 82 | except Exception: 83 | pass 84 | 85 | curses.use_default_colors() 86 | curses.curs_set(False) 87 | 88 | self._win.clear() 89 | self._win.timeout(0) # non-blocking for async I/O 90 | self._win.nodelay(True) 91 | 92 | super().show() 93 | except Exception: 94 | curses.endwin() 95 | raise 96 | 97 | def hide(self) -> None: 98 | """Hide the window. 99 | 100 | Also restore the terminal to a sane status. 101 | """ 102 | if self._win is None: 103 | return 104 | 105 | self._win.keypad(False) 106 | curses.echo() 107 | curses.nocbreak() 108 | curses.endwin() 109 | 110 | self._win = None 111 | 112 | def get_size(self) -> Point: 113 | """Get the window size. 114 | 115 | As per curses convention this returns the tuple (_height_, _width_). 116 | """ 117 | y, x = self._win.getmaxyx() 118 | return Point(x, y) 119 | 120 | def get_win(self) -> Optional["curses._CursesWindow"]: 121 | """Get the underlying curses window. 122 | 123 | Use with care. 124 | """ 125 | return self._win 126 | 127 | def is_visible(self) -> bool: 128 | """Whether the window is visible.""" 129 | return self._win is not None 130 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is a Python wrapper around Austin, the CPython frame stack 7 | # sampler. 8 | # 9 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 10 | # All rights reserved. 11 | # 12 | # This program is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the License, or 15 | # (at your option) any later version. 16 | # 17 | # This program is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | # GNU General Public License for more details. 21 | # You should have received a copy of the GNU General Public License 22 | # along with this program. If not, see . 23 | 24 | [project] 25 | authors = [{ name = "Gabriele N. Tornetta", email = "phoenix1987@gmail.com" }] 26 | description = "The top-like text-based user interface for Austin" 27 | license = "GPL-3.0-or-later" 28 | name = "austin-tui" 29 | readme = "README.md" 30 | 31 | classifiers = [ 32 | "Development Status :: 5 - Production/Stable", 33 | "Intended Audience :: Developers", 34 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 35 | "Programming Language :: Python :: 3.9", 36 | "Programming Language :: Python :: 3.10", 37 | "Programming Language :: Python :: 3.11", 38 | "Programming Language :: Python :: 3.12", 39 | "Programming Language :: Python :: 3.13", 40 | ] 41 | keywords = ["performance", "profiling", "testing", "development"] 42 | 43 | dependencies = [ 44 | "austin-python~=2.1", 45 | "importlib_resources~=5.10", 46 | "lxml~=5.0", 47 | "psutil", 48 | "windows-curses~=2.1; sys_platform == 'win32'", 49 | ] 50 | requires-python = ">=3.9" 51 | 52 | dynamic = ["version"] 53 | 54 | [project.urls] 55 | documentation = "https://austin-tui.readthedocs.io" 56 | homepage = "https://github.com/P403n1x87/austin-tui" 57 | issues = "https://github.com/P403n1x87/austin-tui/issues" 58 | repository = "https://github.com/P403n1x87/austin-tui" 59 | 60 | [project.scripts] 61 | austin-tui = "austin_tui.__main__:main" 62 | 63 | [tool.hatch.envs.tests] 64 | dependencies = ["pytest>=5.4.2", "pytest-cov>=2.8.1"] 65 | template = "tests" 66 | [tool.hatch.envs.tests.scripts] 67 | tests = "pytest --cov=austin --cov-report=term-missing --cov-report=xml {args}" 68 | 69 | [[tool.hatch.envs.tests.matrix]] 70 | python = ["3.9", "3.10", "3.11", "3.12", "3.13"] 71 | 72 | [tool.hatch.envs.checks] 73 | dependencies = [ 74 | "mypy~=1.0", 75 | "flake8~=5.0.4", 76 | "flake8-annotations~=2.9.1", 77 | "flake8-black", 78 | "flake8-bugbear~=22.9.23", 79 | "flake8-docstrings~=1.6.0", 80 | "flake8-import-order~=0.18.1", 81 | "flake8-isort~=5.0.0", 82 | ] 83 | python = "3.12" 84 | template = "checks" 85 | 86 | [tool.hatch.envs.checks.scripts] 87 | linting = "flake8 {args} austin_tui/ test/ " 88 | typing = "mypy --show-error-codes --install-types --non-interactive {args} austin_tui/ tests/" 89 | 90 | [tool.hatch.envs.coverage] 91 | dependencies = ["coverage[toml]", "codecov"] 92 | python = "3.12" 93 | template = "coverage" 94 | 95 | [tool.hatch.envs.coverage.scripts] 96 | cov = "coverage xml --fail-under=0" 97 | 98 | [tool.hatch.version] 99 | source = "vcs" 100 | 101 | [tool.hatch.build.targets.sdist] 102 | exclude = ["/.github", "/docs"] 103 | 104 | [tool.hatch.build.targets.wheel] 105 | packages = ["austin_tui"] 106 | 107 | [tool.coverage.run] 108 | branch = true 109 | source = ["austin_tui"] 110 | 111 | [tool.coverage.report] 112 | show_missing = true 113 | 114 | [tool.isort] 115 | force_single_line = true 116 | lines_after_imports = 2 117 | profile = "black" 118 | 119 | [tool.mypy] 120 | exclude = [] 121 | ignore_missing_imports = true 122 | 123 | [[tool.mypy.overrides]] 124 | ignore_errors = true 125 | module = [] 126 | 127 | [build-system] 128 | build-backend = "hatchling.build" 129 | requires = ["hatchling", "hatch-vcs"] 130 | -------------------------------------------------------------------------------- /austin_tui/widgets/box.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from typing import List 24 | 25 | from austin_tui.widgets import Container 26 | from austin_tui.widgets import Point 27 | from austin_tui.widgets import Rect 28 | 29 | 30 | class Box(Container): 31 | """A flex box widget. 32 | 33 | The ``flow`` is either ``h``orizontal or ``v``ertical. 34 | """ 35 | 36 | def __init__(self, name: str, flow: str) -> None: 37 | if flow[0] not in ["v", "h"]: 38 | raise ValueError( 39 | f"Invalid value '{flow}' for attribute 'flow' of widget '{type(self)}'" 40 | ) 41 | 42 | self.flow = {"h": 1, "v": 1j}[flow[0]] 43 | 44 | super().__init__(name) 45 | 46 | def _dims(self, flow: complex) -> List[int]: 47 | return [ 48 | 0 49 | if child.expand.along(flow) 50 | else int(abs(Point(child.width, child.height).along(flow))) 51 | for child in self._children 52 | ] 53 | 54 | def _dimsum(self, flow: complex) -> int: 55 | dimensions = self._dims(flow) 56 | 57 | if 0 in dimensions: 58 | return 0 59 | 60 | return sum(dimensions) 61 | 62 | def _dimmax(self, flow: complex) -> int: 63 | dimensions = self._dims(flow) 64 | 65 | if not dimensions or 0 in dimensions: 66 | return 0 67 | 68 | return max(dimensions) 69 | 70 | @property 71 | def width(self) -> int: 72 | """The box width.""" 73 | if self.flow == 1: 74 | return self._dimsum(1) 75 | return self._dimmax(1) 76 | 77 | @property 78 | def height(self) -> int: 79 | """The box height.""" 80 | if self.flow == 1j: 81 | return self._dimsum(1j) 82 | return self._dimmax(1j) 83 | 84 | def resize(self, rect: Rect) -> bool: 85 | """Resize the box.""" 86 | refresh = super().resize(rect) 87 | 88 | if self.rect == rect: 89 | return False 90 | 91 | self.rect = rect 92 | 93 | # compute the height of expanding widgets 94 | dimensions = [ 95 | 0 96 | if child.expand.along(self.flow) 97 | else abs(Point(child.width, child.height).along(self.flow)) 98 | for child in self._children 99 | ] 100 | nvar = sum(_ == 0 for _ in dimensions) 101 | 102 | allocated_dim = sum(dimensions) 103 | remaining_dim = int(abs(self.size.along(self.flow)) - allocated_dim) 104 | 105 | if nvar: 106 | var_dim, res_dim = divmod(remaining_dim, nvar) 107 | else: 108 | var_dim, res_dim = 0, remaining_dim 109 | 110 | # place and resize children 111 | perp = Point(self.size.along(1j * self.flow.conjugate())) # type: ignore[call-overload] 112 | pos = self.pos 113 | for child, dim in zip(self._children, dimensions): 114 | size = perp 115 | if not dim: 116 | if res_dim: 117 | e = 1 118 | res_dim -= 1 119 | else: 120 | e = 0 121 | size = Point(size + (var_dim + e) * self.flow) 122 | else: 123 | size = Point(size + dim * self.flow) 124 | 125 | refresh |= child.resize(Rect(pos, size)) 126 | 127 | pos = Point(pos + size.along(self.flow)) 128 | 129 | return refresh 130 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | concurrency: 10 | group: ${{ github.head_ref || github.run_id }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | tests-linux: 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 20 | 21 | name: Tests with Python ${{ matrix.python-version }} on Linux 22 | steps: 23 | - uses: actions/checkout@v4 24 | with: 25 | path: main 26 | 27 | - uses: actions/setup-python@v4 28 | with: 29 | python-version: ${{ matrix.python-version }}-dev 30 | 31 | - name: Checkout Austin development branch 32 | uses: actions/checkout@master 33 | with: 34 | repository: P403n1x87/austin 35 | ref: devel 36 | path: austin 37 | 38 | - name: Compile Austin 39 | run: | 40 | cd $GITHUB_WORKSPACE/austin 41 | gcc -Wall -O3 -Os -s -pthread src/*.c -o src/austin 42 | 43 | - name: Install dependencies 44 | run: | 45 | sudo apt-get update -y 46 | sudo apt-get install -y binutils binutils-common 47 | addr2line -V 48 | 49 | - name: Run tests 50 | run: | 51 | cd $GITHUB_WORKSPACE/main 52 | export PATH="$GITHUB_WORKSPACE/austin/src:$PATH" 53 | pip install hatch 54 | hatch -e "tests.py${{ matrix.python-version }}" run tests 55 | 56 | - name: Publish coverage metrics 57 | run: | 58 | cd $GITHUB_WORKSPACE/main 59 | hatch -e coverage run cov 60 | hatch -e coverage run codecov 61 | if: matrix.python-version == '3.12' 62 | env: 63 | CODECOV_TOKEN: ${{secrets.CODECOV_TOKEN}} 64 | 65 | tests-macos: 66 | runs-on: macos-latest 67 | strategy: 68 | fail-fast: false 69 | matrix: 70 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 71 | 72 | name: Tests with Python ${{ matrix.python-version }} on MacOS 73 | steps: 74 | - uses: actions/checkout@v4 75 | with: 76 | path: main 77 | 78 | - uses: actions/setup-python@v4 79 | with: 80 | python-version: ${{ matrix.python-version }}-dev 81 | 82 | - name: Checkout Austin development branch 83 | uses: actions/checkout@master 84 | with: 85 | repository: P403n1x87/austin 86 | ref: devel 87 | path: austin 88 | 89 | - name: Compile Austin 90 | run: | 91 | cd $GITHUB_WORKSPACE/austin 92 | gcc -Wall -O3 -Os src/*.c -o src/austin 93 | 94 | - name: Remove signature from the Python binary 95 | run: | 96 | codesign --remove-signature /Library/Frameworks/Python.framework/Versions/${{ matrix.python-version }}/bin/python3 || true 97 | codesign --remove-signature /Library/Frameworks/Python.framework/Versions/${{ matrix.python-version }}/Resources/Python.app/Contents/MacOS/Python || true 98 | 99 | - name: Run tests 100 | run: | 101 | cd $GITHUB_WORKSPACE/main 102 | export PATH="$GITHUB_WORKSPACE/austin/src:$PATH" 103 | pip install hatch 104 | sudo hatch -e "tests.py${{ matrix.python-version }}" run tests 105 | 106 | tests-win: 107 | runs-on: windows-latest 108 | strategy: 109 | fail-fast: false 110 | matrix: 111 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 112 | 113 | name: Tests with Python ${{ matrix.python-version }} on Windows 114 | steps: 115 | - uses: actions/checkout@v4 116 | with: 117 | path: main 118 | 119 | - uses: actions/setup-python@v4 120 | with: 121 | python-version: ${{ matrix.python-version }}-dev 122 | 123 | - name: Checkout Austin development branch 124 | uses: actions/checkout@master 125 | with: 126 | repository: P403n1x87/austin 127 | ref: devel 128 | path: austin 129 | 130 | - name: Compile Austin on Windows 131 | run: | 132 | cd $env:GITHUB_WORKSPACE/austin 133 | gcc.exe -O3 -o src/austin.exe src/*.c -lpsapi -lntdll -Wall -Os -s 134 | 135 | - name: Run tests on Windows 136 | run: | 137 | cd $env:GITHUB_WORKSPACE/main 138 | $env:PATH="$env:GITHUB_WORKSPACE\austin\src;$env:PATH" 139 | pip install hatch 140 | hatch -e "tests.py${{ matrix.python-version }}" run tests 141 | -------------------------------------------------------------------------------- /austin_tui/widgets/graph.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2022 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from random import randrange 25 | from typing import Dict 26 | from typing import List 27 | from typing import Optional 28 | from typing import Tuple 29 | 30 | from austin_tui.widgets import Rect 31 | from austin_tui.widgets import Widget 32 | 33 | 34 | FlameGraphData = Dict[str, Tuple[float, "FlameGraphData"]] # type: ignore[misc] 35 | 36 | 37 | class FlameGraph(Widget): 38 | """Flame graph widget.""" 39 | 40 | def __init__(self, name: str) -> None: 41 | super().__init__(name) 42 | 43 | self._data: Optional[dict] = None 44 | self._height = 40 45 | self._palette: Optional[Tuple[List[int], List[int]]] = None 46 | 47 | def set_palette(self, palette: Tuple[List[int], List[int]]) -> None: 48 | """Set the flame graph palette.""" 49 | self._palette = palette 50 | 51 | def resize(self, rect: Rect) -> bool: 52 | """Resize the table.""" 53 | if self.rect == rect: 54 | return False 55 | 56 | self.rect = rect 57 | 58 | self.draw() 59 | 60 | return True 61 | 62 | def set_data(self, data: dict) -> bool: 63 | """Set the graph data.""" 64 | 65 | def h(s: dict, scale: float) -> int: 66 | if not s: 67 | return 1 68 | 69 | return 1 + max( 70 | ( 71 | h(c, scale) 72 | for c in (_[1] for _ in s.values() if _[0] * scale * 8 >= 1) 73 | ), 74 | default=0, 75 | ) 76 | 77 | if data != self._data: 78 | self._data = data 79 | 80 | w = self.size.x 81 | for _, (v, _) in self._data.items(): 82 | scale = w / v 83 | 84 | self._height = h(data, scale) 85 | self.parent.resize(self.parent.rect) 86 | return True 87 | 88 | return False 89 | 90 | def _draw_frame(self, x: int, y: int, w: float, text: str) -> None: 91 | win = self.win.get_win() 92 | 93 | iw = int(w) 94 | fw = int((w - iw) * 8) 95 | 96 | assert self._palette is not None, self._palette 97 | fg, fgf = self._palette 98 | 99 | i = randrange(0, len(fg)) 100 | 101 | color = curses.color_pair(fg[i]) 102 | fcolor = curses.color_pair(fgf[i]) 103 | 104 | try: 105 | win.addstr(y, x, " " * iw, color) 106 | except curses.error: 107 | pass 108 | if fw: 109 | c = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][fw] 110 | try: 111 | win.addstr(y, x + iw, c, fcolor) 112 | except curses.error: 113 | pass 114 | if iw > 4: 115 | if len(text) > iw - 2: 116 | _text = text[: iw - 4] + ".." 117 | else: 118 | _text = text 119 | win.addstr(y, x, " " + _text, color) 120 | 121 | def draw(self) -> bool: 122 | """Draw the graph.""" 123 | super().draw() 124 | 125 | if not self.win or not self._data: 126 | return False 127 | 128 | self.win.get_win().clear() 129 | 130 | w = self.size.x 131 | for _, (v, _) in self._data.items(): 132 | scale = w / v 133 | 134 | levels = [(0, -1, (k, v)) for k, v in self._data.items()] 135 | while levels: 136 | x, y, (f, (v, cs)) = levels.pop(0) 137 | w = v * scale 138 | if y >= 0: 139 | self._draw_frame(x, y, w, f) 140 | i = 0 141 | for k, c in cs.items(): 142 | levels.append((x + i, y + 1, (k, c))) 143 | i += int(c[0] * scale + 0.5) 144 | 145 | return True 146 | -------------------------------------------------------------------------------- /tests/test_widgets.py: -------------------------------------------------------------------------------- 1 | from typing import Generator 2 | 3 | import pytest 4 | 5 | from austin_tui.widgets import Point 6 | from austin_tui.widgets import Rect 7 | from austin_tui.widgets.box import Box 8 | from austin_tui.widgets.label import Label 9 | from austin_tui.widgets.scroll import ScrollView 10 | from austin_tui.widgets.table import Table 11 | from austin_tui.widgets.window import Window 12 | from tests.mcurses import MWindow 13 | 14 | 15 | class MockWindow(Window): 16 | def get_size(self) -> Point: 17 | return Point(80, 32) 18 | 19 | def resize(self): 20 | super().resize(Rect(0, self.get_size())) 21 | 22 | 23 | @pytest.fixture 24 | def win() -> Generator[Window, None, None]: 25 | win = MockWindow("test") 26 | # win._win = MWindow(80, 32) 27 | 28 | yield win 29 | 30 | 31 | def test_window_resize(win): 32 | win.resize() 33 | 34 | assert win.rect == Rect(Point(0), Point(80 + 32j)) 35 | 36 | 37 | @pytest.mark.parametrize( 38 | "w, h, size", 39 | [ 40 | (10, 4, Point(10 + 4j)), 41 | (0, 4, Point(80 + 4j)), 42 | (10, 0, Point(10 + 32j)), 43 | (0, 0, Point(80 + 32j)), 44 | ], 45 | ) 46 | def test_label_resize(win, w, h, size): 47 | label = Label("test-label", w, h, "some text") 48 | 49 | win.add_child(label) 50 | 51 | win.resize() 52 | 53 | assert win.rect == Rect(Point(0), Point(80 + 32j)) 54 | assert label.rect == Rect(Point(0), size) 55 | 56 | 57 | def test_box_resize(win): 58 | box = Box("test-box", "v") 59 | win.add_child(box) 60 | 61 | label1 = Label("label1", 0, 0) 62 | label2 = Label("label2", 0, 5) 63 | label3 = Label("label3", 10, 0) 64 | label4 = Label("label4", 20, 6) 65 | 66 | box.add_child(label1) 67 | box.add_child(label2) 68 | box.add_child(label3) 69 | box.add_child(label4) 70 | 71 | win.resize() 72 | 73 | assert box.rect == win.rect 74 | 75 | assert label1.rect == Rect(Point(0), Point(80 + 11j)) 76 | assert label2.rect == Rect(Point(11j), Point(80 + 5j)) 77 | assert label3.rect == Rect(Point(16j), Point(10 + 10j)) 78 | assert label4.rect == Rect(Point(26j), Point(20 + 6j)) 79 | 80 | 81 | def test_nested_box(win): 82 | hbox = Box("hbox", "h") 83 | vbox = Box("vbox", "v") 84 | 85 | win.add_child(vbox) 86 | 87 | header = Label("header", height=2) 88 | footer = Label("footer", height=1) 89 | sidepane = Label("lx", width=24, height=0) 90 | content = Label("content", height=0) 91 | 92 | hbox.add_child(sidepane) 93 | hbox.add_child(content) 94 | 95 | vbox.add_child(header) 96 | vbox.add_child(hbox) 97 | vbox.add_child(footer) 98 | 99 | win.resize() 100 | 101 | assert vbox.rect == win.rect == Rect(0, 80 + 32j) 102 | assert hbox.rect == Rect(2j, 80 + 29j) 103 | assert header.rect == Rect(0, 80 + 2j) 104 | assert footer.rect == Rect(31j, 80 + 1j) 105 | assert sidepane.rect == Rect(2j, 24 + 29j) 106 | assert content.rect == Rect(24 + 2j, 56 + 29j) 107 | 108 | 109 | def test_nested_box_complex_header(win): 110 | """ 111 | / VBOX / 112 | +------------+------------+ 113 | | LOGO 6 x 3 | INFO 0 x 4 | <- HBOX 114 | +------------+------------+ 115 | | MBOX | 116 | +-------------------------+ 117 | """ 118 | hbox = Box("hbox", "h") 119 | vbox = Box("vbox", "v") 120 | mbox = Box("vbox", "v") 121 | 122 | win.add_child(vbox) 123 | vbox.add_child(hbox) 124 | vbox.add_child(mbox) 125 | 126 | logo = Label("hello", width=6, height=3) 127 | info = Label("info", height=4) 128 | 129 | hbox.add_child(logo) 130 | hbox.add_child(info) 131 | 132 | win.resize() 133 | 134 | assert vbox.rect == win.rect 135 | assert hbox.rect == Rect(0, 80 + 4j) 136 | assert logo.rect == Rect(0, 6 + 3j) 137 | assert info.rect == Rect(6, 74 + 4j) 138 | assert mbox.rect == Rect(4j, 80 + 28j) 139 | 140 | 141 | def test_scroll_view(win): 142 | scroll = ScrollView("scroll-test") 143 | win.add_child(scroll) 144 | 145 | label = Label("label", height=120) 146 | scroll.add_child(label) 147 | 148 | win.resize() 149 | 150 | assert scroll.rect == win.rect 151 | assert scroll.get_view_size() == label.rect.size == Point(79 + 120j) 152 | 153 | 154 | def test_table(win): 155 | scroll = ScrollView("scroll-test") 156 | win.add_child(scroll) 157 | scroll._win = win._win 158 | 159 | table = Table("testtable", 1) 160 | scroll.add_child(table) 161 | 162 | table.set_data([[None]] * 3) 163 | 164 | win.resize() 165 | 166 | assert scroll.rect == win.rect 167 | assert table.rect.pos == scroll.rect.pos 168 | assert table.rect.size == Point(scroll.rect.size.x - 1, 3) 169 | 170 | table.set_data([[None]] * 70) 171 | 172 | win.resize() 173 | 174 | assert table.rect.pos == scroll.rect.pos 175 | assert table.rect.size.x == scroll.rect.size.x - 1 176 | assert table.rect.size.y == 70 177 | -------------------------------------------------------------------------------- /austin_tui/model/austin.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from copy import deepcopy 24 | from time import time 25 | from typing import Any 26 | from typing import Dict 27 | from typing import List 28 | from typing import Optional 29 | from typing import Tuple 30 | 31 | from austin.events import AustinSample 32 | from austin.stats import AustinStats 33 | from austin.stats import AustinStatsType 34 | 35 | from austin_tui import AustinProfileMode 36 | 37 | 38 | class OrderedSet: 39 | """Ordered set.""" 40 | 41 | def __init__(self) -> None: 42 | self._items: List[Any] = [] 43 | self._map: Dict[Any, int] = {} 44 | 45 | def __contains__(self, element: Any) -> bool: 46 | """Check if the set contains the element.""" 47 | return element in self._map 48 | 49 | def __getitem__(self, i: Any) -> Any: 50 | """Get the i-th item or the index of the given hashable object.""" 51 | return self._items[i] if isinstance(i, int) else self._map[i] 52 | 53 | def __len__(self) -> int: 54 | """The number of elements in the set.""" 55 | return len(self._items) 56 | 57 | def add(self, element: Any) -> None: 58 | """Add an element to the set. 59 | 60 | If the element is already in the set, nothing happens. 61 | """ 62 | if element not in self._map: 63 | self._map[element] = len(self._items) 64 | self._items.append(element) 65 | 66 | def __bool__(self) -> bool: 67 | """Convert to boolean.""" 68 | return bool(self._items) 69 | 70 | def __str__(self) -> str: 71 | """Representation of the set.""" 72 | return type(self).__name__ + str(self._items) 73 | 74 | def __repr__(self) -> str: 75 | """Representation of the set.""" 76 | return type(self).__name__ + repr(self._items) 77 | 78 | 79 | class AustinModel: 80 | """Austin model.""" 81 | 82 | def __init__(self) -> None: 83 | self.mode = None 84 | 85 | self._samples = 0 86 | self._invalids = 0 87 | self._last_stack: Dict[str, AustinSample] = {} 88 | self._stats = AustinStats( 89 | AustinStatsType.MEMORY 90 | if self.mode is AustinProfileMode.MEMORY 91 | else AustinStatsType.WALL 92 | ) 93 | self._stats.timestamp = time() 94 | 95 | self._austin_version: Optional[str] = None 96 | self._python_version: Optional[str] = None 97 | 98 | self._threads = OrderedSet() 99 | self._current_thread = 0 100 | 101 | self.metadata: Optional[Dict[str, str]] = None 102 | self.threshold = 0.0 103 | self.command_line: Optional[str] = None 104 | 105 | def set_command_line(self, command_line: str) -> None: 106 | """Set the command line.""" 107 | self.command_line = command_line 108 | 109 | def get_versions(self) -> Tuple[Optional[str], Optional[str]]: 110 | """Get Austin and Python versions.""" 111 | return self._austin_version, self._python_version 112 | 113 | def set_versions(self, austin_version: str, python_version: str) -> None: 114 | """Set Austin and Python versions.""" 115 | self._austin_version = austin_version 116 | self._python_version = python_version 117 | 118 | def set_metadata(self, metadata: Dict[str, str]) -> None: 119 | """Set the Austin metadata.""" 120 | self.metadata = metadata 121 | 122 | def update(self, sample: AustinSample) -> None: 123 | """Update current statistics with a new sample.""" 124 | try: 125 | if sample.metrics.time < 0: 126 | return 127 | self._stats.update(sample) 128 | self._stats.timestamp = time() 129 | thread_key = f"{sample.pid}:{sample.iid}:{sample.thread}" 130 | self._last_stack[thread_key] = sample 131 | self._threads.add(thread_key) 132 | finally: 133 | self._samples += 1 134 | 135 | def get_last_stack(self, thread_key: str) -> AustinSample: 136 | """Get the last seen stack for the given thread.""" 137 | return self._last_stack[thread_key] 138 | 139 | @property 140 | def stats(self) -> AustinStats: 141 | """The current Austin statistics.""" 142 | return self._stats 143 | 144 | @property 145 | def threads(self) -> OrderedSet: 146 | """The seen threads as ordered set.""" 147 | return self._threads 148 | 149 | @property 150 | def samples_count(self) -> int: 151 | """Get the sample count.""" 152 | return self._samples 153 | 154 | @property 155 | def error_rate(self) -> float: 156 | """Get the error rate.""" 157 | return self._invalids / self._samples 158 | 159 | @property 160 | def current_thread(self) -> int: 161 | """Get the currently active thread.""" 162 | return self._current_thread 163 | 164 | @current_thread.setter 165 | def current_thread(self, n: int) -> None: 166 | """Set the currently active thread.""" 167 | assert 0 <= n <= len(self._threads) 168 | self._current_thread = n 169 | 170 | def freeze(self) -> "AustinModel": 171 | """Freeze the model.""" 172 | return deepcopy(self) 173 | -------------------------------------------------------------------------------- /austin_tui/widgets/markup.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from abc import ABC 25 | from abc import abstractmethod 26 | from dataclasses import dataclass 27 | from typing import TYPE_CHECKING 28 | from typing import Any 29 | from typing import List 30 | from xml.sax.saxutils import escape 31 | 32 | from lxml import etree 33 | 34 | 35 | if TYPE_CHECKING: 36 | from austin_tui.view.palette import Palette 37 | 38 | 39 | def _unescape(text: str) -> str: 40 | """Unescape angle brackets.""" 41 | return text.replace("<", "<").replace(">", ">") 42 | 43 | 44 | class StringAttr: 45 | """The string attributes.""" 46 | 47 | BOLD = "b" 48 | REVERSED = "r" 49 | 50 | 51 | class Writable(ABC): 52 | """A writable object base class.""" 53 | 54 | @abstractmethod 55 | def write(self, *args: Any, **kwargs: Any) -> None: 56 | """Write the writable object.""" 57 | ... 58 | 59 | 60 | @dataclass 61 | class AttrStringChunk(Writable): 62 | """A chunk of an attribute string. 63 | 64 | A chunk represents a part of a string with certain curses-specific 65 | attributes, like color. 66 | """ 67 | 68 | text: str 69 | color: int = 0 70 | bold: bool = False 71 | reversed: bool = False 72 | 73 | @property 74 | def attr(self) -> int: 75 | """The chunk attributes.""" 76 | attr = 0 77 | if self.color: 78 | attr |= curses.color_pair(self.color) 79 | if self.bold: 80 | attr |= curses.A_BOLD 81 | if self.reversed: 82 | attr |= curses.A_REVERSE 83 | return attr 84 | 85 | def write( # type: ignore[override] 86 | self, window: "curses._CursesWindow", y: int, x: int, maxlen: int = None 87 | ) -> int: 88 | """Write the chunk on the given curses window. 89 | 90 | The ``maxlen`` argument can be used to cap the string length. 91 | """ 92 | text = _unescape(self.text) 93 | text = text[:maxlen] if maxlen is not None else text 94 | try: 95 | window.addstr(y, x, text, self.attr) 96 | except Exception: 97 | # This throws a _curses.error when attempting a legal write at the 98 | # bottom-right corner of the screen :(. 99 | pass 100 | return len(text) 101 | 102 | def __len__(self) -> int: 103 | """The actual length of the string.""" 104 | return len(str(self)) 105 | 106 | def __str__(self) -> str: 107 | """The plain underlying string.""" 108 | return _unescape(self.text) 109 | 110 | 111 | class AttrString(Writable): 112 | """Attribute string class. 113 | 114 | This is a convenience class for writing strings with chunks having different 115 | attributes (e.g. color). 116 | """ 117 | 118 | def __init__(self) -> None: 119 | self._chunks: List[AttrStringChunk] = [] 120 | 121 | def append(self, chunk: AttrStringChunk) -> None: 122 | """Append a chunk.""" 123 | self._chunks.append(chunk) 124 | 125 | def __repr__(self) -> str: 126 | """A detailed representation of the AttrString object.""" 127 | return f"{type(self).__qualname__}{repr(self._chunks)}" 128 | 129 | def __str__(self) -> str: 130 | """The plain underlying string.""" 131 | return "".join(str(_) for _ in self._chunks) 132 | 133 | def __len__(self) -> int: 134 | """The actual string length.""" 135 | return sum(len(_) for _ in self._chunks) 136 | 137 | def write( # type: ignore[override] 138 | self, window: "curses._CursesWindow", y: int, x: int, maxlen: int = None 139 | ) -> int: 140 | """Write the attribute string on the given window. 141 | 142 | The ``maxlen`` argument can be used to cap the string length. 143 | """ 144 | i = x 145 | available = maxlen 146 | n = 0 147 | for chunk in self._chunks: 148 | written = chunk.write(window, y, i, available) 149 | n += written 150 | if available is not None: 151 | available -= written 152 | if available <= 0: 153 | break 154 | i += len(chunk.text) 155 | return n 156 | 157 | 158 | def markup(text: str, palette: "Palette") -> AttrString: 159 | """Use XML markup to generate an attribute string.""" 160 | astr = AttrString() 161 | 162 | root = etree.fromstring(f"{text}") 163 | 164 | def add_strings( 165 | node: etree.Element, 166 | color: str = "default", 167 | bold: bool = False, 168 | reversed: bool = False, 169 | ) -> None: 170 | """Recursively parse the tag tree to generare chunks.""" 171 | _color = palette.get_color(color) 172 | if node.text: 173 | astr.append(AttrStringChunk(node.text, _color, bold, reversed)) 174 | 175 | for e in node: 176 | if e.tag == StringAttr.BOLD: 177 | add_strings(e, color=color, bold=True, reversed=reversed) 178 | elif e.tag == StringAttr.REVERSED: 179 | add_strings(e, color=color, bold=bold, reversed=True) 180 | else: 181 | add_strings(e, color=e.tag, bold=bold, reversed=reversed) 182 | if e.tail: 183 | astr.append(AttrStringChunk(e.tail, _color, bold, reversed)) 184 | 185 | add_strings(root) 186 | 187 | return astr 188 | -------------------------------------------------------------------------------- /austin_tui/widgets/scroll.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from typing import Optional 25 | from typing import Tuple 26 | 27 | from austin_tui.widgets import Container 28 | from austin_tui.widgets import Point 29 | from austin_tui.widgets import Rect 30 | from austin_tui.widgets import Widget 31 | 32 | 33 | class ScrollView(Container): 34 | """Scroll view container widget. 35 | 36 | This is essentially a wrapper around the curses pad object. The drawing of 37 | a scroll bar is taken care of. 38 | """ 39 | 40 | def __init__(self, name: str) -> None: 41 | super().__init__(name) 42 | self._win: Optional[curses._CursesWindow] = None 43 | 44 | self.win = self 45 | 46 | # curses pad geometry 47 | self.curr_y = 0 48 | self.curr_x = 0 49 | self.w = 1 50 | self.h = 1 51 | 52 | def get_win(self) -> Optional["curses._CursesWindow"]: 53 | """Get the underlying curses pad. 54 | 55 | Use with care. 56 | """ 57 | return self._win 58 | 59 | def add_child(self, child: Widget) -> None: 60 | """Add the scroll view child widget.""" 61 | child.parent = self 62 | child.win = self 63 | 64 | self._children_map = {child.name: 0} 65 | self._children = [child] 66 | 67 | def show(self) -> None: 68 | """Show the scroll view.""" 69 | super().show() 70 | 71 | if self._win is not None: 72 | return 73 | 74 | try: 75 | self._win = curses.newpad(self.h, self.w) 76 | except curses.error: 77 | return 78 | 79 | self._win.scrollok(True) 80 | self._win.keypad(True) 81 | self._win.timeout(0) 82 | self._win.nodelay(True) 83 | 84 | def hide(self) -> None: 85 | """Hide the scroll view.""" 86 | super().hide() 87 | 88 | if self._win is not None: 89 | self._win.clear() 90 | self.refresh() 91 | del self._win 92 | self._win = None 93 | 94 | def get_inner_size(self) -> Point: 95 | """Get the scroll view inner size. 96 | 97 | As per curses convention, the returned value is (_height_, _width_). 98 | """ 99 | return Point(self.size - 1) # type: ignore[call-overload] 100 | 101 | def scroll_down(self, lines: int = 1) -> None: 102 | """Scroll the view down.""" 103 | h = self.size.y 104 | 105 | if self.curr_y + h == self.h: 106 | return 107 | 108 | self.curr_y += lines 109 | if self.curr_y + h > self.h: 110 | self.curr_y = self.h - h 111 | 112 | self._draw_scroll_bar() 113 | 114 | def scroll_page_down(self) -> None: 115 | """Scroll one page down.""" 116 | self.scroll_down(self.size.y) 117 | 118 | def scroll_up(self, lines: int = 1) -> None: 119 | """Scroll the view up.""" 120 | if self.curr_y == 0: 121 | return 122 | 123 | self.curr_y -= lines 124 | if self.curr_y < 0: 125 | self.curr_y = 0 126 | 127 | self._draw_scroll_bar() 128 | 129 | def scroll_page_up(self) -> None: 130 | """Scroll one page up.""" 131 | self.scroll_up(self.size.y) 132 | 133 | def top(self) -> None: 134 | """Scroll to the top.""" 135 | self.curr_y = 0 136 | self._draw_scroll_bar() 137 | 138 | def bottom(self) -> None: 139 | """Scroll to the bottom.""" 140 | self.curr_y = self.h - self.size.y 141 | self._draw_scroll_bar() 142 | 143 | def get_view_size(self) -> Point: 144 | """Get the scroll view size.""" 145 | return Point(self.w, self.h) 146 | 147 | def set_view_size(self, h: int, w: int) -> None: 148 | """Set the view size. 149 | 150 | This is the outer size of the view. The actual inner space is computed 151 | automatically to allow extra space for the scroll bar. 152 | """ 153 | oh, ow = self.h, self.w 154 | self.h, self.w = max(h, self.size.y), self.size.x - 1 155 | 156 | if self._win and (self.h != oh or self.w != ow): 157 | self._win.resize(self.h, self.w) # Scroll bar 158 | 159 | def _draw_scroll_bar(self) -> None: 160 | if not self._win: 161 | return 162 | 163 | y0, x0 = self.pos.y, self.pos.x 164 | h, w = self.size.y, self.size.x 165 | 166 | x = x0 + w - 1 167 | 168 | self.parent.win._win.vline(y0, x, curses.ACS_VLINE, h) 169 | 170 | bar_h = min(int(h * h / self.h) + 1, h) 171 | if bar_h != h: 172 | bar_y = int(self.curr_y / self.h * h) 173 | self.parent.win._win.vline(y0 + bar_y, x, curses.ACS_CKBOARD, bar_h) 174 | 175 | def resize(self, rect: Rect) -> bool: 176 | """Resize the scroll view.""" 177 | refresh = super().resize(rect) 178 | 179 | self.rect = rect 180 | 181 | if not self._children: 182 | return False 183 | 184 | (child,) = self._children 185 | 186 | width = self.rect.size.x - 1 187 | self.set_view_size(child.height, width) 188 | 189 | if child.resize(Rect(0, Point(width, child.height))): 190 | refresh = self.draw() 191 | self.refresh() 192 | 193 | self._draw_scroll_bar() 194 | 195 | return refresh 196 | 197 | def draw(self) -> bool: 198 | """Draw the scroll view.""" 199 | if self._win is None: 200 | return False 201 | 202 | h = self.size.y 203 | 204 | if self.curr_y + h > self.h: 205 | self.curr_y = self.h - h 206 | 207 | if self._children: 208 | (child,) = self._children 209 | child.draw() 210 | 211 | self._draw_scroll_bar() 212 | 213 | return True 214 | 215 | def refresh(self) -> None: 216 | """Refresh the scroll view.""" 217 | if not self._win: 218 | return 219 | 220 | w, h = self.size.to_tuple 221 | 222 | if self.curr_y + h > self.h: 223 | self.curr_y = self.h - h 224 | 225 | y1, x1 = self.pos.y, self.pos.x 226 | 227 | y2, x2 = y1 + h - 1, x1 + w - 1 228 | 229 | self._win.refresh(self.curr_y, self.curr_x, y1, x1, y2, x2) 230 | for child in self._children: 231 | child.refresh() 232 | -------------------------------------------------------------------------------- /austin_tui/__main__.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import asyncio 24 | import sys 25 | from textwrap import wrap 26 | from typing import Any 27 | from typing import Optional 28 | 29 | from austin.aio import AsyncAustin 30 | from austin.cli import AustinArgumentParser 31 | from austin.cli import AustinCommandLineError 32 | from austin.errors import AustinError 33 | from austin.events import AustinMetadata 34 | from austin.events import AustinSample 35 | from psutil import Process 36 | 37 | from austin_tui import AustinProfileMode 38 | from austin_tui.controller import AustinTUIController 39 | from austin_tui.view.austin import AustinView 40 | 41 | 42 | def _print(text: str) -> None: 43 | for line in wrap(text, 78): 44 | print(line) 45 | 46 | 47 | class AustinTUIArgumentParser(AustinArgumentParser): 48 | """Austin TUI implementation of the Austin argument parser.""" 49 | 50 | def __init__(self) -> None: 51 | super().__init__(name="austin-tui", full=False) 52 | 53 | def parse_args(self) -> Any: 54 | """Parse command line arguments and report any errors.""" 55 | try: 56 | return super().parse_args() 57 | except AustinCommandLineError as e: 58 | reason, *code = e.args 59 | if reason: 60 | _print(reason) 61 | exit(code[0] if code else -1) 62 | 63 | 64 | class AustinTUI(AsyncAustin): 65 | """Austin TUI implementation of AsyncAustin.""" 66 | 67 | def __init__(self) -> None: 68 | super().__init__() 69 | 70 | self._controller = AustinTUIController() 71 | self._view = self._controller.view 72 | 73 | self._view.callback = self.on_view_event 74 | 75 | self._global_stats: Optional[str] = None 76 | 77 | self._exception = None 78 | self._austin_terminated = False 79 | 80 | async def on_sample(self, sample: AustinSample) -> None: 81 | """Austin sample received callback.""" 82 | self._controller.model.austin.update(sample) 83 | 84 | async def on_metadata(self, metadata: AustinMetadata) -> None: 85 | if metadata.name == "mode": 86 | self._view.set_mode(metadata.value) 87 | elif metadata.name == "python": 88 | self._view.set_python(metadata.value) 89 | else: 90 | self._controller.model.austin.set_metadata(self._meta) 91 | 92 | async def on_terminate(self) -> None: 93 | """Austin terminate callback.""" 94 | self._austin_terminated = True 95 | 96 | self._global_stats = None 97 | await self._controller.stop() 98 | 99 | self._view.stop() 100 | 101 | def on_view_event(self, event: AustinView.Event, data: Any = None) -> None: 102 | """View events handler.""" 103 | 104 | def _unhandled(_: Any) -> None: 105 | raise RuntimeError(f"Unhandled view event: {event}") 106 | 107 | { 108 | AustinView.Event.QUIT: self.on_shutdown, 109 | AustinView.Event.EXCEPTION: self.on_exception, 110 | }.get(event, _unhandled)(data) # type: ignore[operator] 111 | 112 | async def start(self, args: AustinTUIArgumentParser) -> None: 113 | """Start Austin and catch any exceptions.""" 114 | try: 115 | await super().start(args) 116 | except Exception: 117 | self.shutdown() 118 | raise 119 | 120 | pargs = self.get_arguments() 121 | 122 | if pargs.pid is not None: 123 | child_process = Process(pargs.pid) 124 | else: 125 | austin_process = Process(self._proc.pid) 126 | (child_process,) = austin_process.children() 127 | command = child_process.cmdline() 128 | 129 | mode = AustinProfileMode.MEMORY if pargs.memory else AustinProfileMode.TIME 130 | self._view.mode = mode 131 | 132 | """Austin ready callback.""" 133 | self._controller.model.system.set_child_process(child_process) 134 | self._controller.model.austin.set_metadata(self._meta) 135 | self._controller.model.austin.set_command_line(command) 136 | 137 | self._controller.start() 138 | 139 | self._view.set_pid(child_process.pid, pargs.children) 140 | 141 | async def _start(self) -> None: 142 | exc = None 143 | try: 144 | await self.start(sys.argv[1:]) 145 | await self.wait() 146 | await self._view._input_task 147 | except Exception as e: 148 | exc = e 149 | self._view.close() 150 | except KeyboardInterrupt: 151 | self._view.close() 152 | 153 | if exc is not None: 154 | self._view.close() 155 | raise exc 156 | if self._exception is not None: 157 | self._view.close() 158 | raise self._exception 159 | 160 | def run(self) -> None: 161 | """Run the TUI.""" 162 | try: 163 | asyncio.run(self._start()) 164 | except KeyboardInterrupt: 165 | try: 166 | self.terminate() 167 | except AustinError: 168 | pass 169 | except asyncio.CancelledError: 170 | pass 171 | 172 | def shutdown(self) -> None: 173 | """Shutdown the TUI.""" 174 | try: 175 | self.terminate() 176 | except AustinError: 177 | pass 178 | self._view.close() 179 | 180 | def on_shutdown(self, _: Any = None) -> None: 181 | """The shutdown view event handler.""" 182 | self.shutdown() 183 | 184 | def on_exception(self, exc: Exception) -> None: 185 | """The exception view event handler.""" 186 | self.shutdown() 187 | raise exc 188 | 189 | 190 | def main() -> None: 191 | """Main function.""" 192 | if sys.platform == "win32": 193 | asyncio.set_event_loop(asyncio.ProactorEventLoop()) 194 | 195 | tui = AustinTUI() 196 | 197 | try: 198 | tui.run() 199 | except AustinError as e: 200 | print( 201 | "❌ Austin failed to start: \n" 202 | f"\n ❯ {e}\n\n" 203 | "Please make sure that the Austin binary is available from the PATH environment\n" 204 | "variable and that the command line arguments that you have provided are correct.", 205 | file=sys.stderr, 206 | ) 207 | exit(-1) 208 | 209 | exit(0) 210 | 211 | 212 | if __name__ == "__main__": 213 | main() 214 | -------------------------------------------------------------------------------- /austin_tui/widgets/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from typing import Any 25 | from typing import Callable 26 | from typing import Dict 27 | from typing import List 28 | from typing import Optional 29 | from typing import Tuple 30 | from typing import Union 31 | 32 | 33 | class Point(complex): 34 | """A point object for easy vector and symplectic operations.""" 35 | 36 | def along(self, other: complex) -> "Point": 37 | """Project the point along the given complex number.""" 38 | return Point((other.conjugate() * self).real * other / abs(other) ** 2) # type: ignore[call-overload] 39 | 40 | @property 41 | def x(self) -> int: 42 | """The x coordinate of the point.""" 43 | return int(self.real) 44 | 45 | @property 46 | def y(self) -> int: 47 | """The y coordinate of the point.""" 48 | return int(self.imag) 49 | 50 | @property 51 | def to_tuple(self) -> Tuple[int, int]: 52 | """Convert to the (x, y) pair.""" 53 | return (int(self.real), int(self.imag)) 54 | 55 | 56 | class Rect: 57 | """A rectangle object. 58 | 59 | Represent the rectangular area that a widget is allowed to occupy. This is 60 | described by a position point and a size point. 61 | """ 62 | 63 | def __init__(self, pos: Union[Point, complex], size: Union[Point, complex]) -> None: 64 | self.pos = Point(pos) # type: ignore[call-overload] 65 | self.size = Point(size) # type: ignore[call-overload] 66 | 67 | def __eq__(self, other: object) -> bool: 68 | """Recangle object equality check.""" 69 | if not isinstance(other, Rect): 70 | raise NotImplementedError() 71 | 72 | return self.pos == other.pos and self.size == other.size 73 | 74 | def __repr__(self) -> str: 75 | """The rectangle object representation.""" 76 | return f"Rect(pos={self.pos}, size={self.size})" 77 | 78 | 79 | class ContainerError(Exception): 80 | """Container widget error.""" 81 | 82 | pass 83 | 84 | 85 | class Widget: 86 | """Base widget class. 87 | 88 | Every widget should have a name, and some width and height requests. By 89 | default, ``width`` and ``height`` are set to ``0``, meaning that the widget 90 | is happy to be stretched by a parent container as needed. 91 | """ 92 | 93 | def __init__(self, name: str, width: int = 0, height: int = 0) -> None: 94 | self._win: Optional[curses._CursesWindow] = None 95 | self.win: Optional[Widget] = None 96 | self.parent: Optional[Widget] = None 97 | self.view = None 98 | 99 | self.name = name 100 | 101 | # geometry 102 | self.x = 0 103 | self.y = 0 104 | self._width = int(width or 0) 105 | self._height = int(height or 0) 106 | 107 | self.pos = Point(self.x, self.y) 108 | self.size = Point(self.width, self.height) 109 | 110 | @property 111 | def width(self) -> int: 112 | """The widget width.""" 113 | return self._width 114 | 115 | @property 116 | def height(self) -> int: 117 | """The widget height.""" 118 | return self._height 119 | 120 | @property 121 | def expand(self) -> Point: 122 | """The expand directions.""" 123 | return Point(not self.width, not self.height) 124 | 125 | @property 126 | def rect(self) -> Rect: 127 | """The widget rectangular area.""" 128 | return Rect(self.pos, self.size) 129 | 130 | @rect.setter 131 | def rect(self, rect: Rect) -> None: 132 | self.pos = rect.pos 133 | self.size = rect.size 134 | 135 | def __repr__(self) -> str: 136 | """Widget textual representation.""" 137 | return f"{self.__class__.__name__}({self.name})" 138 | 139 | def refresh(self) -> None: 140 | """Refresh the widget. 141 | 142 | This method should cause the appropriate underlying curses window to be 143 | refreshed in order to actually draw the changed widgets. 144 | """ 145 | if self._win: 146 | self._win.refresh() 147 | 148 | def show(self) -> None: 149 | """Show the widget. 150 | 151 | This method is used to create the required low-level curses windows and 152 | to make a first call to ``resize`` to give widgets the initial positions 153 | and sizes. 154 | """ 155 | pass 156 | 157 | def hide(self) -> None: 158 | """Hide the widget. 159 | 160 | If a curses window is no longer needed, this would be the place to 161 | destroy it and reset the terminal to its original state. 162 | """ 163 | pass 164 | 165 | def draw(self) -> bool: 166 | """Draw the widget on screen. 167 | 168 | This method must return ``True`` if a refresh of the screen is required. 169 | """ 170 | return False 171 | 172 | def resize(self, rect: Rect) -> bool: 173 | """Resize the widget. 174 | 175 | This is supposed to change the geometric attribute of the widgets only. 176 | If a re-draw is required, because any of the widget's attributes have 177 | changed, an explicit call to draw must be made. 178 | 179 | The optional ``rect`` argument can be used to define the bounding 180 | rectangle within which the resize is allowed to take place. This is 181 | normally passed by container widgets to their children to constraint 182 | their allowed area. 183 | 184 | This method should return ``True`` if a refresh of the screen is needed. 185 | """ 186 | return False 187 | 188 | 189 | class BaseContainer(Widget): 190 | """Base Container widget. 191 | 192 | A base container widget to implement container data structure for child 193 | widgets. 194 | """ 195 | 196 | def __init__(self, name: str) -> None: 197 | self._children: List[Widget] = [] 198 | self._children_map: Dict[str, int] = {} 199 | super().__init__(name) 200 | 201 | def __getattr__(self, name: str) -> Widget: 202 | """Convenience accessor to child widgets.""" 203 | return self.get_child(name) 204 | 205 | def add_child(self, child: Widget) -> None: 206 | """Add a child widget.""" 207 | if child.name in self._children_map: 208 | raise RuntimeError( 209 | f"Widget {self.name} already has a child with name {child.name}." 210 | ) 211 | 212 | child.parent = self 213 | child.win = self.win 214 | 215 | self._children_map[child.name] = len(self._children) 216 | self._children.append(child) 217 | 218 | def get_child(self, name: str) -> Widget: 219 | """Get a child widget by name.""" 220 | try: 221 | return self._children[self._children_map[name]] 222 | except KeyError: 223 | raise ContainerError( 224 | f"Widget {self.name} does not contain the child widget {name}" 225 | ) from None 226 | 227 | 228 | class Container(BaseContainer): 229 | """Container widget. 230 | 231 | A container widget is just a logical widget. Therefore it shouldn't draw 232 | anything on the screen, but delegate the operation to its children. 233 | """ 234 | 235 | def show(self) -> None: 236 | """Show the children.""" 237 | for child in self._children: 238 | child.show() 239 | 240 | def hide(self) -> None: 241 | """Hide the container.""" 242 | for child in self._children: 243 | child.hide() 244 | 245 | def draw(self) -> bool: 246 | """Draw the children.""" 247 | refresh = False 248 | for child in self._children: 249 | refresh |= child.draw() 250 | return refresh 251 | 252 | def refresh(self) -> None: 253 | """Refresh child widgets.""" 254 | super().refresh() 255 | 256 | for child in self._children: 257 | child.refresh() 258 | -------------------------------------------------------------------------------- /austin_tui/view/austin.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from enum import Enum 24 | from typing import Any 25 | from typing import Callable 26 | from typing import Optional 27 | 28 | from austin_tui import AustinProfileMode 29 | from austin_tui.adapters import fmt_time as _fmt_time 30 | from austin_tui.view import View 31 | from austin_tui.widgets.markup import AttrString 32 | from austin_tui.widgets.markup import AttrStringChunk 33 | 34 | 35 | # ---- AustinView ------------------------------------------------------------- 36 | 37 | 38 | class AustinViewMode(int, Enum): 39 | LIVE = 0 40 | FULL = 1 41 | GRAPH = 2 42 | TOP = 3 43 | 44 | 45 | class AustinView(View): 46 | """Austin view.""" 47 | 48 | class Event(Enum): 49 | """Austin View Events.""" 50 | 51 | EXCEPTION = 0 52 | QUIT = 1 53 | 54 | def __init__( 55 | self, 56 | name: str, 57 | mode: AustinProfileMode = AustinProfileMode.TIME, 58 | callback: Optional[Callable[["Event", Optional[Any]], None]] = None, 59 | ) -> None: 60 | super().__init__(name) 61 | 62 | self.mode = mode 63 | self.callback = callback 64 | 65 | self._stopped = False 66 | 67 | self.view_mode = AustinViewMode.LIVE 68 | 69 | def on_exception(self, exc: Exception) -> None: 70 | """The on exception Austin view handler.""" 71 | if not self.callback: 72 | raise RuntimeError( 73 | "AustinTUI requires a callback to handle exception events." 74 | ) 75 | self.callback(self.Event.EXCEPTION, exc) 76 | 77 | async def on_quit(self) -> bool: 78 | """Handle Quit event.""" 79 | if not self.callback: 80 | raise RuntimeError("AustinTUI requires a callback to handle quit events.") 81 | self.callback(self.Event.QUIT, None) 82 | return False 83 | 84 | def on_mode_selected(self, view_mode: AustinViewMode) -> bool: 85 | needs_update = False 86 | 87 | for m, c in { 88 | AustinViewMode.LIVE: self.live_mode_cmd, 89 | AustinViewMode.GRAPH: self.graph_cmd, 90 | AustinViewMode.FULL: self.full_mode_cmd, 91 | AustinViewMode.TOP: self.top_mode_cmd, 92 | }.items(): 93 | if needs_toggling := ((m is view_mode) != c.state): 94 | c.toggle() 95 | needs_update |= needs_toggling 96 | 97 | return needs_update 98 | 99 | async def on_live_mode_selected(self) -> bool: 100 | """Handle Live Mode toggle.""" 101 | return self.on_mode_selected(AustinViewMode.LIVE) 102 | 103 | async def on_full_mode_selected(self) -> bool: 104 | """Handle Full Mode toggle.""" 105 | return self.on_mode_selected(AustinViewMode.FULL) 106 | 107 | async def on_graph_selected(self) -> bool: 108 | """Handle Graph Mode toggle.""" 109 | return self.on_mode_selected(AustinViewMode.GRAPH) 110 | 111 | async def on_top_mode_selected(self) -> bool: 112 | """Handle Full Mode toggle.""" 113 | return self.on_mode_selected(AustinViewMode.TOP) 114 | 115 | async def on_save(self, data: Any = None) -> bool: 116 | """Handle Save event.""" 117 | self.notification.set_text("Saving collected statistics ...") 118 | return True 119 | 120 | async def on_table_up(self, data: Any = None) -> bool: 121 | """Handle Up Arrow on the table widget.""" 122 | view = self.flame_view if self.graph_cmd.state else self.stats_view 123 | 124 | view.scroll_up() 125 | view.refresh() 126 | return False 127 | 128 | async def on_table_down(self, data: Any = None) -> bool: 129 | """Handle Down Arrow on the table widget.""" 130 | view = self.flame_view if self.graph_cmd.state else self.stats_view 131 | 132 | view.scroll_down() 133 | view.refresh() 134 | return False 135 | 136 | async def on_table_pgup(self, data: Any = None) -> bool: 137 | """Handle Page Up on the table widget.""" 138 | view = self.flame_view if self.graph_cmd.state else self.stats_view 139 | 140 | view.scroll_page_up() 141 | view.refresh() 142 | return False 143 | 144 | async def on_table_pgdown(self, data: Any = None) -> bool: 145 | """Handle Page Down on the table widget.""" 146 | view = self.flame_view if self.graph_cmd.state else self.stats_view 147 | 148 | view.scroll_page_down() 149 | view.refresh() 150 | return False 151 | 152 | async def on_table_home(self, _: Any = None) -> bool: 153 | """Handle Home key on the table widget.""" 154 | view = self.flame_view if self.graph_cmd.state else self.stats_view 155 | 156 | view.top() 157 | view.refresh() 158 | 159 | return False 160 | 161 | async def on_table_end(self, _: Any = None) -> bool: 162 | """Handle End key on the table widget.""" 163 | view = self.flame_view if self.graph_cmd.state else self.stats_view 164 | 165 | view.bottom() 166 | view.refresh() 167 | 168 | return False 169 | 170 | async def on_play_pause(self, _: Any = None) -> bool: 171 | """Play/pause handler.""" 172 | if self._stopped: 173 | return False 174 | 175 | self.play_pause_cmd.toggle() 176 | self.play_pause_label.set_text( 177 | "Resume" if self.play_pause_cmd.state else "Pause" 178 | ) 179 | self.logo.set_color("paused" if self.play_pause_cmd.state else "running") 180 | return True 181 | 182 | def open(self) -> None: 183 | """Open the view.""" 184 | super().open() 185 | 186 | self.logo.set_color("running") 187 | 188 | self.profile_mode.set_text(f"{self.mode.value} Profile") 189 | 190 | self.table.draw() 191 | self.table.refresh() 192 | 193 | def stop(self) -> None: 194 | """Stop Austin view.""" 195 | if not self.is_open or not self.root_widget: 196 | return 197 | 198 | self._stopped = True 199 | self.logo.set_color("stopped") 200 | self.cpu.set_text("--% ") 201 | self.mem.set_text("--M ") 202 | self.play_pause_cmd.set_color("disabled") 203 | 204 | self.table.draw() 205 | self.root_widget.refresh() 206 | 207 | def fmt_time(self, t: int, active: bool = True) -> AttrString: 208 | """Format time value.""" 209 | time = f"{_fmt_time(t):^8}" 210 | return self.markup(f"{time}" if not active else time) 211 | 212 | def fmt_mem(self, s: int, active: bool = True) -> AttrString: 213 | """Format memory value.""" 214 | units = ["B", "K", "M"] 215 | 216 | i = 0 217 | ss = s 218 | while ss >= 1024 and i < len(units) - 1: 219 | i += 1 220 | ss >>= 10 221 | mem = f"{ss: 6d}{units[i]} " 222 | return self.markup(f"{mem}" if not active else mem) 223 | 224 | def color_level(self, value: float, active: bool = True) -> int: 225 | """Return the value heat.""" 226 | prefix = ("i" if not active else "") + "heat" 227 | for stop in [20, 40, 60, 80, 100]: 228 | if value <= stop: 229 | return self.palette.get_color(prefix + str(stop)) 230 | return self.palette.get_color(prefix + "100") 231 | 232 | def _scaler(self, ratio: float, active: bool) -> AttrStringChunk: 233 | return AttrStringChunk( 234 | f"{min(100, ratio):6.1f}% ", color=self.color_level(ratio, active) 235 | ) 236 | 237 | def scale_memory( 238 | self, memory: int, max_memory: int, active: bool = True 239 | ) -> AttrStringChunk: 240 | """Scale a memory value and return an attribute string chunk.""" 241 | return self._scaler(memory / max_memory * 100 if max_memory else 0, active) 242 | 243 | def scale_time( 244 | self, time: int, duration: int, active: bool = True 245 | ) -> AttrStringChunk: 246 | """Scale a time value and return an attribute string chunk.""" 247 | return self._scaler(min(time / 1e4 / duration, 100), active) 248 | 249 | def set_mode(self, mode: str) -> None: 250 | """Set profiling mode.""" 251 | self.profile_mode.set_text( 252 | " " 253 | + { 254 | "wall": "Wall Time Profile", 255 | "cpu": "CPU Time Profile", 256 | "memory": "Memory Profile", 257 | }[mode] 258 | ) 259 | self.profile_mode.set_color(f"mode_{mode}") 260 | 261 | def set_pid(self, pid: int, children: bool) -> None: 262 | """Set the PID.""" 263 | self.pid_label.set_text("PPID" if children else "PID") 264 | self.pid.set_text(self.markup(f"{pid}")) 265 | 266 | def set_python(self, version: str) -> None: 267 | """Set the Python version.""" 268 | self.python.set_text(version) 269 | -------------------------------------------------------------------------------- /austin_tui/widgets/label.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import curses 24 | from collections import deque 25 | from enum import Enum 26 | from typing import Any 27 | from typing import Optional 28 | 29 | from austin_tui.widgets import Point 30 | from austin_tui.widgets import Rect 31 | from austin_tui.widgets import Widget 32 | from austin_tui.widgets.markup import AttrString 33 | 34 | 35 | class TextAlign(Enum): 36 | """Text alignment.""" 37 | 38 | LEFT = "" 39 | RIGHT = ">" 40 | CENTER = "^" 41 | 42 | 43 | def ell(text: str, length: int, sep: str = "..") -> str: 44 | """Ellipsize a string to a given length using the given separator.""" 45 | if len(text) <= length: 46 | return text 47 | 48 | if length <= len(sep): 49 | return sep[:length] 50 | 51 | m = length >> 1 52 | n = length - m 53 | a = len(sep) >> 1 54 | b = len(sep) - a 55 | 56 | return text[: n - b - 1] + sep + text[-m + a - 1 :] 57 | 58 | 59 | class Label(Widget): 60 | """Label widget.""" 61 | 62 | def __init__( 63 | self, 64 | name: str, 65 | width: int = 0, 66 | height: int = 1, 67 | text: Any = "", 68 | align: Any = TextAlign.LEFT, 69 | color: str = "default", 70 | reverse: bool = False, 71 | bold: bool = False, 72 | ellipsize: bool = True, 73 | ) -> None: 74 | super().__init__(name, width, height) 75 | 76 | self.color = color 77 | self.reverse = reverse 78 | self.bold = bold 79 | self.text = text 80 | self.ellipsize = ellipsize 81 | self.align = ( 82 | align if isinstance(align, TextAlign) else getattr(TextAlign, align.upper()) 83 | ) 84 | 85 | def set_text(self, text: Any) -> bool: 86 | """Set the label text.""" 87 | if isinstance(text, AttrString) and self.text is not text: 88 | self.text = text 89 | return self.draw() 90 | 91 | new_text = str(text) 92 | if new_text != self.text: 93 | self.text = new_text 94 | return self.draw() 95 | 96 | return False 97 | 98 | def set_color(self, color: str) -> bool: 99 | """Set the label color.""" 100 | if color != self.color: 101 | self.color = color 102 | return self.draw() 103 | 104 | return False 105 | 106 | def set_bold(self, bold: bool = True) -> bool: 107 | """Set the label appearance to bold.""" 108 | if bold != self.bold: 109 | self.bold = bold 110 | return self.draw() 111 | 112 | return False 113 | 114 | @property 115 | def attr(self) -> int: 116 | """The label attributes.""" 117 | try: 118 | return ( 119 | self.view 120 | and curses.color_pair(self.view.palette.get_color(self.color)) 121 | or 0 122 | | (self.bold and curses.A_BOLD or 0) 123 | | (self.reverse and curses.A_REVERSE or 0) 124 | ) 125 | except curses.error: 126 | return 0 127 | 128 | def resize(self, rect: Optional[Rect] = None) -> bool: 129 | """Resize logic for the label object.""" 130 | width = min(self.width, rect.size.real) or rect.size.real 131 | height = min(self.height, rect.size.imag) or rect.size.imag 132 | new_rect = Rect(rect.pos, Point(width, height)) 133 | if self.rect == new_rect: 134 | return False 135 | 136 | self.rect = new_rect 137 | 138 | self.draw() 139 | 140 | return True 141 | 142 | def draw(self) -> bool: 143 | """Draw the label.""" 144 | if not self.win: 145 | return False 146 | 147 | win = self.win.get_win() 148 | if not win: 149 | return False 150 | 151 | width = self.size.x 152 | if not width: 153 | return False 154 | 155 | if isinstance(self.text, AttrString): 156 | try: 157 | win.addstr(self.pos.y, self.pos.x, " " * width, self.attr) 158 | except curses.error: 159 | pass 160 | x = self.pos.x 161 | if self.align == TextAlign.RIGHT and len(self.text) < width: 162 | x += width - len(self.text) 163 | elif self.align == TextAlign.CENTER and len(self.text) < width: 164 | x += (width - len(self.text)) >> 1 165 | return self.text.write(win, self.pos.y, x, width) > 0 166 | 167 | attr = self.attr 168 | format = "{:" + f"{self.align.value}{max(0, width)}" + "}" 169 | 170 | for i, line in enumerate(self.text.split(r"\n")): 171 | if i >= self.size.y: 172 | break 173 | try: 174 | text = format.format(line or "") 175 | except ValueError: 176 | text = "" 177 | if self.ellipsize: 178 | text = ell(text, width) 179 | try: 180 | win.addstr(self.pos.y + i, self.pos.x, text, attr) 181 | except curses.error: 182 | # Curses cannot write at the bottom right corner of the screen 183 | # so we ignore this error. Be aware that this might be 184 | # swallowing actual errors. 185 | pass 186 | else: 187 | return False 188 | 189 | return True 190 | 191 | def hide(self) -> None: 192 | """Hide the label.""" 193 | win = self.win.get_win() 194 | if not win: 195 | return 196 | 197 | width = self.size.x 198 | if not width: 199 | return 200 | 201 | try: 202 | win.addstr(self.pos.y, self.pos.x, " " * width, 0) 203 | except curses.error: 204 | pass 205 | 206 | 207 | class Line(Label): 208 | """A line that spans the width of its container.""" 209 | 210 | def __init__( 211 | self, 212 | name: str, 213 | text: str = "", 214 | color: str = "default", 215 | reverse: bool = False, 216 | bold: bool = False, 217 | ) -> None: 218 | super().__init__( 219 | name=name, 220 | text=text, 221 | color=color, 222 | reverse=reverse, 223 | bold=bold, 224 | ellipsize=False, 225 | ) 226 | 227 | 228 | class ToggleLabel(Label): 229 | """Toggle label. 230 | 231 | A convenience label that can toggle between two different colors. 232 | """ 233 | 234 | def __init__( 235 | self, 236 | name: str, 237 | width: int = 0, 238 | height: int = 1, 239 | text: str = "", 240 | align: TextAlign = TextAlign.LEFT, 241 | on: str = "default", 242 | off: str = "default", 243 | state: str = "0", 244 | reverse: bool = False, 245 | bold: bool = False, 246 | ellipsize: bool = True, 247 | ) -> None: 248 | self._colors = (off, on) 249 | self._state = int(state) 250 | 251 | super().__init__( 252 | name, 253 | width=width, 254 | height=height, 255 | text=text, 256 | align=align, 257 | color=self._colors[self._state], 258 | reverse=reverse, 259 | bold=bold, 260 | ellipsize=ellipsize, 261 | ) 262 | 263 | @property 264 | def state(self) -> bool: 265 | """Get the toggle state.""" 266 | return bool(self._state) 267 | 268 | def toggle(self) -> bool: 269 | """Toggle the color.""" 270 | self._state = 1 - self._state 271 | return self.set_color(self._colors[self._state]) 272 | 273 | 274 | class BarPlot(Label): 275 | """A bar plot widget. 276 | 277 | If a ``scale`` is given, it is used to scale the values. Otherwise 278 | autoscaling is performed, which can also be enforced with the ``auto`` 279 | argument. The plot can be initialised with an initial value via the ``init`` 280 | argument. 281 | """ 282 | 283 | STEPS = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"] 284 | 285 | @staticmethod 286 | def _bar_icon(i: float) -> str: 287 | i = max(0, min(i, 1)) 288 | return BarPlot.STEPS[int(i * (len(BarPlot.STEPS) - 1))] 289 | 290 | def __init__( 291 | self, 292 | name: str, 293 | width: int = 8, 294 | scale: Optional[int] = None, 295 | init: Optional[int] = None, 296 | color: str = "default", 297 | ) -> None: 298 | super().__init__(name, width=8, color=color, ellipsize=False) 299 | 300 | self._values = deque( 301 | [int(init)] * width if init is not None else [], maxlen=width 302 | ) 303 | self.scale = int(scale or 0) 304 | self.auto = not scale 305 | 306 | def _plot(self) -> bool: 307 | return self.set_text( 308 | "".join( 309 | BarPlot._bar_icon(v / self.scale if self.scale else v) 310 | for v in self._values 311 | ) 312 | ) 313 | 314 | def push(self, value: int) -> bool: 315 | """Push a new value to the plot.""" 316 | self._values.append(value) 317 | if self.auto: 318 | self.scale = max(self._values) 319 | 320 | return self._plot() 321 | -------------------------------------------------------------------------------- /austin_tui/view/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import asyncio 24 | import curses 25 | import sys 26 | from abc import ABC 27 | from collections import defaultdict 28 | from typing import Any 29 | from typing import Callable 30 | from typing import Dict 31 | from typing import List 32 | from typing import Optional 33 | from typing import TextIO 34 | from typing import Type 35 | 36 | from importlib_resources import files 37 | from lxml.etree import Element 38 | from lxml.etree import QName 39 | from lxml.etree import _Comment as Comment 40 | from lxml.etree import fromstring as parse_xml_string 41 | from lxml.etree import parse as parse_xml_stream 42 | 43 | import austin_tui.widgets.catalog as catalog 44 | from austin_tui.view.palette import Palette 45 | from austin_tui.widgets import Container 46 | from austin_tui.widgets import Rect 47 | from austin_tui.widgets import Widget 48 | from austin_tui.widgets.markup import AttrString 49 | from austin_tui.widgets.markup import markup 50 | 51 | 52 | EventHandler = Callable[[Optional[Any]], bool] 53 | 54 | 55 | class _ClassNotFoundError(Exception): 56 | pass 57 | 58 | 59 | def _find_class(class_name: str) -> Type: 60 | try: 61 | # Try to get a class from the standard catalog 62 | return getattr(catalog, class_name) 63 | except AttributeError: 64 | # Try from any of the loaded modules 65 | for _, module in sys.modules.items(): 66 | try: 67 | return getattr(module, class_name) 68 | except AttributeError: 69 | pass 70 | 71 | raise _ClassNotFoundError(f"Cannot find class '{class_name}'") 72 | 73 | 74 | class ViewBuilderError(Exception): 75 | """View builder generic error.""" 76 | 77 | pass 78 | 79 | 80 | def _issignal(node: Element) -> bool: 81 | return QName(node).localname == "signal" 82 | 83 | 84 | def _ispalette(node: Element) -> bool: 85 | return QName(node).localname == "palette" 86 | 87 | 88 | def _validate_ns(node: Element) -> None: 89 | if QName(node).namespace != "http://austin.p403n1x87.com/ui": 90 | raise ViewBuilderError(f"Node '{node}' has invalid namespace") 91 | 92 | 93 | class View(ABC): 94 | """View object. 95 | 96 | All coroutines are collected and scheduled for execution when the view is 97 | opened. 98 | """ 99 | 100 | def __init__(self, name: str) -> None: 101 | self._event_handlers: Dict[str, List[EventHandler]] = defaultdict(list) 102 | 103 | self._open = False 104 | 105 | self.name = name 106 | self.palette = Palette() 107 | self.root_widget = None 108 | 109 | self._input_task = None 110 | 111 | def on_exception(self, exc: Exception) -> None: 112 | """Default task exception callback. 113 | 114 | This simply closes the view and re-raises the exception. Override in 115 | sub-classes with custom logic. 116 | """ 117 | raise exc 118 | 119 | async def _input_loop(self) -> None: 120 | try: 121 | if not self.root_widget: 122 | raise RuntimeError("Missing root widget") 123 | 124 | while self._open: 125 | try: 126 | await asyncio.sleep(0.015) 127 | except asyncio.CancelledError: 128 | break 129 | 130 | if not self.root_widget._win: 131 | continue 132 | 133 | # Handle user input on the root widget 134 | try: 135 | event = self.root_widget._win.getkey() 136 | if event in self._event_handlers: 137 | done = await asyncio.gather( 138 | *(_() for _ in self._event_handlers[event]) 139 | ) 140 | if any(done): 141 | self.root_widget.refresh() 142 | except (KeyError, curses.error): 143 | pass 144 | except Exception as exc: 145 | self.on_exception(exc) 146 | 147 | def _build(self, node: Element) -> Widget: 148 | _validate_ns(node) 149 | widget_class = QName(node).localname 150 | try: 151 | # Try to get a widget from the standard catalog 152 | widget = _find_class(widget_class)(**node.attrib) 153 | except _ClassNotFoundError as e: 154 | raise ViewBuilderError(f"Unknown widget: {widget_class}") from e 155 | 156 | widget.view = self 157 | setattr(self, widget.name, widget) 158 | 159 | return widget 160 | 161 | def connect(self, event: str, handler: EventHandler) -> None: 162 | """Connect event handlers.""" 163 | if handler is None: 164 | raise ValueError(f"{handler} is not a valid handler") 165 | self._event_handlers[event].append(handler) 166 | 167 | def markup(self, text: Any) -> AttrString: 168 | """Convert a markup string into an attribute string.""" 169 | return markup(str(text), self.palette) 170 | 171 | def open(self) -> None: 172 | """Open the view. 173 | 174 | Calling this method not only shows the TUI on screen, but also collects 175 | and schedules all the coroutines on the instance with the event loop. 176 | """ 177 | if not self.root_widget: 178 | raise RuntimeError("View has no root widget") 179 | 180 | self.root_widget.show() 181 | self._open = True 182 | 183 | self.palette.init() 184 | 185 | self.root_widget.resize(Rect(0, self.root_widget.get_size())) 186 | self.root_widget.draw() 187 | self.root_widget.refresh() 188 | 189 | self._input_task = asyncio.create_task(self._input_loop()) 190 | 191 | def close(self) -> None: 192 | """Close the view.""" 193 | if self._open and self.root_widget: 194 | self.root_widget.hide() 195 | 196 | if self._input_task is not None: 197 | self._input_task.cancel() 198 | 199 | self._open = False 200 | 201 | @property 202 | def is_open(self) -> bool: 203 | """Whether the view is open.""" 204 | return self._open 205 | 206 | 207 | class ViewBuilder: 208 | """View builder class.""" 209 | 210 | def __init__(self, view_node: Element) -> None: 211 | _validate_ns(view_node) 212 | self._root = view_node 213 | self._signals: Dict[str, str] = {} 214 | self._autoconnect = False 215 | self._view: Optional[View] = None 216 | 217 | def _parse(self) -> View: 218 | view_class = QName(self._root).localname 219 | try: 220 | view = _find_class(view_class)(**self._root.attrib) 221 | except _ClassNotFoundError: 222 | raise ViewBuilderError(f"Cannot find view class '{view_class}'") from None 223 | 224 | root, *rest = self._root 225 | view.root_widget = view._build(root) 226 | view.connect("KEY_RESIZE", view.root_widget.on_resize) 227 | 228 | def _add_children(widget: Container, node: Element) -> None: 229 | for child in node: 230 | if isinstance(child, Comment): 231 | continue 232 | child_widget = view._build(child) 233 | child_widget.win = widget.win 234 | _add_children(child_widget, child) 235 | widget.add_child(child_widget) 236 | 237 | _add_children(view.root_widget, root) 238 | 239 | for node in rest: 240 | if isinstance(node, Comment): 241 | continue 242 | _validate_ns(node) 243 | if _issignal(node): 244 | event = node.attrib["key"] 245 | handler = node.attrib["handler"] 246 | self._signals[event] = handler 247 | elif _ispalette(node): 248 | for color in node: 249 | if isinstance(color, Comment): 250 | continue 251 | view.palette.add_color(**color.attrib) 252 | else: 253 | raise ViewBuilderError(f"Unknown view element: {node}") 254 | 255 | return view 256 | 257 | def autoconnect(self, *controllers: Any) -> None: 258 | """Auto-connect event handlers. 259 | 260 | If a view has been built, this method allows passing objects that hold 261 | all the necessary event handlers that are declared in the UI resource. 262 | Any unconnected handlers will cause an exception to be raised. 263 | """ 264 | if self._view is None: 265 | raise RuntimeError("View has not been built yet.") 266 | if self._autoconnect: 267 | raise RuntimeError("Event handlers already autoconnected.") 268 | 269 | view = self._view 270 | holders = [view, *controllers] 271 | for event, handler in self._signals.items(): 272 | try: 273 | methods = [getattr(_, handler) for _ in holders if hasattr(_, handler)] 274 | if not methods: 275 | raise AttributeError() 276 | for method in methods: 277 | view.connect(event=event, handler=method) 278 | except Exception as e: 279 | raise ViewBuilderError( 280 | f"Cannot autoconnect handlers for '{handler}' to event '{event}'" 281 | ) from e 282 | 283 | self._autoconnect = True 284 | 285 | def build(self) -> View: 286 | """Build the view.""" 287 | self._view = view = self._parse() 288 | return view 289 | 290 | @classmethod 291 | def from_stream(cls, stream: TextIO) -> "ViewBuilder": 292 | """Build view from a stream.""" 293 | return cls(parse_xml_stream(stream).getroot()) 294 | 295 | @classmethod 296 | def from_resource(cls, module: str, resource: str) -> "ViewBuilder": 297 | """Build view from a resource file.""" 298 | return cls( 299 | parse_xml_string( 300 | files(module).joinpath(resource).read_text(encoding="utf8").encode() 301 | ) 302 | ) 303 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |
Austin TUI
3 |

4 | 5 |

A Top-like Interface for Austin

6 | 7 | 8 |

9 | 10 | GitHub Actions: Tests 12 | 13 |
14 | 22 | 23 | PyPI 25 | 26 | 27 | PyPI Downloads 29 | 30 |   31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
39 | 40 | 41 | LICENSE 43 | 44 |

45 | 46 |

47 | Synopsis • 48 | Installation • 49 | Usage • 50 | Compatibility • 51 | Contribute 52 |

53 | 54 |

55 | 58 | Buy Me A Coffee 61 | 62 |

63 | 64 | # Synopsis 65 | 66 | The Python TUI is a top-like text-based user interface for [Austin], the frame 67 | stack sampler for CPython. Originally planned as a sample application to 68 | showcase [Austin] uses, it's been promoted to a full-fledged project thanks to 69 | great popularity. 70 | 71 |

72 | Austin TUI 75 |

76 | 77 | The header shows you the information of the application that is being profiled, 78 | like its PID, the command line used to invoke it, as well as a plot of the 79 | amount of CPU and memory that is being used by it, in a system-monitor style. 80 | 81 | To know more about how the TUI itself was made, have a read through [The Austin 82 | TUI Way to Resourceful Text-based User Interfaces]. 83 | 84 | # Installation 85 | 86 | Austin TUI can be installed directly from PyPI with 87 | 88 | ~~~ console 89 | pipx install austin-tui 90 | ~~~ 91 | 92 | > **NOTE** In order for the TUI to work, the Austin 3 binary needs to be 93 | > discoverable in the ways documented by the [austin-python] library. Have a 94 | > look at [Austin installation] instructions to see how you can easily install 95 | > Austin on your platform. 96 | 97 | On macOS and Linux, Austin TUI and its dependencies (including Austin itself) 98 | can be installed via conda with 99 | 100 | ~~~ console 101 | conda install -c conda-forge austin-tui 102 | ~~~ 103 | 104 | # Usage 105 | 106 | Once [Austin] 3 and Austin TUI are installed, you can start using them 107 | straight-away. If you want to launch and profile a Python script, say 108 | `myscript.py`, you can do 109 | 110 | ~~~ console 111 | austin-tui python3 myscript.py 112 | ~~~ 113 | 114 | or, if `myscript.py` is an executable script, 115 | 116 | ~~~ console 117 | austin-tui ./myscript.py 118 | ~~~ 119 | 120 | Like [Austin], the TUI can also attach to a running Python application. To 121 | analyse the frame stacks of all the processes of a running WSGI server, for 122 | example, get hold of the PID of the parent process and do 123 | 124 | ~~~ console 125 | sudo austin-tui -Cp 126 | ~~~ 127 | 128 | The `-C` option will instruct [Austin] to look for child Python processes, and you 129 | will be able to navigate through them with the arrow keys. 130 | 131 | > The TUI is based on `python-curses`. The version included with the standard 132 | > Windows installations of Python is broken so it won't work out of the box. A 133 | > solution is to install the the wheel of the port to Windows from 134 | > [this](https://www.lfd.uci.edu/~gohlke/pythonlibs/#curses) page. Wheel files 135 | > can be installed directly with `pip`, as described in the 136 | > [linked](https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels) 137 | > page. 138 | 139 | ## Thread navigation 140 | 141 | Profiling data is processed on a per-thread basis. The total number of threads 142 | (across all processes, if sampling child processes) is displayed in the 143 | top-right corner of the TUI. To navigate to a different thread, use the 144 | and arrows. The PID and TID of the currently 145 | selected thread will appear in the middle of the top bar in the TUI. 146 | 147 | 148 | ## Full mode 149 | 150 | By default, Austin TUI shows you statistics of the last seen stack for each 151 | process and thread when the UI is refreshed (about every second). This is 152 | similar to what top does with all the running processes on your system. 153 | 154 |

155 | Austin TUI - Default mode 158 |

159 | 160 | If you want to see all the collected statistics, with the frame stacks 161 | represented as a rooted tree, you can press F to enter the _Full_ 162 | mode. The last seen stack will be highlighted so that you also have that 163 | information available while in this mode. 164 | 165 |

166 | Austin TUI - Full mode 169 |

170 | 171 | The information that gets displayed is very dynamic and could become tricky to 172 | inspect. The current view can be paused by pressing P. To resume 173 | refreshing the view, press P again. While the view is paused, 174 | profiling data is still being captured and processed in the background, so that 175 | when the view is resumed, the latest figures are shown. 176 | 177 | 178 | ## Graph mode 179 | 180 | A live flame graph visualisation of the current thread statistics can be 181 | displayed by pressing G. This might help with identifying the largest 182 | frames at a glance. 183 | 184 |

185 | Austin TUI - Live flame graph 188 |

189 | 190 | To toggle back to the top view, simply press G again. 191 | 192 | ## Save statistics 193 | 194 | Peeking at a running Python application is nice but in many cases you would want 195 | to save the collected data for further offline analysis (for example, you might 196 | want to represent it as a flame graph). At any point, whenever you want to dump 197 | the collected data to a file, you can press S and a file with all the 198 | samples will be generated for you in the working directory, prefixed with 199 | `austin_` and followed by a timestamp. The TUI will notify of the successful 200 | operation on the bottom-right corner. 201 | 202 |

203 | Austin TUI - Save notification 206 |

207 | 208 | If you run the Austin TUI inside VS Code, you can benefit from the editor's 209 | terminal features, like using Ctrl/Cmd+Left-Click 210 | to hop straight into a source file at a given line. You can also leverage the 211 | TUI's save feature to export the collected samples and import them into the 212 | [Austin VS Code] extension to also get a flame graph representation. 213 | 214 |

215 | Austin TUI 218 |

219 | 220 | ## Threshold 221 | 222 | The statistics reported by the TUI might be overwhelming, especially in full 223 | mode. To reduce the amout of data that gets displayed, the keys + and 224 | - can be used to increase or lower the `%TOTAL` threshold 225 | 226 |

227 | Austin TUI - Threshold demonstration 230 |

231 | 232 | 233 | # Compatibility 234 | 235 | Austin TUI has been tested with Python 3.7-3.10 and is known to work on 236 | **Linux**, **macOS** and **Windows**. 237 | 238 | Since Austin TUI uses [Austin] to collect samples, the same note applies here: 239 | 240 | > Due to the **System Integrity Protection** introduced in **macOS** with El 241 | > Capitan, Austin cannot profile Python processes that use an executable located 242 | > in the `/bin` folder, even with `sudo`. Hence, either run the interpreter from 243 | > a virtual environment or use a Python interpreter that is installed in, e.g., 244 | > `/Applications` or via `brew` with the default prefix (`/usr/local`). Even in 245 | > these cases, though, the use of `sudo` is required. 246 | 247 | As for Linux users, the use of `sudo` can be avoided by granting Austin the 248 | `cap_sys_ptrace` capability with, e.g. 249 | 250 | ~~~ console 251 | sudo setcap cap_sys_ptrace+ep `which austin` 252 | ~~~ 253 | 254 | # Contribute 255 | 256 | If you like Austin TUI and you find it useful, there are ways for you to 257 | contribute. 258 | 259 | If you want to help with the development, then have a look at the open issues 260 | and have a look at the [contributing guidelines](CONTRIBUTING.md) before you 261 | open a pull request. 262 | 263 | You can also contribute to the development of the Austin TUI by becoming a 264 | sponsor and/or by [buying me a coffee](https://www.buymeacoffee.com/Q9C1Hnm28) 265 | on BMC or by chipping in a few pennies on 266 | [PayPal.Me](https://www.paypal.me/gtornetta/1). 267 | 268 |

269 | 271 | Buy Me A Coffee 273 | 274 |

275 | 276 | 277 | [Austin]: https://github.com/P403n1x87/austin 278 | [austin-python]: https://github.com/P403n1x87/austin-python#installation 279 | [Austin installation]: https://github.com/P403n1x87/austin#installation 280 | [Austin VS Code]: https://marketplace.visualstudio.com/items?itemName=p403n1x87.austin-vscode 281 | [The Austin TUI Way to Resourceful Text-based User Interfaces]: https://p403n1x87.github.io/the-austin-tui-way-to-resourceful-text-based-user-interfaces.html 282 | -------------------------------------------------------------------------------- /austin_tui/view/tui.austinui: -------------------------------------------------------------------------------- 1 | 2 | 3 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 36 | 37 | 44 | 45 | 46 | 47 | 48 | 51 | 52 | 53 | 57 | 61 | 62 | 63 | 67 | 71 | 72 | 78 | 79 | 80 | 81 | 82 | 84 | 85 | 86 | 87 | 88 | 91 | 92 | 95 | 96 | 97 | 100 | 101 | 102 | 103 | 104 | 107 | 108 | 109 | 112 | 113 | 114 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 131 | 137 | 143 | 149 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 177 | 181 | 182 | 187 | 191 | 192 | 197 | 201 | 202 | 209 | 213 | 214 | 221 | 225 | 226 | 233 | 237 | 238 | 245 | 249 | 250 | 255 | 259 | 260 | 265 | 269 | 270 | 277 | 281 | 282 | 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 | -------------------------------------------------------------------------------- /austin_tui/controller.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2020 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | import asyncio 24 | from enum import Enum 25 | from pathlib import Path 26 | from time import time 27 | from typing import Any 28 | 29 | from austin.events import AustinMetadata 30 | from austin.format.mojo import MojoStreamWriter 31 | 32 | from austin_tui import AustinProfileMode 33 | from austin_tui.adapters import Adapter 34 | from austin_tui.adapters import CommandLineAdapter 35 | from austin_tui.adapters import CountAdapter 36 | from austin_tui.adapters import CpuAdapter 37 | from austin_tui.adapters import CurrentThreadAdapter 38 | from austin_tui.adapters import DurationAdapter 39 | from austin_tui.adapters import FlameGraphAdapter 40 | from austin_tui.adapters import MemoryAdapter 41 | from austin_tui.adapters import ThreadDataAdapter 42 | from austin_tui.adapters import ThreadFullDataAdapter 43 | from austin_tui.adapters import ThreadNameAdapter 44 | from austin_tui.adapters import ThreadTopDataAdapter 45 | from austin_tui.model import Model 46 | from austin_tui.view import ViewBuilder 47 | from austin_tui.view.austin import AustinViewMode 48 | from austin_tui.widgets.markup import escape 49 | 50 | 51 | class ThreadNav(Enum): 52 | """Thread navigation.""" 53 | 54 | PREV = -1 55 | NEXT = 1 56 | 57 | 58 | class AustinTUIController: 59 | """Austin controller. 60 | 61 | This controller is in charge of Austin data managing and UI updates. 62 | """ 63 | 64 | model = Model.get() # type: ignore[assignment] 65 | 66 | cpu = CpuAdapter 67 | memory = MemoryAdapter 68 | duration = DurationAdapter 69 | samples = CountAdapter 70 | current_thread = CurrentThreadAdapter 71 | thread_name = ThreadNameAdapter 72 | thread_data = ThreadDataAdapter 73 | thread_full_data = ThreadFullDataAdapter 74 | thread_top_data = ThreadTopDataAdapter 75 | command_line = CommandLineAdapter 76 | flamegraph = FlameGraphAdapter 77 | 78 | def __init__(self) -> None: 79 | self._view_mode = AustinViewMode.LIVE 80 | self._scaler = None 81 | self._formatter = None 82 | self._last_timestamp = 0 83 | self._update_task = None 84 | 85 | view_builder = ViewBuilder.from_resource("austin_tui.view", "tui.austinui") 86 | 87 | self.view = view = view_builder.build() # type: ignore[assignment] 88 | 89 | view_builder.autoconnect(self) 90 | 91 | self.model.austin.mode = view.mode 92 | 93 | # Auto-create adapters 94 | for name, adapter_class in ( 95 | (n, v) 96 | for n, v in type(self).__dict__.items() 97 | if isinstance(v, type) and v.__mro__[-2] == Adapter 98 | ): 99 | setattr(self, name, adapter_class(self.model, self.view)) 100 | 101 | def set_thread_data(self) -> None: 102 | """Set the thread stack.""" 103 | if not self.model.austin.threads: 104 | return 105 | 106 | if self._view_mode is AustinViewMode.GRAPH: 107 | self.flamegraph() # type: ignore[call-arg] 108 | elif self._view_mode is AustinViewMode.FULL: 109 | self.thread_full_data() # type: ignore[call-arg] 110 | elif self._view_mode is AustinViewMode.TOP: 111 | self.thread_top_data() # type: ignore[call-arg] 112 | else: 113 | self.thread_data() # type: ignore[call-arg] 114 | 115 | # self._last_timestamp = self.model.austin.stats.timestamp 116 | 117 | def set_thread(self) -> bool: 118 | """Set the thread to display.""" 119 | self.current_thread() # type: ignore[call-arg] 120 | self.thread_name() 121 | 122 | if not self.model.austin.threads: 123 | return True 124 | 125 | # Populate the thread stack view 126 | self.set_thread_data() 127 | 128 | return True 129 | 130 | def _add_flamegraph_palette(self) -> None: 131 | colors = [196, 202, 214, 124, 160, 166, 208] 132 | palette = self.view.palette 133 | 134 | for i, color in enumerate(colors): 135 | palette.add_color(f"fg{i}", 15, color) 136 | palette.add_color(f"fgf{i}", color) 137 | 138 | self.view.flamegraph.set_palette( 139 | ( 140 | [palette.get_color(f"fg{i}") for i in range(len(colors))], 141 | [palette.get_color(f"fgf{i}") for i in range(len(colors))], 142 | ) 143 | ) 144 | 145 | def start(self) -> None: 146 | """Start event.""" 147 | self._add_flamegraph_palette() 148 | self.view.open() 149 | self._update_task = asyncio.create_task(self.update_loop()) 150 | 151 | self._formatter, self._scaler = ( 152 | (self.view.fmt_mem, self.view.scale_memory) 153 | if self.view.mode == AustinProfileMode.MEMORY 154 | else (self.view.fmt_time, self.view.scale_time) 155 | ) 156 | self.model.system.start() 157 | 158 | self.command_line() 159 | 160 | async def stop(self) -> None: 161 | """Stop event.""" 162 | self.model.system.stop() 163 | if self._update_task is not None: 164 | self._update_task.cancel() 165 | await self._update_task 166 | self._update_task = None 167 | 168 | def update(self) -> bool: 169 | """Update event.""" 170 | if self.model.frozen: 171 | return False 172 | 173 | # System data 174 | self.duration() 175 | self.cpu() # type: ignore[call-arg] 176 | self.memory() # type: ignore[call-arg] 177 | 178 | # Samples count 179 | self.samples() 180 | 181 | if self.model.austin.stats.timestamp > self._last_timestamp: 182 | return self.set_thread() 183 | 184 | return False 185 | 186 | async def update_loop(self) -> None: 187 | """The UI update loop.""" 188 | while not self.view._stopped and self.view.is_open and self.view.root_widget: 189 | if self.update(): 190 | if self._view_mode is AustinViewMode.GRAPH: 191 | self.view.flamegraph.draw() 192 | else: 193 | self.view.table.draw() 194 | 195 | self.view.root_widget.refresh() 196 | 197 | try: 198 | await asyncio.sleep(1) 199 | except asyncio.CancelledError: 200 | break 201 | 202 | def _change_thread(self, direction: ThreadNav) -> bool: 203 | """Change thread.""" 204 | austin = self.model.frozen_austin if self.model.frozen else self.model.austin 205 | prev_index = austin.current_thread 206 | 207 | austin.current_thread = max( 208 | 0, 209 | min( 210 | austin.current_thread + direction.value, 211 | len(austin.threads) - 1, 212 | ), 213 | ) 214 | 215 | if prev_index != austin.current_thread: 216 | return self.set_thread() 217 | 218 | return False 219 | 220 | async def on_next_thread(self) -> bool: 221 | """Handle next thread event.""" 222 | if self._change_thread(ThreadNav.NEXT): 223 | if self._graph: 224 | self.view.flamegraph.draw() 225 | self.view.flame_view.refresh() 226 | else: 227 | self.view.table.draw() 228 | self.view.stats_view.refresh() 229 | return True 230 | return False 231 | 232 | async def on_previous_thread(self) -> bool: 233 | """Handle previous thread event.""" 234 | if self._change_thread(ThreadNav.PREV): 235 | if self._graph: 236 | self.view.flamegraph.draw() 237 | self.view.flame_view.refresh() 238 | else: 239 | self.view.table.draw() 240 | self.view.stats_view.refresh() 241 | return True 242 | return False 243 | 244 | async def on_live_mode_selected(self, _: Any = None) -> bool: 245 | """Select live mode.""" 246 | if self._view_mode is AustinViewMode.LIVE: 247 | return False 248 | 249 | self._view_mode = AustinViewMode.LIVE 250 | self.view.dataview_selector.select(0) 251 | self.set_thread_data() 252 | 253 | self.view.table.draw() 254 | self.view.stats_view.refresh() 255 | 256 | return True 257 | 258 | async def on_top_mode_selected(self, _: Any = None) -> bool: 259 | """Select top mode.""" 260 | if self._view_mode is AustinViewMode.TOP: 261 | return False 262 | 263 | self._view_mode = AustinViewMode.TOP 264 | self.view.dataview_selector.select(0) 265 | self.set_thread_data() 266 | 267 | self.view.table.draw() 268 | self.view.stats_view.refresh() 269 | 270 | return True 271 | 272 | async def on_full_mode_selected(self, _: Any = None) -> bool: 273 | """Toggle full mode.""" 274 | if self._view_mode is AustinViewMode.FULL: 275 | return False 276 | 277 | self._view_mode = AustinViewMode.FULL 278 | self.view.dataview_selector.select(0) 279 | self.set_thread_data() 280 | 281 | self.view.table.draw() 282 | self.view.stats_view.refresh() 283 | 284 | return True 285 | 286 | async def on_save(self, _: Any = None) -> bool: 287 | """Save the collected stats.""" 288 | model = self.model.frozen_austin if self.model.frozen else self.model.austin 289 | 290 | def _dump_stats() -> None: 291 | pid = self.model.system.child_process.pid 292 | output_file = Path(f"austin_{int(time())}_{pid}").with_suffix(".mojo") 293 | try: 294 | with output_file.open("wb") as stream: 295 | mojo_writer = MojoStreamWriter(stream) 296 | for k, v in model.metadata.items(): 297 | mojo_writer.write(AustinMetadata(k, v)) 298 | for event in model.stats.flatten(): 299 | mojo_writer.write(event) 300 | self.view.notification.set_text( 301 | self.view.markup( 302 | f"Stats saved as {escape(str(output_file))} " 303 | ) 304 | ) 305 | except IOError as e: 306 | self.view.notification.set_text(f"Failed to save stats: {e}") 307 | 308 | self.view.root_widget.refresh() 309 | 310 | await asyncio.get_event_loop().run_in_executor(None, _dump_stats) 311 | 312 | return False 313 | 314 | async def on_play_pause(self, _: Any = None) -> bool: 315 | """On play/pause handler.""" 316 | if self.view._stopped: 317 | return False 318 | 319 | self.model.toggle_freeze() 320 | self.update() 321 | self.view.notification.set_text("Paused" if self.model.frozen else "Resumed") 322 | return True 323 | 324 | def _change_threshold(self, delta: float) -> float: 325 | self.model.austin.threshold += delta 326 | 327 | if self.model.austin.threshold < 0.0: 328 | self.model.austin.threshold = 0.0 329 | elif self.model.austin.threshold > 1.0: 330 | self.model.austin.threshold = 1.0 331 | 332 | if self.view._stopped or self.model.frozen: 333 | self.set_thread_data() 334 | self.view.table.draw() 335 | self.view.table.refresh() 336 | 337 | return self.model.austin.threshold 338 | 339 | async def on_threshold_up(self, _: Any = None) -> bool: 340 | """Handle threshold up.""" 341 | th = self._change_threshold(0.01) * 100.0 342 | self.view.threshold.set_text(f"{th:.0f}%") 343 | return True 344 | 345 | async def on_threshold_down(self, _: Any = None) -> bool: 346 | """Handle threshold down.""" 347 | th = self._change_threshold(-0.01) * 100.0 348 | self.view.threshold.set_text(f"{th:.0f}%") 349 | return True 350 | 351 | async def on_graph_selected(self, _: Any = None) -> bool: 352 | """Select graph visualisation.""" 353 | if self._view_mode is AustinViewMode.GRAPH: 354 | return False 355 | 356 | self._view_mode = AustinViewMode.GRAPH 357 | 358 | self.view.dataview_selector.select(1) 359 | 360 | self.flamegraph() # type: ignore[call-arg] 361 | 362 | return True 363 | -------------------------------------------------------------------------------- /austin_tui/adapters.py: -------------------------------------------------------------------------------- 1 | # This file is part of "austin-tui" which is released under GPL. 2 | # 3 | # See file LICENCE or go to http://www.gnu.org/licenses/ for full license 4 | # details. 5 | # 6 | # austin-tui is top-like TUI for Austin. 7 | # 8 | # Copyright (c) 2018-2021 Gabriele N. Tornetta . 9 | # All rights reserved. 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | from typing import Any 24 | from typing import Optional 25 | from typing import Set 26 | from typing import Union 27 | 28 | from austin.events import ThreadName 29 | from austin.stats import HierarchicalStats 30 | 31 | from austin_tui import AustinProfileMode 32 | from austin_tui.model import Model 33 | from austin_tui.model.austin import AustinModel 34 | from austin_tui.model.system import Bytes 35 | from austin_tui.model.system import FrozenSystemModel 36 | from austin_tui.model.system import Percentage 37 | from austin_tui.model.system import SystemModel 38 | from austin_tui.view import View 39 | from austin_tui.widgets.graph import FlameGraphData 40 | from austin_tui.widgets.markup import AttrString 41 | from austin_tui.widgets.markup import escape 42 | from austin_tui.widgets.table import TableData 43 | 44 | 45 | class Adapter: 46 | """Model-View adapter. 47 | 48 | Bridges between a data model and the actual data structure required by a 49 | widget so that it can be displayed in a view. 50 | 51 | An adapter is made of two steps: ``transform`` and ``update``. The former 52 | transforms the model data into a format that is suitable for representation 53 | for the given widget. The latter is responsible for updating the widget 54 | appearance. 55 | 56 | An adapter is used by simply calling it. 57 | """ 58 | 59 | def __init__(self, model: Model, view: View) -> None: 60 | self._model = model 61 | self._view = view 62 | 63 | def __call__(self) -> bool: 64 | """Invoke the adapter.""" 65 | return self.update(self.transform()) 66 | 67 | def transform(self) -> Any: 68 | """Transform the model data into the widget data.""" 69 | pass 70 | 71 | def update(self, data: Any) -> bool: 72 | """Update the view with the widget data.""" 73 | pass 74 | 75 | 76 | class FreezableAdapter(Adapter): 77 | """An adapter with freezable widget data.""" 78 | 79 | def __init__(self, *args: Any, **kwargs: Any) -> None: 80 | super().__init__(*args, **kwargs) 81 | self._frozen = False 82 | self._data: Optional[Any] = None 83 | 84 | def __call__(self) -> bool: 85 | """Invoke the adapter on either live or frozen data.""" 86 | if self._frozen: 87 | return self.update(self.defrost()) 88 | return super().__call__() 89 | 90 | def freeze(self) -> None: 91 | """Freeze the widget data.""" 92 | self._data = self.transform() 93 | self._frozen = True 94 | 95 | def defrost(self) -> Any: 96 | """Retrieve the frozen data. 97 | 98 | Implement to return the frozen data. 99 | """ 100 | return self._data 101 | 102 | def unfreeze(self) -> None: 103 | """Unfreeze the adapter.""" 104 | self._frozen = False 105 | 106 | @property 107 | def frozen(self) -> bool: 108 | """The freeze status of the adapter.""" 109 | return self._frozen 110 | 111 | 112 | class CommandLineAdapter(FreezableAdapter): 113 | """Command line adapter.""" 114 | 115 | def transform(self) -> AttrString: 116 | """Retrieve the command line.""" 117 | cmd = self._model.austin.command_line 118 | exec, *args = cmd 119 | return self._view.markup( 120 | f"{escape(exec)} {escape(' '.join(args))}" 121 | ) 122 | 123 | def update(self, data: AttrString) -> bool: 124 | """Update the widget.""" 125 | return self._view.cmd_line.set_text(data) 126 | 127 | 128 | class CountAdapter(FreezableAdapter): 129 | """Sample count adapter.""" 130 | 131 | def transform(self) -> int: 132 | """Retrieve the count.""" 133 | return self._model.austin.samples_count 134 | 135 | def update(self, data: int) -> bool: 136 | """Update the widget.""" 137 | return self._view.samples.set_text(data) 138 | 139 | 140 | class CpuAdapter(Adapter): 141 | """CPU metrics adapter.""" 142 | 143 | def transform(self) -> Percentage: 144 | """Get the CPU usage.""" 145 | return self._model.system.get_cpu(self._model.system.child_process) 146 | 147 | def update(self, data: Percentage) -> bool: 148 | """Update the metric and the plot.""" 149 | self._view.cpu.set_text(f"{data}% ") 150 | self._view.cpu_plot.push(data) 151 | return True 152 | 153 | 154 | class MemoryAdapter(Adapter): 155 | """Memory usage adapter.""" 156 | 157 | def transform(self) -> Bytes: 158 | """Get memory usage.""" 159 | return self._model.system.get_memory(self._model.system.child_process) 160 | 161 | def update(self, data: Bytes) -> bool: 162 | """Update metric and plot.""" 163 | self._view.mem.set_text(f"{data >> 20}M ") 164 | self._view.mem_plot.push(data) 165 | return True 166 | 167 | 168 | def fmt_time(us: int) -> str: 169 | """Format microseconds into [mm]m[ss[.ff]]s.""" 170 | s = us / 1e6 171 | m = int(s // 60) 172 | return f"{m:02d}m{s:02d}s" if m else f"{s:.2f}s" 173 | 174 | 175 | class DurationAdapter(FreezableAdapter): 176 | """Duration adapter.""" 177 | 178 | def transform(self) -> str: 179 | """Get duration.""" 180 | return fmt_time(int(self._model.system.duration * 1e6)) 181 | 182 | def update(self, data: str) -> bool: 183 | """Update the widget.""" 184 | return self._view.duration.set_text(data) 185 | 186 | 187 | class CurrentThreadAdapter(Adapter): 188 | """Currently selected thread adapter.""" 189 | 190 | def transform(self) -> Union[str, AttrString]: 191 | """Get current thread.""" 192 | austin = self._model.frozen_austin if self._model.frozen else self._model.austin 193 | n = len(austin.threads) 194 | if not n: 195 | return "--/--" 196 | 197 | return self._view.markup( 198 | f"{austin.current_thread + 1}/{n}" 199 | ) 200 | 201 | def update(self, data: Union[str, AttrString]) -> bool: 202 | """Update the widget.""" 203 | return self._view.thread_num.set_text(data) 204 | 205 | 206 | class ThreadNameAdapter(FreezableAdapter): 207 | """Currently selected thread name adapter.""" 208 | 209 | def transform(self) -> Union[str, AttrString]: 210 | """Get the thread name.""" 211 | austin = self._model.frozen_austin if self._model.frozen else self._model.austin 212 | if austin.threads: 213 | pid, _, tid = austin.threads[austin.current_thread].partition(":") 214 | return self._view.markup(f"{pid}:{tid}") 215 | return "--:--" 216 | 217 | def update(self, data: Union[str, AttrString]) -> bool: 218 | """Update the widget.""" 219 | return self._view.thread_name.set_text(data) 220 | 221 | 222 | class BaseThreadDataAdapter(Adapter): 223 | """Base implementation for the thread table data adapter.""" 224 | 225 | def transform(self) -> TableData: 226 | """Transform according to the right model.""" 227 | austin = self._model.frozen_austin if self._model.frozen else self._model.austin 228 | system = self._model.frozen_system if self._model.frozen else self._model.system 229 | return self._transform(austin, system) 230 | 231 | def update(self, data: TableData) -> bool: 232 | """Update the table.""" 233 | return self._view.table.set_data(data) 234 | 235 | 236 | class ThreadDataAdapter(BaseThreadDataAdapter): 237 | """Thread table data adapter.""" 238 | 239 | def _transform( 240 | self, austin: AustinModel, system: Union[SystemModel, FrozenSystemModel] 241 | ) -> TableData: 242 | formatter, scaler = ( 243 | (self._view.fmt_mem, self._view.scale_memory) 244 | if self._view.mode == AustinProfileMode.MEMORY 245 | else (self._view.fmt_time, self._view.scale_time) 246 | ) 247 | thread_key = austin.threads[austin.current_thread] 248 | pid, _, thread = thread_key.partition(":") 249 | 250 | pid, _, thread_name = thread_key.partition(":") 251 | iid, _, thread = thread_name.partition(":") 252 | thread_stats = austin.stats.processes[int(pid)].threads[ 253 | ThreadName(thread, int(iid)) 254 | ] 255 | frames = austin.get_last_stack(thread_key).frames 256 | 257 | container = thread_stats.children 258 | frame_stats = [] 259 | max_scale = ( 260 | system.max_memory 261 | if self._view.mode == AustinProfileMode.MEMORY 262 | else system.duration 263 | ) 264 | 265 | for frame in frames or []: 266 | child_frame_stats = container[frame] 267 | if child_frame_stats.total / 1e6 / max_scale < self._model.austin.threshold: 268 | break 269 | column = ( 270 | f":{child_frame_stats.label.column}" 271 | if child_frame_stats.label.column 272 | else "" 273 | ) 274 | location = self._view.markup( 275 | " " 276 | + escape(child_frame_stats.label.function) 277 | + f" ({escape(child_frame_stats.label.filename)}" 278 | f":{child_frame_stats.label.line}{column})" 279 | ) 280 | frame_stats.append( 281 | [ 282 | formatter(child_frame_stats.own), 283 | formatter(child_frame_stats.total), 284 | scaler(child_frame_stats.own, max_scale), 285 | scaler(child_frame_stats.total, max_scale), 286 | location, 287 | ] 288 | ) 289 | container = child_frame_stats.children 290 | 291 | return frame_stats 292 | 293 | 294 | class ThreadTopDataAdapter(BaseThreadDataAdapter): 295 | """Thread table top data adapter.""" 296 | 297 | def _transform( 298 | self, austin: AustinModel, system: Union[SystemModel, FrozenSystemModel] 299 | ) -> TableData: 300 | formatter, scaler = ( 301 | (self._view.fmt_mem, self._view.scale_memory) 302 | if self._view.mode == AustinProfileMode.MEMORY 303 | else (self._view.fmt_time, self._view.scale_time) 304 | ) 305 | 306 | thread_key = austin.threads[austin.current_thread] 307 | pid, _, thread = thread_key.partition(":") 308 | 309 | frame_stats = {} 310 | max_scale = ( 311 | system.max_memory 312 | if self._view.mode == AustinProfileMode.MEMORY 313 | else system.duration 314 | ) 315 | 316 | def _add_frame_stats( 317 | stats: HierarchicalStats, seen_locations: Set[str] 318 | ) -> None: 319 | if len(frame_stats) == MAX_LENGTH: 320 | frame_stats.append( 321 | [ 322 | " " * 8, 323 | " " * 8, 324 | " " * 8, 325 | " " * 8, 326 | self._view.markup( 327 | " [truncated view; export the data to MOJO to see more with other tools]" 328 | ), 329 | ] 330 | ) 331 | return 332 | if len(frame_stats) > MAX_LENGTH: 333 | return 334 | if stats.total / 1e6 / max_scale < self._model.austin.threshold: 335 | return 336 | 337 | column = ( 338 | f":{stats.label.column}" if stats.label.column else "" 339 | ) 340 | location = ( 341 | (escape(stats.label.function)) 342 | + f" ({escape(stats.label.filename)}:{stats.label.line}{column})" 343 | ) 344 | frame_stats[location] = ( 345 | frame_stats.get(location, 0) 346 | + stats.own 347 | + 1j * stats.total * (location not in seen_locations) 348 | ) 349 | 350 | if not (children_stats := list(stats.children.values())): 351 | return 352 | 353 | new_seen_locations = seen_locations | {location} 354 | for child_stats in children_stats[:-1]: 355 | _add_frame_stats(child_stats, new_seen_locations) 356 | 357 | _add_frame_stats(children_stats[-1], new_seen_locations) 358 | 359 | pid, _, thread_name = thread_key.partition(":") 360 | iid, _, thread = thread_name.partition(":") 361 | thread_stats = austin.stats.processes[int(pid)].threads[ 362 | ThreadName(thread, int(iid)) 363 | ] 364 | if children := list(thread_stats.children.values()): 365 | for stats in children[:-1]: 366 | _add_frame_stats(stats, set()) 367 | 368 | _add_frame_stats(children[-1], set()) 369 | 370 | return [ 371 | ( 372 | formatter(int(m.real), True), 373 | formatter(int(m.imag), True), 374 | scaler(int(m.real), max_scale, True), 375 | scaler(int(m.imag), max_scale, True), 376 | self._view.markup(location), 377 | ) 378 | for location, m in sorted( 379 | frame_stats.items(), reverse=True, key=lambda _: _[1].real 380 | ) 381 | ] 382 | 383 | 384 | MAX_DEPTH = 64 385 | MAX_LENGTH = 1 << 12 386 | 387 | 388 | class ThreadFullDataAdapter(BaseThreadDataAdapter): 389 | """Full thread data adapter.""" 390 | 391 | def _transform( 392 | self, austin: AustinModel, system: Union[SystemModel, FrozenSystemModel] 393 | ) -> TableData: 394 | formatter, scaler = ( 395 | (self._view.fmt_mem, self._view.scale_memory) 396 | if self._view.mode == AustinProfileMode.MEMORY 397 | else (self._view.fmt_time, self._view.scale_time) 398 | ) 399 | 400 | thread_key = austin.threads[austin.current_thread] 401 | pid, _, thread = thread_key.partition(":") 402 | 403 | frames = austin.get_last_stack(thread_key).frames or [] 404 | frame_stats = [] 405 | max_scale = ( 406 | system.max_memory 407 | if self._view.mode == AustinProfileMode.MEMORY 408 | else system.duration 409 | ) 410 | 411 | def _add_frame_stats( 412 | stats: HierarchicalStats, 413 | marker: str, 414 | prefix: str, 415 | level: int = 0, 416 | active_bucket: Optional[dict] = None, 417 | active_parent: bool = True, 418 | ) -> None: 419 | if len(frame_stats) == MAX_LENGTH: 420 | frame_stats.append( 421 | [ 422 | " " * 8, 423 | " " * 8, 424 | " " * 8, 425 | " " * 8, 426 | self._view.markup( 427 | " [truncated view; export the data to MOJO to see more with other tools]" 428 | ), 429 | ] 430 | ) 431 | return 432 | if len(frame_stats) > MAX_LENGTH: 433 | return 434 | if stats.total / 1e6 / max_scale < self._model.austin.threshold: 435 | return 436 | try: 437 | active = ( 438 | active_bucket is not None 439 | and stats.label in active_bucket 440 | and stats.label == frames[level] 441 | and active_parent 442 | ) 443 | active_bucket = stats.children 444 | except IndexError: 445 | active = False 446 | active_bucket = None 447 | 448 | column = ( 449 | f":{stats.label.column}" if stats.label.column else "" 450 | ) 451 | location = ( 452 | ( 453 | ( 454 | escape(stats.label.function) 455 | if active 456 | else f"{escape(stats.label.function)}" 457 | ) 458 | + f" ({escape(stats.label.filename)}:{stats.label.line}{column})" 459 | ) 460 | if level < MAX_DEPTH 461 | else "..." 462 | ) 463 | frame_stats.append( 464 | [ 465 | formatter(stats.own, active), 466 | formatter(stats.total, active), 467 | scaler(stats.own, max_scale, active), 468 | scaler(stats.total, max_scale, active), 469 | self._view.markup(f" {marker}{location}"), 470 | ] 471 | ) 472 | 473 | if level >= MAX_DEPTH or not ( 474 | children_stats := list(stats.children.values()) 475 | ): 476 | return 477 | 478 | for child_stats in children_stats[:-1]: 479 | _add_frame_stats( 480 | child_stats, 481 | prefix + "├─ ", 482 | prefix + "│ ", 483 | level + 1, 484 | active_bucket, 485 | active, 486 | ) 487 | 488 | _add_frame_stats( 489 | children_stats[-1], 490 | prefix + "└─ ", 491 | prefix + " ", 492 | level + 1, 493 | active_bucket, 494 | active, 495 | ) 496 | 497 | pid, _, thread_name = thread_key.partition(":") 498 | iid, _, thread = thread_name.partition(":") 499 | thread_stats = austin.stats.processes[int(pid)].threads[ 500 | ThreadName(thread, int(iid)) 501 | ] 502 | if children := list(thread_stats.children.values()): 503 | for stats in children[:-1]: 504 | _add_frame_stats(stats, "├─ ", "│ ", 0, thread_stats.children) 505 | 506 | _add_frame_stats(children[-1], "└─ ", " ", 0, thread_stats.children) 507 | 508 | return frame_stats 509 | 510 | 511 | class FlameGraphAdapter(Adapter): 512 | """Flame graph data adapter.""" 513 | 514 | def transform(self) -> dict: 515 | """Transform according to the right model.""" 516 | austin = self._model.frozen_austin if self._model.frozen else self._model.austin 517 | system = self._model.frozen_system if self._model.frozen else self._model.system 518 | return self._transform(austin, system) # type: ignore[arg-type] 519 | 520 | def _transform( 521 | self, austin: AustinModel, system: Union[SystemModel, FrozenSystemModel] 522 | ) -> FlameGraphData: 523 | thread_key = austin.threads[austin.current_thread] 524 | pid, _, thread_name = thread_key.partition(":") 525 | iid, _, thread = thread_name.partition(":") 526 | thread = austin.stats.processes[int(pid)].threads[ThreadName(thread, int(iid))] 527 | 528 | cs = {} # type: ignore[var-annotated] 529 | total = thread.total 530 | total_pct = min(int(total / system.duration / 1e4), 100) 531 | data: FlameGraphData = { 532 | f"THREAD {thread.label.iid}:{thread.label.thread} ⏲️ {fmt_time(total)} ({total_pct}%)": ( 533 | total, 534 | cs, 535 | ) 536 | } 537 | levels = [(c, cs) for c in thread.children.values()] 538 | while levels: 539 | level, c = levels.pop(0) 540 | k = f"{level.label.function} ({level.label.filename})" 541 | if k in c: 542 | v, cs = c[k] 543 | c[k] = (v + level.total, cs) 544 | else: 545 | cs = {} 546 | c[k] = (level.total, cs) 547 | levels.extend(((c, cs) for c in level.children.values())) 548 | 549 | return data 550 | 551 | def update(self, data: FlameGraphData) -> bool: 552 | """Update the table.""" 553 | (header,) = data 554 | return self._view.flamegraph.set_data(data) | self._view.graph_header.set_text( 555 | " FLAME GRAPH FOR " + header 556 | ) 557 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license 7 | document, but changing it is not allowed. 8 | 9 | ## Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for software and 12 | other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed to take 15 | away your freedom to share and change the works. By contrast, the GNU General 16 | Public License is intended to guarantee your freedom to share and change all 17 | versions of a program--to make sure it remains free software for all its users. 18 | We, the Free Software Foundation, use the GNU General Public License for most 19 | of our software; it applies also to any other work released this way by its 20 | authors. You can apply it to your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not price. Our 23 | General Public Licenses are designed to make sure that you have the freedom to 24 | distribute copies of free software (and charge for them if you wish), that you 25 | receive source code or can get it if you want it, that you can change the 26 | software or use pieces of it in new free programs, and that you know you can do 27 | these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights 30 | or asking you to surrender the rights. Therefore, you have certain 31 | responsibilities if you distribute copies of the software, or if you modify it: 32 | responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for 35 | a fee, you must pass on to the recipients the same freedoms that you received. 36 | You must make sure that they, too, receive or can get the source code. And you 37 | must show them these terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: 40 | 41 | 1. assert copyright on the software, and 42 | 2. offer you this License giving you legal permission to copy, distribute 43 | and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains that 46 | there is no warranty for this free software. For both users' and authors' sake, 47 | the GPL requires that modified versions be marked as changed, so that their 48 | problems will not be attributed erroneously to authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run modified 51 | versions of the software inside them, although the manufacturer can do so. This 52 | is fundamentally incompatible with the aim of protecting users' freedom to 53 | change the software. The systematic pattern of such abuse occurs in the area of 54 | products for individuals to use, which is precisely where it is most 55 | unacceptable. Therefore, we have designed this version of the GPL to prohibit 56 | the practice for those products. If such problems arise substantially in other 57 | domains, we stand ready to extend this provision to those domains in future 58 | versions of the GPL, as needed to protect the freedom of users. 59 | 60 | Finally, every program is threatened constantly by software patents. States 61 | should not allow patents to restrict development and use of software on 62 | general-purpose computers, but in those that do, we wish to avoid the special 63 | danger that patents applied to a free program could make it effectively 64 | proprietary. To prevent this, the GPL assures that patents cannot be used to 65 | render the program non-free. 66 | 67 | The precise terms and conditions for copying, distribution and modification 68 | follow. 69 | 70 | ## TERMS AND CONDITIONS 71 | 72 | ### 0. Definitions. 73 | 74 | *This License* refers to version 3 of the GNU General Public License. 75 | 76 | *Copyright* also means copyright-like laws that apply to other kinds of works, 77 | such as semiconductor masks. 78 | 79 | *The Program* refers to any copyrightable work licensed under this License. 80 | Each licensee is addressed as *you*. *Licensees* and *recipients* may be 81 | individuals or organizations. 82 | 83 | To *modify* a work means to copy from or adapt all or part of the work in a 84 | fashion requiring copyright permission, other than the making of an exact copy. 85 | The resulting work is called a *modified version* of the earlier work or a work 86 | *based on* the earlier work. 87 | 88 | A *covered work* means either the unmodified Program or a work based on the 89 | Program. 90 | 91 | To *propagate* a work means to do anything with it that, without permission, 92 | would make you directly or secondarily liable for infringement under applicable 93 | copyright law, except executing it on a computer or modifying a private copy. 94 | Propagation includes copying, distribution (with or without modification), 95 | making available to the public, and in some countries other activities as well. 96 | 97 | To *convey* a work means any kind of propagation that enables other parties to 98 | make or receive copies. Mere interaction with a user through a computer 99 | network, with no transfer of a copy, is not conveying. 100 | 101 | An interactive user interface displays *Appropriate Legal Notices* to the 102 | extent that it includes a convenient and prominently visible feature that 103 | 104 | 1. displays an appropriate copyright notice, and 105 | 2. tells the user that there is no warranty for the work (except to the 106 | extent that warranties are provided), that licensees may convey the work 107 | under this License, and how to view a copy of this License. 108 | 109 | If the interface presents a list of user commands or options, such as a menu, a 110 | prominent item in the list meets this criterion. 111 | 112 | ### 1. Source Code. 113 | 114 | The *source code* for a work means the preferred form of the work for making 115 | modifications to it. *Object code* means any non-source form of a work. 116 | 117 | A *Standard Interface* means an interface that either is an official standard 118 | defined by a recognized standards body, or, in the case of interfaces specified 119 | for a particular programming language, one that is widely used among developers 120 | working in that language. 121 | 122 | The *System Libraries* of an executable work include anything, other than the 123 | work as a whole, that (a) is included in the normal form of packaging a Major 124 | Component, but which is not part of that Major Component, and (b) serves only 125 | to enable use of the work with that Major Component, or to implement a Standard 126 | Interface for which an implementation is available to the public in source code 127 | form. A *Major Component*, in this context, means a major essential component 128 | (kernel, window system, and so on) of the specific operating system (if any) on 129 | which the executable work runs, or a compiler used to produce the work, or an 130 | object code interpreter used to run it. 131 | 132 | The *Corresponding Source* for a work in object code form means all the source 133 | code needed to generate, install, and (for an executable work) run the object 134 | code and to modify the work, including scripts to control those activities. 135 | However, it does not include the work's System Libraries, or general-purpose 136 | tools or generally available free programs which are used unmodified in 137 | performing those activities but which are not part of the work. For example, 138 | Corresponding Source includes interface definition files associated with source 139 | files for the work, and the source code for shared libraries and dynamically 140 | linked subprograms that the work is specifically designed to require, such as 141 | by intimate data communication or control flow between those subprograms and 142 | other parts of the work. 143 | 144 | The Corresponding Source need not include anything that users can regenerate 145 | automatically from other parts of the Corresponding Source. 146 | 147 | The Corresponding Source for a work in source code form is that same work. 148 | 149 | ### 2. Basic Permissions. 150 | 151 | All rights granted under this License are granted for the term of copyright on 152 | the Program, and are irrevocable provided the stated conditions are met. This 153 | License explicitly affirms your unlimited permission to run the unmodified 154 | Program. The output from running a covered work is covered by this License only 155 | if the output, given its content, constitutes a covered work. This License 156 | acknowledges your rights of fair use or other equivalent, as provided by 157 | copyright law. 158 | 159 | You may make, run and propagate covered works that you do not convey, without 160 | conditions so long as your license otherwise remains in force. You may convey 161 | covered works to others for the sole purpose of having them make modifications 162 | exclusively for you, or provide you with facilities for running those works, 163 | provided that you comply with the terms of this License in conveying all 164 | material for which you do not control copyright. Those thus making or running 165 | the covered works for you must do so exclusively on your behalf, under your 166 | direction and control, on terms that prohibit them from making any copies of 167 | your copyrighted material outside their relationship with you. 168 | 169 | Conveying under any other circumstances is permitted solely under the 170 | conditions stated below. Sublicensing is not allowed; section 10 makes it 171 | unnecessary. 172 | 173 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 174 | 175 | No covered work shall be deemed part of an effective technological measure 176 | under any applicable law fulfilling obligations under article 11 of the WIPO 177 | copyright treaty adopted on 20 December 1996, or similar laws prohibiting or 178 | restricting circumvention of such measures. 179 | 180 | When you convey a covered work, you waive any legal power to forbid 181 | circumvention of technological measures to the extent such circumvention is 182 | effected by exercising rights under this License with respect to the covered 183 | work, and you disclaim any intention to limit operation or modification of the 184 | work as a means of enforcing, against the work's users, your or third parties' 185 | legal rights to forbid circumvention of technological measures. 186 | 187 | ### 4. Conveying Verbatim Copies. 188 | 189 | You may convey verbatim copies of the Program's source code as you receive it, 190 | in any medium, provided that you conspicuously and appropriately publish on 191 | each copy an appropriate copyright notice; keep intact all notices stating that 192 | this License and any non-permissive terms added in accord with section 7 apply 193 | to the code; keep intact all notices of the absence of any warranty; and give 194 | all recipients a copy of this License along with the Program. 195 | 196 | You may charge any price or no price for each copy that you convey, and you may 197 | offer support or warranty protection for a fee. 198 | 199 | ### 5. Conveying Modified Source Versions. 200 | 201 | You may convey a work based on the Program, or the modifications to produce it 202 | from the Program, in the form of source code under the terms of section 4, 203 | provided that you also meet all of these conditions: 204 | 205 | - a) The work must carry prominent notices stating that you modified it, and 206 | giving a relevant date. 207 | - b) The work must carry prominent notices stating that it is released under 208 | this License and any conditions added under section 7. This requirement 209 | modifies the requirement in section 4 to *keep intact all notices*. 210 | - c) You must license the entire work, as a whole, under this License to 211 | anyone who comes into possession of a copy. This License will therefore 212 | apply, along with any applicable section 7 additional terms, to the whole 213 | of the work, and all its parts, regardless of how they are packaged. This 214 | License gives no permission to license the work in any other way, but it 215 | does not invalidate such permission if you have separately received it. 216 | - d) If the work has interactive user interfaces, each must display 217 | Appropriate Legal Notices; however, if the Program has interactive 218 | interfaces that do not display Appropriate Legal Notices, your work need 219 | not make them do so. 220 | 221 | A compilation of a covered work with other separate and independent works, 222 | which are not by their nature extensions of the covered work, and which are not 223 | combined with it such as to form a larger program, in or on a volume of a 224 | storage or distribution medium, is called an *aggregate* if the compilation and 225 | its resulting copyright are not used to limit the access or legal rights of the 226 | compilation's users beyond what the individual works permit. Inclusion of a 227 | covered work in an aggregate does not cause this License to apply to the other 228 | parts of the aggregate. 229 | 230 | ### 6. Conveying Non-Source Forms. 231 | 232 | You may convey a covered work in object code form under the terms of sections 4 233 | and 5, provided that you also convey the machine-readable Corresponding Source 234 | under the terms of this License, in one of these ways: 235 | 236 | - a) Convey the object code in, or embodied in, a physical product (including 237 | a physical distribution medium), accompanied by the Corresponding Source 238 | fixed on a durable physical medium customarily used for software 239 | interchange. 240 | - b) Convey the object code in, or embodied in, a physical product (including 241 | a physical distribution medium), accompanied by a written offer, valid for 242 | at least three years and valid for as long as you offer spare parts or 243 | customer support for that product model, to give anyone who possesses the 244 | object code either 245 | 1. a copy of the Corresponding Source for all the software in the product 246 | that is covered by this License, on a durable physical medium 247 | customarily used for software interchange, for a price no more than your 248 | reasonable cost of physically performing this conveying of source, or 249 | 2. access to copy the Corresponding Source from a network server at no 250 | charge. 251 | - c) Convey individual copies of the object code with a copy of the written 252 | offer to provide the Corresponding Source. This alternative is allowed only 253 | occasionally and noncommercially, and only if you received the object code 254 | with such an offer, in accord with subsection 6b. 255 | - d) Convey the object code by offering access from a designated place 256 | (gratis or for a charge), and offer equivalent access to the Corresponding 257 | Source in the same way through the same place at no further charge. You 258 | need not require recipients to copy the Corresponding Source along with the 259 | object code. If the place to copy the object code is a network server, the 260 | Corresponding Source may be on a different server operated by you or a 261 | third party) that supports equivalent copying facilities, provided you 262 | maintain clear directions next to the object code saying where to find the 263 | Corresponding Source. Regardless of what server hosts the Corresponding 264 | Source, you remain obligated to ensure that it is available for as long as 265 | needed to satisfy these requirements. 266 | - e) Convey the object code using peer-to-peer transmission, provided you 267 | inform other peers where the object code and Corresponding Source of the 268 | work are being offered to the general public at no charge under subsection 269 | 6d. 270 | 271 | A separable portion of the object code, whose source code is excluded from the 272 | Corresponding Source as a System Library, need not be included in conveying the 273 | object code work. 274 | 275 | A *User Product* is either 276 | 277 | 1. a *consumer product*, which means any tangible personal property which is 278 | normally used for personal, family, or household purposes, or 279 | 2. anything designed or sold for incorporation into a dwelling. 280 | 281 | In determining whether a product is a consumer product, doubtful cases shall be 282 | resolved in favor of coverage. For a particular product received by a 283 | particular user, *normally used* refers to a typical or common use of that 284 | class of product, regardless of the status of the particular user or of the way 285 | in which the particular user actually uses, or expects or is expected to use, 286 | the product. A product is a consumer product regardless of whether the product 287 | has substantial commercial, industrial or non-consumer uses, unless such uses 288 | represent the only significant mode of use of the product. 289 | 290 | *Installation Information* for a User Product means any methods, procedures, 291 | authorization keys, or other information required to install and execute 292 | modified versions of a covered work in that User Product from a modified 293 | version of its Corresponding Source. The information must suffice to ensure 294 | that the continued functioning of the modified object code is in no case 295 | prevented or interfered with solely because modification has been made. 296 | 297 | If you convey an object code work under this section in, or with, or 298 | specifically for use in, a User Product, and the conveying occurs as part of a 299 | transaction in which the right of possession and use of the User Product is 300 | transferred to the recipient in perpetuity or for a fixed term (regardless of 301 | how the transaction is characterized), the Corresponding Source conveyed under 302 | this section must be accompanied by the Installation Information. But this 303 | requirement does not apply if neither you nor any third party retains the 304 | ability to install modified object code on the User Product (for example, the 305 | work has been installed in ROM). 306 | 307 | The requirement to provide Installation Information does not include a 308 | requirement to continue to provide support service, warranty, or updates for a 309 | work that has been modified or installed by the recipient, or for the User 310 | Product in which it has been modified or installed. Access to a network may be 311 | denied when the modification itself materially and adversely affects the 312 | operation of the network or violates the rules and protocols for communication 313 | across the network. 314 | 315 | Corresponding Source conveyed, and Installation Information provided, in accord 316 | with this section must be in a format that is publicly documented (and with an 317 | implementation available to the public in source code form), and must require 318 | no special password or key for unpacking, reading or copying. 319 | 320 | ### 7. Additional Terms. 321 | 322 | *Additional permissions* are terms that supplement the terms of this License by 323 | making exceptions from one or more of its conditions. Additional permissions 324 | that are applicable to the entire Program shall be treated as though they were 325 | included in this License, to the extent that they are valid under applicable 326 | law. If additional permissions apply only to part of the Program, that part may 327 | be used separately under those permissions, but the entire Program remains 328 | governed by this License without regard to the additional permissions. 329 | 330 | When you convey a copy of a covered work, you may at your option remove any 331 | additional permissions from that copy, or from any part of it. (Additional 332 | permissions may be written to require their own removal in certain cases when 333 | you modify the work.) You may place additional permissions on material, added 334 | by you to a covered work, for which you have or can give appropriate copyright 335 | permission. 336 | 337 | Notwithstanding any other provision of this License, for material you add to a 338 | covered work, you may (if authorized by the copyright holders of that material) 339 | supplement the terms of this License with terms: 340 | 341 | - a) Disclaiming warranty or limiting liability differently from the terms of 342 | sections 15 and 16 of this License; or 343 | - b) Requiring preservation of specified reasonable legal notices or author 344 | attributions in that material or in the Appropriate Legal Notices displayed 345 | by works containing it; or 346 | - c) Prohibiting misrepresentation of the origin of that material, or 347 | requiring that modified versions of such material be marked in reasonable 348 | ways as different from the original version; or 349 | - d) Limiting the use for publicity purposes of names of licensors or authors 350 | of the material; or 351 | - e) Declining to grant rights under trademark law for use of some trade 352 | names, trademarks, or service marks; or 353 | - f) Requiring indemnification of licensors and authors of that material by 354 | anyone who conveys the material (or modified versions of it) with 355 | contractual assumptions of liability to the recipient, for any liability 356 | that these contractual assumptions directly impose on those licensors and 357 | authors. 358 | 359 | All other non-permissive additional terms are considered *further restrictions* 360 | within the meaning of section 10. If the Program as you received it, or any 361 | part of it, contains a notice stating that it is governed by this License along 362 | with a term that is a further restriction, you may remove that term. If a 363 | license document contains a further restriction but permits relicensing or 364 | conveying under this License, you may add to a covered work material governed 365 | by the terms of that license document, provided that the further restriction 366 | does not survive such relicensing or conveying. 367 | 368 | If you add terms to a covered work in accord with this section, you must place, 369 | in the relevant source files, a statement of the additional terms that apply to 370 | those files, or a notice indicating where to find the applicable terms. 371 | 372 | Additional terms, permissive or non-permissive, may be stated in the form of a 373 | separately written license, or stated as exceptions; the above requirements 374 | apply either way. 375 | 376 | ### 8. Termination. 377 | 378 | You may not propagate or modify a covered work except as expressly provided 379 | under this License. Any attempt otherwise to propagate or modify it is void, 380 | and will automatically terminate your rights under this License (including any 381 | patent licenses granted under the third paragraph of section 11). 382 | 383 | However, if you cease all violation of this License, then your license from a 384 | particular copyright holder is reinstated 385 | 386 | - a) provisionally, unless and until the copyright holder explicitly and 387 | finally terminates your license, and 388 | - b) permanently, if the copyright holder fails to notify you of the 389 | violation by some reasonable means prior to 60 days after the cessation. 390 | 391 | Moreover, your license from a particular copyright holder is reinstated 392 | permanently if the copyright holder notifies you of the violation by some 393 | reasonable means, this is the first time you have received notice of violation 394 | of this License (for any work) from that copyright holder, and you cure the 395 | violation prior to 30 days after your receipt of the notice. 396 | 397 | Termination of your rights under this section does not terminate the licenses 398 | of parties who have received copies or rights from you under this License. If 399 | your rights have been terminated and not permanently reinstated, you do not 400 | qualify to receive new licenses for the same material under section 10. 401 | 402 | ### 9. Acceptance Not Required for Having Copies. 403 | 404 | You are not required to accept this License in order to receive or run a copy 405 | of the Program. Ancillary propagation of a covered work occurring solely as a 406 | consequence of using peer-to-peer transmission to receive a copy likewise does 407 | not require acceptance. However, nothing other than this License grants you 408 | permission to propagate or modify any covered work. These actions infringe 409 | copyright if you do not accept this License. Therefore, by modifying or 410 | propagating a covered work, you indicate your acceptance of this License to do 411 | so. 412 | 413 | ### 10. Automatic Licensing of Downstream Recipients. 414 | 415 | Each time you convey a covered work, the recipient automatically receives a 416 | license from the original licensors, to run, modify and propagate that work, 417 | subject to this License. You are not responsible for enforcing compliance by 418 | third parties with this License. 419 | 420 | An *entity transaction* is a transaction transferring control of an 421 | organization, or substantially all assets of one, or subdividing an 422 | organization, or merging organizations. If propagation of a covered work 423 | results from an entity transaction, each party to that transaction who receives 424 | a copy of the work also receives whatever licenses to the work the party's 425 | predecessor in interest had or could give under the previous paragraph, plus a 426 | right to possession of the Corresponding Source of the work from the 427 | predecessor in interest, if the predecessor has it or can get it with 428 | reasonable efforts. 429 | 430 | You may not impose any further restrictions on the exercise of the rights 431 | granted or affirmed under this License. For example, you may not impose a 432 | license fee, royalty, or other charge for exercise of rights granted under this 433 | License, and you may not initiate litigation (including a cross-claim or 434 | counterclaim in a lawsuit) alleging that any patent claim is infringed by 435 | making, using, selling, offering for sale, or importing the Program or any 436 | portion of it. 437 | 438 | ### 11. Patents. 439 | 440 | A *contributor* is a copyright holder who authorizes use under this License of 441 | the Program or a work on which the Program is based. The work thus licensed is 442 | called the contributor's *contributor version*. 443 | 444 | A contributor's *essential patent claims* are all patent claims owned or 445 | controlled by the contributor, whether already acquired or hereafter acquired, 446 | that would be infringed by some manner, permitted by this License, of making, 447 | using, or selling its contributor version, but do not include claims that would 448 | be infringed only as a consequence of further modification of the contributor 449 | version. For purposes of this definition, *control* includes the right to grant 450 | patent sublicenses in a manner consistent with the requirements of this 451 | License. 452 | 453 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent 454 | license under the contributor's essential patent claims, to make, use, sell, 455 | offer for sale, import and otherwise run, modify and propagate the contents of 456 | its contributor version. 457 | 458 | In the following three paragraphs, a *patent license* is any express agreement 459 | or commitment, however denominated, not to enforce a patent (such as an express 460 | permission to practice a patent or covenant not to sue for patent 461 | infringement). To *grant* such a patent license to a party means to make such 462 | an agreement or commitment not to enforce a patent against the party. 463 | 464 | If you convey a covered work, knowingly relying on a patent license, and the 465 | Corresponding Source of the work is not available for anyone to copy, free of 466 | charge and under the terms of this License, through a publicly available 467 | network server or other readily accessible means, then you must either 468 | 469 | 1. cause the Corresponding Source to be so available, or 470 | 2. arrange to deprive yourself of the benefit of the patent license for this 471 | particular work, or 472 | 3. arrange, in a manner consistent with the requirements of this License, to 473 | extend the patent license to downstream recipients. 474 | 475 | *Knowingly relying* means you have actual knowledge that, but for the patent 476 | license, your conveying the covered work in a country, or your recipient's use 477 | of the covered work in a country, would infringe one or more identifiable 478 | patents in that country that you have reason to believe are valid. 479 | 480 | If, pursuant to or in connection with a single transaction or arrangement, you 481 | convey, or propagate by procuring conveyance of, a covered work, and grant a 482 | patent license to some of the parties receiving the covered work authorizing 483 | them to use, propagate, modify or convey a specific copy of the covered work, 484 | then the patent license you grant is automatically extended to all recipients 485 | of the covered work and works based on it. 486 | 487 | A patent license is *discriminatory* if it does not include within the scope of 488 | its coverage, prohibits the exercise of, or is conditioned on the non-exercise 489 | of one or more of the rights that are specifically granted under this License. 490 | You may not convey a covered work if you are a party to an arrangement with a 491 | third party that is in the business of distributing software, under which you 492 | make payment to the third party based on the extent of your activity of 493 | conveying the work, and under which the third party grants, to any of the 494 | parties who would receive the covered work from you, a discriminatory patent 495 | license 496 | 497 | - a) in connection with copies of the covered work conveyed by you (or copies 498 | made from those copies), or 499 | - b) primarily for and in connection with specific products or compilations 500 | that contain the covered work, unless you entered into that arrangement, or 501 | that patent license was granted, prior to 28 March 2007. 502 | 503 | Nothing in this License shall be construed as excluding or limiting any implied 504 | license or other defenses to infringement that may otherwise be available to 505 | you under applicable patent law. 506 | 507 | ### 12. No Surrender of Others' Freedom. 508 | 509 | If conditions are imposed on you (whether by court order, agreement or 510 | otherwise) that contradict the conditions of this License, they do not excuse 511 | you from the conditions of this License. If you cannot convey a covered work so 512 | as to satisfy simultaneously your obligations under this License and any other 513 | pertinent obligations, then as a consequence you may not convey it at all. For 514 | example, if you agree to terms that obligate you to collect a royalty for 515 | further conveying from those to whom you convey the Program, the only way you 516 | could satisfy both those terms and this License would be to refrain entirely 517 | from conveying the Program. 518 | 519 | ### 13. Use with the GNU Affero General Public License. 520 | 521 | Notwithstanding any other provision of this License, you have permission to 522 | link or combine any covered work with a work licensed under version 3 of the 523 | GNU Affero General Public License into a single combined work, and to convey 524 | the resulting work. The terms of this License will continue to apply to the 525 | part which is the covered work, but the special requirements of the GNU Affero 526 | General Public License, section 13, concerning interaction through a network 527 | will apply to the combination as such. 528 | 529 | ### 14. Revised Versions of this License. 530 | 531 | The Free Software Foundation may publish revised and/or new versions of the GNU 532 | General Public License from time to time. Such new versions will be similar in 533 | spirit to the present version, but may differ in detail to address new problems 534 | or concerns. 535 | 536 | Each version is given a distinguishing version number. If the Program specifies 537 | that a certain numbered version of the GNU General Public License *or any later 538 | version* applies to it, you have the option of following the terms and 539 | conditions either of that numbered version or of any later version published by 540 | the Free Software Foundation. If the Program does not specify a version number 541 | of the GNU General Public License, you may choose any version ever published by 542 | the Free Software Foundation. 543 | 544 | If the Program specifies that a proxy can decide which future versions of the 545 | GNU General Public License can be used, that proxy's public statement of 546 | acceptance of a version permanently authorizes you to choose that version for 547 | the Program. 548 | 549 | Later license versions may give you additional or different permissions. 550 | However, no additional obligations are imposed on any author or copyright 551 | holder as a result of your choosing to follow a later version. 552 | 553 | ### 15. Disclaimer of Warranty. 554 | 555 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE 556 | LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER 557 | PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER 558 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 559 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 560 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 561 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 562 | CORRECTION. 563 | 564 | ### 16. Limitation of Liability. 565 | 566 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 567 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 568 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 569 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE 570 | THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED 571 | INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE 572 | PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY 573 | HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 574 | 575 | ### 17. Interpretation of Sections 15 and 16. 576 | 577 | If the disclaimer of warranty and limitation of liability provided above cannot 578 | be given local legal effect according to their terms, reviewing courts shall 579 | apply local law that most closely approximates an absolute waiver of all civil 580 | liability in connection with the Program, unless a warranty or assumption of 581 | liability accompanies a copy of the Program in return for a fee. 582 | 583 | ## END OF TERMS AND CONDITIONS ### 584 | 585 | ### How to Apply These Terms to Your New Programs 586 | 587 | If you develop a new program, and you want it to be of the greatest possible 588 | use to the public, the best way to achieve this is to make it free software 589 | which everyone can redistribute and change under these terms. 590 | 591 | To do so, attach the following notices to the program. It is safest to attach 592 | them to the start of each source file to most effectively state the exclusion 593 | of warranty; and each file should have at least the *copyright* line and a 594 | pointer to where the full notice is found. 595 | 596 | 597 | Copyright (C) 598 | 599 | This program is free software: you can redistribute it and/or modify 600 | it under the terms of the GNU General Public License as published by 601 | the Free Software Foundation, either version 3 of the License, or 602 | (at your option) any later version. 603 | 604 | This program is distributed in the hope that it will be useful, 605 | but WITHOUT ANY WARRANTY; without even the implied warranty of 606 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 607 | GNU General Public License for more details. 608 | 609 | You should have received a copy of the GNU General Public License 610 | along with this program. If not, see . 611 | 612 | Also add information on how to contact you by electronic and paper mail. 613 | 614 | If the program does terminal interaction, make it output a short notice like 615 | this when it starts in an interactive mode: 616 | 617 | Copyright (C) 618 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 619 | This is free software, and you are welcome to redistribute it 620 | under certain conditions; type `show c' for details. 621 | 622 | The hypothetical commands `show w` and `show c` should show the appropriate 623 | parts of the General Public License. Of course, your program's commands might 624 | be different; for a GUI interface, you would use an *about box*. 625 | 626 | You should also get your employer (if you work as a programmer) or school, if 627 | any, to sign a *copyright disclaimer* for the program, if necessary. For more 628 | information on this, and how to apply and follow the GNU GPL, see 629 | [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). 630 | 631 | The GNU General Public License does not permit incorporating your program into 632 | proprietary programs. If your program is a subroutine library, you may consider 633 | it more useful to permit linking proprietary applications with the library. If 634 | this is what you want to do, use the GNU Lesser General Public License instead 635 | of this License. But first, please read 636 | [http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). 637 | --------------------------------------------------------------------------------