pax_global_header00006660000000000000000000000064146530424420014516gustar00rootroot0000000000000052 comment=dd69b063d51724976c16c8f75502fda34fd0af3f ttyplot-1.7.0/000077500000000000000000000000001465304244200132425ustar00rootroot00000000000000ttyplot-1.7.0/.clang-format000066400000000000000000000157621465304244200156300ustar00rootroot00000000000000--- Language: Cpp # BasedOnStyle: Chromium AccessModifierOffset: -1 AlignAfterOpenBracket: Align AlignArrayOfStructures: None AlignConsecutiveAssignments: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false PadOperators: true AlignConsecutiveBitFields: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false PadOperators: false AlignConsecutiveDeclarations: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false PadOperators: false AlignConsecutiveMacros: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false PadOperators: false AlignConsecutiveShortCaseStatements: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCaseColons: false AlignEscapedNewlines: Left AlignOperands: Align AlignTrailingComments: Kind: Always OverEmptyLines: 0 AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: Inline AllowShortIfStatementsOnASingleLine: Never AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: Yes AttributeMacros: - __capability BinPackArguments: true BinPackParameters: true BitFieldColonSpacing: Both BraceWrapping: AfterCaseLabel: false AfterClass: false AfterControlStatement: Never AfterEnum: false AfterExternBlock: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false BeforeCatch: false BeforeElse: false BeforeLambdaBody: false BeforeWhile: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakAfterAttributes: Never BreakAfterJavaFieldAnnotations: false BreakArrays: true BreakBeforeBinaryOperators: None BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Attach BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon BreakInheritanceList: BeforeColon BreakStringLiterals: true ColumnLimit: 88 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false EmptyLineAfterAccessModifier: Never EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IfMacros: - KJ_IF_MAYBE IncludeBlocks: Preserve IncludeCategories: - Regex: '^' Priority: 2 SortPriority: 0 CaseSensitive: false - Regex: '^<.*\.h>' Priority: 1 SortPriority: 0 CaseSensitive: false - Regex: '^<.*' Priority: 2 SortPriority: 0 CaseSensitive: false - Regex: '.*' Priority: 3 SortPriority: 0 CaseSensitive: false IncludeIsMainRegex: '([-_](test|unittest))?$' IncludeIsMainSourceRegex: '' IndentAccessModifiers: false IndentCaseBlocks: false IndentCaseLabels: true IndentExternBlock: AfterExternBlock IndentGotoLabels: true IndentPPDirectives: None IndentRequiresClause: true IndentWidth: 4 IndentWrappedFunctionNames: false InsertBraces: false InsertNewlineAtEOF: false InsertTrailingCommas: None IntegerLiteralSeparator: Binary: 0 BinaryMinDigits: 0 Decimal: 0 DecimalMinDigits: 0 Hex: 0 HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false KeepEmptyLinesAtEOF: false LambdaBodyIndentation: Signature LineEnding: DeriveLF MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Never ObjCBlockIndentWidth: 2 ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PackConstructorInitializers: NextLine PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 1 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakOpenParenthesis: 0 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Right PPIndentWidth: -1 QualifierAlignment: Leave RawStringFormats: - Language: Cpp Delimiters: - cc - CC - cpp - Cpp - CPP - 'c++' - 'C++' CanonicalDelimiter: '' BasedOnStyle: google - Language: TextProto Delimiters: - pb - PB - proto - PROTO EnclosingFunctions: - EqualsProto - EquivToProto - PARSE_PARTIAL_TEXT_PROTO - PARSE_TEST_PROTO - PARSE_TEXT_PROTO - ParseTextOrDie - ParseTextProtoOrDie - ParseTestProto - ParsePartialTestProto CanonicalDelimiter: pb BasedOnStyle: google ReferenceAlignment: Pointer ReflowComments: true RemoveBracesLLVM: false RemoveParentheses: Leave RemoveSemicolon: false RequiresClausePosition: OwnLine RequiresExpressionIndentation: OuterScope SeparateDefinitionBlocks: Leave ShortNamespaceLines: 1 SortIncludes: Never SortJavaStaticImport: Before SortUsingDeclarations: LexicographicNumeric SpaceAfterCStyleCast: false SpaceAfterLogicalNot: true SpaceAfterTemplateKeyword: true SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements SpaceBeforeParensOptions: AfterControlStatements: true AfterForeachMacros: true AfterFunctionDefinitionName: false AfterFunctionDeclarationName: false AfterIfMacros: true AfterOverloadedOperator: false AfterRequiresInClause: false AfterRequiresInExpression: false BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 2 SpacesInAngles: Never SpacesInContainerLiterals: true SpacesInLineCommentPrefix: Minimum: 1 Maximum: -1 SpacesInParens: Never SpacesInParensOptions: InCStyleCasts: false InConditionalStatements: false InEmptyParentheses: false Other: false SpacesInSquareBrackets: false Standard: Auto StatementAttributeLikeMacros: - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 8 UseTab: Never VerilogBreakBetweenInstancePorts: true WhitespaceSensitiveMacros: - BOOST_PP_STRINGIZE - CF_SWIFT_NAME - NS_SWIFT_NAME - PP_STRINGIZE - STRINGIZE ... ttyplot-1.7.0/.github/000077500000000000000000000000001465304244200146025ustar00rootroot00000000000000ttyplot-1.7.0/.github/dependabot.yml000066400000000000000000000005101465304244200174260ustar00rootroot00000000000000# Copyright (c) 2023 Sebastian Pipping # Licensed under Apache License Version 2.0 version: 2 updates: - package-ecosystem: "github-actions" commit-message: include: "scope" prefix: "Actions" directory: "/" labels: - "enhancement" schedule: interval: "weekly" ttyplot-1.7.0/.github/workflows/000077500000000000000000000000001465304244200166375ustar00rootroot00000000000000ttyplot-1.7.0/.github/workflows/clang_format.yml000066400000000000000000000024371465304244200220240ustar00rootroot00000000000000# Copyright (c) 2023 Sebastian Pipping # Licensed under Apache License Version 2.0 name: Enforce clang-format on: pull_request: push: schedule: - cron: '0 3 * * 5' # Every Friday at 3am workflow_dispatch: # Minimum permissions for security permissions: contents: read jobs: clang-format: name: Enforce clang-format runs-on: ubuntu-22.04 env: CLANG_MAJOR_VERSION: 17 steps: - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 - name: Add Clang/LLVM repositories run: |- set -x source /etc/os-release wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - sudo add-apt-repository "deb http://apt.llvm.org/${UBUNTU_CODENAME}/ llvm-toolchain-${UBUNTU_CODENAME}-${CLANG_MAJOR_VERSION} main" - name: Install clang-format run: |- set -x sudo apt-get update sudo apt-get install --yes --no-install-recommends -V \ clang-format-${CLANG_MAJOR_VERSION} - name: Enforce clang-format run: |- set -x clang-format-${CLANG_MAJOR_VERSION} --version clang-format-${CLANG_MAJOR_VERSION} -i *.c git diff --exit-code # i.e. reject non-empty diff ttyplot-1.7.0/.github/workflows/codespell.yml000066400000000000000000000014771465304244200213450ustar00rootroot00000000000000# Copyright (c) 2023 Sebastian Pipping # Licensed under Apache License Version 2.0 name: Enforce codespell-clean spelling on: pull_request: push: schedule: - cron: '0 3 * * 5' # Every Friday at 3am workflow_dispatch: # Minimum permissions for security permissions: contents: read jobs: codespell: name: Enforce codespell-clean spelling runs-on: ubuntu-22.04 steps: - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 - uses: codespell-project/actions-codespell@94259cd8be02ad2903ba34a22d9c13de21a74461 # v2.0 with: # "nd" (with lowercase "n") is from ".Nd" (with uppercase "n") in ttyplot.1 # https://github.com/codespell-project/codespell/issues/3233#issuecomment-1828026522 ignore_words_list: nd ttyplot-1.7.0/.github/workflows/linux_and_macos.yml000066400000000000000000000166051465304244200225350ustar00rootroot00000000000000# Copyright (c) 2023 Sebastian Pipping # Licensed under Apache License Version 2.0 name: Build on Linux/macOS on: pull_request: push: schedule: - cron: '0 3 * * 5' # Every Friday at 3am workflow_dispatch: # Minimum permissions for security permissions: contents: read jobs: linux: name: Build (${{ matrix.cc }}/${{ matrix.make }} on ${{ matrix.runs-on }}) runs-on: ${{ matrix.runs-on }} strategy: fail-fast: false matrix: include: - cc: gcc-14 cxx: g++-14 clang_major_version: null clang_repo_suffix: null make: make runs-on: ubuntu-24.04 - cc: clang-18 cxx: clang++-18 clang_major_version: 18 clang_repo_suffix: -18 make: bmake runs-on: ubuntu-22.04 - cc: musl-gcc cxx: 'false' clang_major_version: null clang_repo_suffix: null make: bmake runs-on: ubuntu-22.04 - cc: gcc-11 cxx: g++-11 clang_major_version: null clang_repo_suffix: null make: make runs-on: macos-12 - cc: gcc-13 cxx: g++-13 clang_major_version: null clang_repo_suffix: null make: bmake runs-on: macos-12 - cc: clang-15 cxx: clang++-15 clang_major_version: 15 clang_repo_suffix: null make: bsdmake runs-on: macos-12 steps: - name: Add Clang/LLVM repositories if: "${{ runner.os == 'Linux' && contains(matrix.cxx, 'clang') }}" run: |- set -x source /etc/os-release wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - sudo add-apt-repository "deb http://apt.llvm.org/${UBUNTU_CODENAME}/ llvm-toolchain-${UBUNTU_CODENAME}${{ matrix.clang_repo_suffix }} main" - name: Install build dependencies if: "${{ runner.os == 'Linux' }}" run: |- sudo apt-get update sudo apt-get install --yes --no-install-recommends \ bmake \ libncurses-dev \ musl-tools \ pkg-config - name: Install build dependencies if: "${{ runner.os == 'macOS' }}" run: |- brew install \ bmake \ bsdmake \ coreutils - name: Install build dependency Clang ${{ matrix.clang_major_version }} if: "${{ runner.os == 'Linux' && contains(matrix.cxx, 'clang') }}" run: |- sudo apt-get install --yes --no-install-recommends -V \ clang-${{ matrix.clang_major_version }} \ libclang-rt-${{ matrix.clang_major_version }}-dev - name: Add versioned aliases for Clang ${{ matrix.clang_major_version }} if: "${{ runner.os == 'macOS' && contains(matrix.cxx, 'clang') }}" run: |- set -x sudo ln -s "$(brew --prefix llvm@${{ matrix.clang_major_version }})"/bin/clang /usr/local/bin/clang-${{ matrix.clang_major_version }} sudo ln -s "$(brew --prefix llvm@${{ matrix.clang_major_version }})"/bin/clang++ /usr/local/bin/clang++-${{ matrix.clang_major_version }} - name: Checkout Git branch uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 - name: Build musl Ncurses if: "${{ runner.os == 'Linux' && contains(matrix.cc, 'musl') }}" run: |- set -x -o pipefail sudo apt-get remove --yes libncurses-dev # to be sure to not mix them wget -q https://invisible-island.net/datafiles/release/ncurses.tar.gz tar xf ncurses.tar.gz pushd ncurses-*/ configure_args=( # Redirect everything to musl CC=musl-gcc --prefix=/usr --includedir=/usr/include/x86_64-linux-musl --libdir=/usr/lib/x86_64-linux-musl # Enable things we rely on --enable-pc-files --enable-shared --enable-widec # Disable things we don't need (to speed up CI) --disable-static --without-cxx-binding --without-manpages --without-progs --without-tack --without-tests ) ./configure "${configure_args[@]}" make -j$(nproc) sudo make install popd rm -Rf ncurses-*/ ncurses.tar.gz # Mass-fix "#include " to "#include " grep -RlF "/dev/null || true CFLAGS="-std=c99 -pedantic -Werror ${sanitizer} -O1" LDFLAGS="${as_needed} ${sanitizer}" ${MAKE} - name: 'Install' env: MAKE: ${{ matrix.make }} run: |- set -x -o pipefail ${MAKE} install DESTDIR="${PWD}"/ROOT/ find ROOT/ | sort | xargs ls -ld - name: 'Uninstall' env: MAKE: ${{ matrix.make }} run: |- set -x ${MAKE} uninstall DESTDIR="${PWD}"/ROOT/ [[ "$(find ROOT/ -not -type d | tee /dev/stderr)" == '' ]] # i.e. fail CI if leftover files - name: 'Run UI tests' run: |- ./recordings/record.sh rm -Rf recordings/venv/ - name: 'Upload UI test renderings for inspection' uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4 with: name: ttyplot_ui_test_${{ github.sha }}_${{ matrix.runs-on }}_${{ matrix.cc }}_${{ matrix.make }} path: recordings/actual* if-no-files-found: error - name: 'Evaluate UI test results' run: |- cat <<"EOF" ################################################################ ## If this step FAILS you can get the expected ANSI screenshots ## back in sync with reality by running: ## ## $ ./recordings/get_back_in_sync.sh ## ## More details on the topic can be found in CONTRIBUTING.md . ################################################################ EOF diff -u recordings/{expected,actual}.txt rm -f recordings/actual.txt - name: 'Clean' env: MAKE: ${{ matrix.make }} run: |- set -x -o pipefail ${MAKE} clean [[ "$(git ls-files -o | tee /dev/stderr | wc -l)" -eq 0 ]] ttyplot-1.7.0/.gitignore000066400000000000000000000000231465304244200152250ustar00rootroot00000000000000stresstest ttyplot ttyplot-1.7.0/CONTRIBUTING.md000066400000000000000000000023671465304244200155030ustar00rootroot00000000000000# Welcome to ttyplot! This file documents how to contribute to ttyplot and things to know before facing them. It will likely never be complete, but if something important turns out to be missing here, let's add it! ## Problem: The CI complains that the UI test failed The CI does basic UI testing by making ANSI "screenshots" of the running application and comparing them against pre-recorded ANSI "screenshots" `recordings/expected.txt`. When you make changes to ttyplot that change the *runtime appearance* of ttyplot, the CI will hopefully catch these changes and reject them as a regression. In a case where these changes are made with full intention, the screenshots that the CI is comparing to at `recordings/expected.txt` will then need to be regenerated. For your convenience, an easy way to do that is: ```console $ ./recordings/get_back_in_sync.sh ``` The script will re-render these screenshots and even create a Git commit for you. For all that to work well on macOS, you would need to install: ```console $ brew tap homebrew/cask-fonts $ brew install \ coreutils ``` On a Debian-based Linux including Ubuntu, you would need to install: ```console $ sudo apt-get update $ sudo apt-get install --no-install-recommends -V \ python3-venv ``` ttyplot-1.7.0/LICENSE000066400000000000000000000261351465304244200142560ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ttyplot-1.7.0/Makefile000077500000000000000000000012211465304244200147010ustar00rootroot00000000000000DESTDIR ?= PREFIX ?= /usr/local MANPREFIX ?= $(PREFIX)/man CFLAGS += -Wall -Wextra CFLAGS += `pkg-config --cflags ncursesw` LDLIBS += `pkg-config --libs ncursesw` -lm all: ttyplot stresstest install: ttyplot ttyplot.1 install -d $(DESTDIR)$(PREFIX)/bin install -d $(DESTDIR)$(MANPREFIX)/man1 install -m755 ttyplot $(DESTDIR)$(PREFIX)/bin install -m644 ttyplot.1 $(DESTDIR)$(MANPREFIX)/man1 uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/ttyplot rm -f $(DESTDIR)$(MANPREFIX)/man1/ttyplot.1 clean: rm -f ttyplot stresstest .c: @pkg-config --version > /dev/null $(CC) $(CFLAGS) $(LDFLAGS) $< $(LDLIBS) -o $@ .PHONY: all clean install uninstall ttyplot-1.7.0/README.md000066400000000000000000000215131465304244200145230ustar00rootroot00000000000000# ttyplot a realtime plotting utility for text mode consoles and terminals with data input from stdin / pipe takes data from standard input / unix pipeline, most commonly some tool like *ping, snmpget, netstat, ip link, ifconfig, sar, vmstat*, etc. and plots in text mode on a terminal in real time, for example a simple **ping**: ![ttyplot ping](ttyplot-ping.png)     supports rate calculation for counters and up to two graphs on a single display using reverse video for second line, for example **snmpget**, **ip link**, **rrdtool**, etc: ![ttyplot snmp](ttyplot-snmp.png)     ## get Packaging status ### ubuntu ``` snap install ttyplot ``` ### debian ``` apt install ttyplot ``` alternatively [download](https://packages.debian.org/sid/ttyplot) | [tracker](https://tracker.debian.org/pkg/ttyplot) ### gentoo ``` emerge -av app-admin/ttyplot ``` ### macOS ``` brew install ttyplot ``` ### termux ``` pkg install ttyplot ``` ### FreeBSD ``` pkg install ttyplot ``` ### misc for other platforms see [releases tab](https://github.com/tenox7/ttyplot/releases), also [older versions](https://github.com/tenox7/ttyplot/releases/tag/1.4) ## examples ### cpu usage from vmstat using awk to pick the right column `fflush()` is needed to disable stdio buffering ``` vmstat -n 1 | gawk '{ print 100-int($(NF-2)); fflush(); }' | ttyplot -s 100 -t "CPU Usage" -u "%" ``` ### memory usage on Linux using free, grep, tr and cut `stdbuf` is used to disable stdio buffering throughout the pipeline ``` free -m -s 1 | stdbuf -o0 grep "^Mem:" | stdbuf -o0 tr -s " " | stdbuf -o0 cut -d" " -f3 | ttyplot -t "MEM Usage" -u "MB" ``` ### memory usage on macOS ``` vm_stat 1 | awk '{ print int($2)*4096/1024^3; fflush(); }' | ttyplot -t "MacOS Memory Usage" -u GB ``` ### number of processes in running and io blocked state ``` vmstat -n 1 | perl -lane 'BEGIN{$|=1} print "@F[0,1]"' | ttyplot -2 -t "procs in R and D state" ``` ### load average via uptime and awk ``` { while true; do uptime | gawk '{ gsub(/,/, ""); print $(NF-2) }'; sleep 1; done } | ttyplot -t "load average" -s load ``` ### ping plot with sed on macOS change `-u` to `-l` ``` ping 8.8.8.8 | sed -u 's/^.*time=//g; s/ ms//g' | ttyplot -t "ping to 8.8.8.8" -u ms ``` ### wifi signal level in -dBM (higher is worse) using iwconfig ``` { while true; do iwconfig 2>/dev/null | grep "Signal level" | sed -u 's/^.*Signal level=-//g; s/dBm//g'; sleep 1; done } | ttyplot -t "wifi signal" -u "-dBm" -s 90 ``` ### wifi signal on macOS ``` { while true; do /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --getinfo | awk '/agrCtlRSSI/ {print -$2; fflush();}'; sleep 1; done } | ttyplot -t "wifi signal" -u "-dBm" -s 90 ``` ### cpu temperature from proc ``` { while true; do awk '{ printf("%.1f\n", $1/1000) }' /sys/class/thermal/thermal_zone0/temp; sleep 1; done } | ttyplot -t "cpu temp" -u C ``` ### fan speed from lm-sensors using grep, tr and cut ``` { while true; do sensors | grep fan1: | tr -s " " | cut -d" " -f2; sleep 1; done } | ttyplot -t "fan speed" -u RPM ``` ### memory usage from rrdtool and collectd using awk ``` { while true; do rrdtool lastupdate /var/lib/collectd/rrd/$(hostname)/memory/memory-used.rrd | awk 'END { print ($NF)/1024/1024 }'; sleep 1; done } | ttyplot -m $(awk '/MemTotal/ { print ($2)/1024 }' /proc/meminfo) -t "Memoru Used" -u MB ``` ### bitcoin price chart using curl and jq ``` { while true; do curl -sL https://api.coindesk.com/v1/bpi/currentprice.json | jq .bpi.USD.rate_float; sleep 600; done } | ttyplot -t "bitcoin price" -u usd ``` ### stock quote chart ``` { while true; do curl -sL https://api.iextrading.com/1.0/stock/googl/price; echo; sleep 600; done } | ttyplot -t "google stock price" -u usd ``` ### prometheus load average via node_exporter ``` { while true; do curl -s http://10.4.7.180:9100/metrics | grep "^node_load1 " | cut -d" " -f2; sleep 1; done } | ttyplot ```     ## network/disk throughput examples ttyplot supports "two line" plot for in/out or read/write ### snmp network throughput for an interface using snmpdelta ``` snmpdelta -v 2c -c public -Cp 10 10.23.73.254 1.3.6.1.2.1.2.2.1.{10,16}.9 | gawk '{ print $NF/1000/1000/10; fflush(); }' | ttyplot -2 -t "interface 9 throughput" -u Mb/s ``` ### network throughput for an interface using netstat (OpenBSD, FreeBSD) ``` netstat -b -w ${1} -I em0 | awk 'NR>3 { print $1/1024; print $2/1024; fflush }' | ttyplot -2 -t "IN/OUT Bandwidth in KB/s (${1}s resolution)" -u "KB/s" -c "#" ``` ### local network throughput for all interfaces combined from sar ``` sar -n DEV 1 | gawk '{ if($6 ~ /rxkB/) { print iin/1000; print out/1000; iin=0; out=0; fflush(); } iin=iin+$6; out=out+$7; }' | ttyplot -2 -u "MB/s" ``` ### disk throughput from iostat ``` iostat -xmy 1 nvme0n1 | stdbuf -o0 tr -s " " | stdbuf -o0 cut -d " " -f 4,5 | ttyplot -2 -t "nvme0n1 throughput" -u MB/s ```     ## rate calculator for counters ttyplot also supports *counter* style metrics, calculating *rate* by measured time difference between samples ### snmp network throughput for an interface using snmpget ``` { while true; do snmpget -v 2c -c public 10.23.73.254 1.3.6.1.2.1.2.2.1.{10,16}.9 | awk '{ print $NF/1000/1000; }'; sleep 10; done } | ttyplot -2 -r -u "MB/s" ``` ### local interface throughput using ip link and jq ``` { while true; do ip -s -j link show enp0s31f6 | jq .[].stats64.rx.bytes/1024/1024,.[].stats64.tx.bytes/1024/1024; sleep 1; done } | ttyplot -r -2 -u "MB/s" ``` ### prometheus node exporter disk throughput for /dev/sda ``` { while true; do curl -s http://10.11.0.173:9100/metrics | awk '/^node_disk_.+_bytes_total{device="sda"}/ { printf("%f\n", $2/1024/1024); }'; sleep 1; done } | ttyplot -r -2 -u MB/s -t "10.11.0.173 sda writes" ``` ### network throughput from collectd with rrdtool and awk ``` { while true; do rrdtool lastupdate /var/lib/collectd/rrd/$(hostname)/interface-enp1s0/if_octets.rrd | awk 'END { print ($2)/1000/1000, ($3)/1000/1000 }'; sleep 10; done } | ttyplot -2 -r -t "enp1s0 throughput" -u MB/s ```     ## flags ``` ttyplot [-2] [-r] [-c plotchar] [-s scale] [-m max] [-M min] [-t title] [-u unit] ttyplot -h ttyplot -v -2 read two values and draw two plots, the second one is in reverse video -r rate of a counter (divide value by measured sample interval) -c character to use for plot line, eg @ # % . etc -e character to use for error line when value exceeds hardmax (default: e) -E character to use for error symbol displayed when value is less than hardmin (default: v) -s initial scale of the plot (can go above if data input has larger value) -m maximum value, if exceeded draws error line (see -e), upper-limit of plot scale is fixed -M minimum value, if entered less than this, draws error symbol (see -E), lower-limit of the plot scale is fixed -t title of the plot -u unit displayed beside vertical bar -v print the current version and exit -h print this help message and exit ```     ## key bindings when reading data from a pipe, ttyplot accepts the following commands typed at the terminal: ``` q quit r toggle rate mode ``` these commands do not work if the standard input is a terminal: in this case quit with Ctrl-C.     ## frequently questioned answers ### ttyplot quits when there is no more data **UPDATE** as of version 1.5 ttyplot will print "input stream closed" and wait forever, instead of quititing. this is by design; your problem is likely that the output is lost (terminal erased) when ttyplot exits; this is explained in [the next question below](#ttyplot-erases-screen-when-exiting) you can also simply work around it, by adding `sleep`, `read`, `cat` at the end of the stream: ``` { echo 1 2 3; cat; } | ttyplot ``` ### ttyplot erases screen when exiting this is because of [alternate screen](https://invisible-island.net/xterm/xterm.faq.html#xterm_tite) in terminals based on xterm; if you use one of these this will likely work around it: ``` echo 1 2 3 | TERM=vt100 ttyplot ``` you can also permanently fix terminfo entry (this will make a copy in $HOME/.terminfo/): ``` infocmp -I $TERM | sed -e 's/smcup=[^,]*,//g' -e 's/rmcup=[^,]*,//g' | tic - ``` ### when running interactively and non-numeric data is entered (eg. some key) ttyplot hangs press `ctrl^j` to re-set ### stdio buffering by default in unix stdio is buffered, you can work around it [in various ways](http://www.perkin.org.uk/posts/how-to-fix-stdio-buffering.html) also [this](https://github.com/collectd/collectd/wiki/Plugin-Exec#output-buffering) ## legal stuff ``` License: Apache 2.0 Copyright (c) 2013-2018 Antoni Sawicki Copyright (c) 2019-2024 Google LLC Copyright (c) 2023 Edgar Bonet Copyright (c) 2023 Sebastian Pipping ``` ttyplot-1.7.0/recordings/000077500000000000000000000000001465304244200154015ustar00rootroot00000000000000ttyplot-1.7.0/recordings/.gitignore000066400000000000000000000000231465304244200173640ustar00rootroot00000000000000/venv/ /actual.txt ttyplot-1.7.0/recordings/expected.txt000066400000000000000000000163621465304244200177530ustar00rootroot00000000000000[90x20] Frame 1: +------------------------------------------------------------------------------------------+ | .: ttyplot :. | | ^ | | │ | | │ | | │ | | │ | | │ | | │ | | │ | | │ | | │ waiting for data from stdin | | │ | | │ | | │ | | │ | | │ | | │ | | └─────────────────────────────────────────────────────────────────────────────────────> | | X Thu Jan 1 00:00:00 1970 | |   https://github.com/tenox7/ttyplot 1.7.0 | +------------------------------------------------------------------------------------------+ [90x20] Frame 2: +------------------------------------------------------------------------------------------+ | .: ttyplot :. | | ^ 4.0   | | │   | | │   | | │   | | │ 3.0 X | | │ X | | │ X | | │ X | | │ 2.0  X | | │  X | | │  X | | │  X | | │ 1.0 XX | | │ XX | | │ XX | | │ XX | | └─────────────────────────────────────────────────────────────────────────────────────> | | X last=3.0 min=1.0 max=3.0 avg=2.0 Thu Jan 1 00:00:00 1970 | |   last=4.0 min=2.0 max=4.0 avg=3.0 https://github.com/tenox7/ttyplot 1.7.0 | +------------------------------------------------------------------------------------------+ [90x20] Frame 3: +------------------------------------------------------------------------------------------+ | .: ttyplot :. | | ^ 4.0   | | │   | | │   | | │   | | │ 3.0 X | | │ X | | │ X | | │ X | | │ 2.0  X | | │ input stream closed  X | | │  X | | │  X | | │ 1.0 XX | | │ XX | | │ XX | | │ XX | | └─────────────────────────────────────────────────────────────────────────────────────> | | X last=3.0 min=1.0 max=3.0 avg=2.0 Thu Jan 1 00:00:00 1970 | |   last=4.0 min=2.0 max=4.0 avg=3.0 https://github.com/tenox7/ttyplot 1.7.0 | +------------------------------------------------------------------------------------------+ ttyplot-1.7.0/recordings/flip_book.py000077500000000000000000000112001465304244200177140ustar00rootroot00000000000000#! /usr/bin/env python3 # Copyright (c) 2015 by pyte authors and contributors # Copyright (c) 2023 by Sebastian Pipping # # Licensed under LGPL v3, see pyte's LICENSE file for more details. # # Based on pyte's example "nanoterm.py" # https://raw.githubusercontent.com/selectel/pyte/master/examples/nanoterm.py # and a few lines from # https://github.com/selectel/pyte/blob/master/pyte/screens.py import enum import os import pty import select import signal import sys import time from functools import lru_cache from typing import Callable, Generator import pyte from pyte.screens import Char, StaticDefaultDict from wcwidth import wcwidth as _wcwidth # type: ignore[import-untyped] wcwidth: Callable[[str], int] = lru_cache(maxsize=4096)(_wcwidth) # from pyte/screens.py class AnsiGraphics(enum.Enum): # https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters RESET = 0 REVERSE = 7 def ansi_sequence(n): # https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences return f'\033[{n.value}m' def pyte_char_to_ansi(ch: Char) -> str: """ Render a single isolated ``pyte.screens.Char`` using ANSI escape sequences https://pyte.readthedocs.io/en/latest/api.html#pyte.screens.Char """ chunks = [] if ch.reverse: chunks.append(ansi_sequence(AnsiGraphics.RESET)) chunks.append(ansi_sequence(AnsiGraphics.REVERSE)) chunks.append(ch.data) if ch.reverse: chunks.append(ansi_sequence(AnsiGraphics.RESET)) return ''.join(chunks) def ansi_display(screen): """ A (mostly identical) fork of ``pyte.screens.Screen.display`` that uses ``pyte_char_to_ansi`` rather than ``line[x].data``. """ def render(line: StaticDefaultDict[int, Char]) -> Generator[str, None, None]: is_wide_char = False for x in range(screen.columns): if is_wide_char: # Skip stub is_wide_char = False continue char = line[x].data assert sum(map(wcwidth, char[1:])) == 0 is_wide_char = wcwidth(char[0]) == 2 yield pyte_char_to_ansi(line[x]) return ["".join(render(screen.buffer[y])) for y in range(screen.lines)] def dump(screen, frame_number): print(f'[{screen.columns}x{screen.lines}] Frame {frame_number}:') print(f'+{"-" * screen.columns}+') for line in ansi_display(screen): print(f'|{line}|') print(f'+{"-" * screen.columns}+') print(flush=True) def get_runtime_nanos(): return time.clock_gettime_ns(time.CLOCK_MONOTONIC) def create_rhythmic_dumper(screen): nano_before = get_runtime_nanos() frame_number = 1 screen.dirty.clear() def dump_or_not(last=False): nonlocal nano_before nonlocal frame_number nano_now = get_runtime_nanos() # For CI robustness, we want to: # 1. Display 1 frame per second at most # 2. Never display two identical consecutive frames # 3. Only show an all-empty frame if it is not the first frame # or the last frame # 4. Always show at least one frame (overruling 3.) if last or nano_now - nano_before >= 1_000_000_000: if (frame_number == 1 and last) or (screen.dirty and not ((frame_number == 1 or last) and ''.join(ansi_display(screen)).isspace())): dump(screen, frame_number=frame_number) screen.dirty.clear() frame_number += 1 nano_before = nano_now return dump_or_not if __name__ == "__main__": if len(sys.argv) <= 1: progname_py = os.path.basename(sys.argv[0]) sys.exit(f'usage: python3 {progname_py} COMMAND [ARG ..]') COLUMNS = 90 LINES = 20 screen = pyte.Screen(COLUMNS, LINES) stream = pyte.ByteStream(screen) dump_or_not = create_rhythmic_dumper(screen) p_pid, master_fd = pty.fork() if p_pid == 0: # Child. env = os.environ.copy() env.update(dict(TERM="linux", COLUMNS=str(COLUMNS), LINES=str(LINES))) os.execvpe(sys.argv[1], sys.argv[1:], env=env) while True: try: readables, _w, _x = select.select( [master_fd], [], [], 0.1) except (KeyboardInterrupt, # Stop right now! ValueError): # Nothing to read. break dump_or_not() if not readables: continue try: data = os.read(master_fd, 1024) except OSError: break if not data: break stream.feed(data) dump_or_not() os.kill(p_pid, signal.SIGTERM) dump_or_not(last=True) ttyplot-1.7.0/recordings/get_back_in_sync.sh000077500000000000000000000012121465304244200212150ustar00rootroot00000000000000#! /usr/bin/env bash ## ## Copyright (c) 2023 by Sebastian Pipping ## Apache License 2.0 ## set -e -u : ${MAKE:=make} self_dir="$(dirname "$(type -P "$0")")" cd "${self_dir}" if ! git diff --exit-code >/dev/null \ || ! git diff --cached --exit-code >/dev/null ; then echo 'ERROR: Please commit/stash your uncommitted work first, aborting.' >&2 exit 1 fi "${MAKE}" -C .. # to ensure up-to-date ttyplot binary ./record.sh cp actual.txt expected.txt git add expected.txt if git diff --cached --exit-code >/dev/null ; then echo 'Already in sync, good.' else EDITOR=true git commit -m 'recordings: Sync expected.txt' fi ttyplot-1.7.0/recordings/record.sh000077500000000000000000000016131465304244200172170ustar00rootroot00000000000000#! /usr/bin/env bash ## ## Copyright (c) 2023 by Sebastian Pipping ## Apache License 2.0 ## set -e -u self_dir="$(dirname "$(realpath "$(type -P "$0")")")" ttyplot_bin_dir="${self_dir}/.." # i.e. the local build export PATH="${ttyplot_bin_dir}:${PATH}" # Consistent clock display for reproducibility export FAKETIME=yesplease cd "${self_dir}" # Ensure recent and pinned pyte [[ -d venv/ ]] || python3 -m venv venv/ source venv/bin/activate pip3 install --disable-pip-version-check pyte==0.8.2 # Check and report on runtime requirements which realpath timeout ttyplot # Enforce a diff on failure rm -f actual.txt # Run and record the actual test run # MallocNanoZone=0 is for AddressSanitizer on macOS, see https://stackoverflow.com/a/70209891/11626624 . ./flip_book.py \ timeout -s INT 5 sh -c '{ sleep 2.5; seq 4; sleep 1.5; } | MallocNanoZone=0 ttyplot -2 -c X' 2>&1 \ | tee actual.txt ttyplot-1.7.0/snap/000077500000000000000000000000001465304244200142035ustar00rootroot00000000000000ttyplot-1.7.0/snap/snapcraft.yaml000066400000000000000000000014201465304244200170450ustar00rootroot00000000000000name: ttyplot version: 1.6.2 summary: realtime plotting utility for terminal/console with data input from stdin description: | takes data from standard input / unix pipeline, most commonly some tool like ping, snmpget, netstat, ifconfig, ip, sar, vmstat, etc. and plots in text mode on a terminal in real time, supports rate calculation for counters and up to two graphs on a single display using reverse video for second line confinement: strict grade: stable parts: ttyplot: plugin: make source-type: git source: https://github.com/tenox7/ttyplot.git build-packages: - gcc - make - libncurses5-dev - libtinfo-dev stage-packages: - libncurses5 - libtinfo5 apps: ttyplot: command: usr/local/bin/ttyplot ttyplot-1.7.0/stresstest.c000066400000000000000000000072161465304244200156370ustar00rootroot00000000000000// // stresstest ttyplot // // License: Apache 2.0 // // This is needed for musl libc #if ! defined(_XOPEN_SOURCE) || (_XOPEN_SOURCE < 500) #undef _XOPEN_SOURCE // to address warnings about potential re-definition #define _XOPEN_SOURCE 500 #endif #include #include #include #include #include #include #include const char help[] = "Usage:\n" " stresstest [-2] [-c] [-g] [-n] [-r rate]\n" " stresstest -h\n" "\n" " -h print this help message and exit\n" " -2 output two waves\n" " -c randomly chunk the output\n" " -g occasionally output garbage\n" " -n output negative values\n" " -r rate sample rate in samples/s (default: 100)\n" " -s seed set random seed\n"; const char optstring[] = "h2cgnr:s:"; int main(int argc, char *argv[]) { char buffer[1024]; size_t buffer_pos = 0; int opt; bool two_waves = false; bool chunked = false; bool add_garbage = false; bool output_negative = false; double rate = 100; unsigned int seed = time(NULL); // Parse the command line. while ((opt = getopt(argc, argv, optstring)) != -1) { switch (opt) { case 'h': printf(help); return EXIT_SUCCESS; case '2': two_waves = true; break; case 'c': chunked = true; break; case 'g': add_garbage = true; break; case 'n': output_negative = true; break; case 'r': rate = atof(optarg); break; case 's': seed = atoi(optarg); break; default: fprintf(stderr, help); return EXIT_FAILURE; } } if (argc > optind) { fprintf(stderr, help); return EXIT_FAILURE; } const useconds_t delay = 1e6 / rate; srand(seed); for (unsigned int n = 0;; n += 5) { buffer_pos += sprintf(buffer + buffer_pos, "%.1f\n", (sin(n * M_PI / 180) * 5) + (output_negative ? 0 : 5)); if (add_garbage && rand() <= RAND_MAX / 5) buffer_pos += sprintf(buffer + buffer_pos, "garbage "); if (two_waves) { buffer_pos += sprintf(buffer + buffer_pos, "%.1f\n", (cos(n * M_PI / 180) * 5) + (output_negative ? 0 : 5)); if (add_garbage && rand() <= RAND_MAX / 5) buffer_pos += sprintf(buffer + buffer_pos, "garbage "); } if (chunked) { size_t send_pos = 0; while (buffer_pos - send_pos >= 16) { const size_t bytes_to_send = 1 + rand() % 16; // 1..16 const ssize_t bytes_sent = write(STDOUT_FILENO, buffer + send_pos, bytes_to_send); usleep(50); // let ttyplot read this before proceeding if (bytes_sent > 0) send_pos += bytes_sent; } if (send_pos > 0 && send_pos < buffer_pos) memmove(buffer, buffer + send_pos, buffer_pos - send_pos); buffer_pos -= send_pos; } else { const ssize_t bytes_sent = write(STDOUT_FILENO, buffer, buffer_pos); if ((bytes_sent > 0) && ((size_t)bytes_sent < buffer_pos)) memmove(buffer, buffer + bytes_sent, buffer_pos - bytes_sent); if (bytes_sent > 0) buffer_pos -= bytes_sent; } usleep(delay); } return 0; } ttyplot-1.7.0/ttyplot-ping.png000066400000000000000000000263651465304244200164360ustar00rootroot00000000000000PNG  IHDREx],IDATx1 0۽Aq68Z=3wSUw+޹ +`O P\.sʬ2\ۨ[*@~3J?ks_rQ0Uj2ST L5j䘰5&C ~aN @ W ͳ.'1pK,S<:3EL&+% NNxL,DOCx".`/~ #G@ +^Jo0ENASm0ID(WJ/{s_Rαm?D~]d>g&GC#X1J2>C n*dWԖ㼛9}EH>7PEOC =2 ;8pa[FVƞׯHzCq]7Urr`v_Kt!_9x!A=6NoI*%Eo8m_%vYZѝ_+B#rKB8xـ@ WGVxH}61+S kT8TDWxAb}uKOiC))och{iOp1 _ңYi_O,lQ^'+h}VL֟0}XvH_I %a;2_c+可 ϕ2@]B|Е^B%Eh^|Husyc+eSF[Qx '- V:6DZ4I={7F~ZȂIm3牸GW.q _ G7h'J kɾc~GJR#"p>\լ .>BRTqvMm7֜i5`H8x3;X}?)>^` z[^F0MV%%UDF"I.M-˾j}7%ɝWk$ %IeY~v`JI_awFnAYPكYvdzظ|#{|'Q3f'ơ`בܝi_/D M&>g!^ @ ~K+(Nuԇ2KE-c{U +<{Dk.K^.m{}~?Z{+\Y3C8`Eֹcߒ~`Nl~޵ݢ&`g7tϬ;=PkݕI|@it;@PL`Mnk qhE|x _Q_Q!B0?+G}Ż1PSm7Sɠg[gFX@z@@5q&z# w&B$" tEuY)uT*"ZժU")V@A$ $ƞ Բ7t/~29szJ$w?To@z+^3rml-{$s~؍-iűŎ*ˇ]Gq5:CO{U x~k+_y0;MI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304244200150430ustar00rootroot00000000000000.Dd January 20, 2024 .Dt TTYPLOT 1 .Os .Sh NAME .Nm ttyplot .Nd realtime terminal plotting utility .Sh SYNOPSIS .Nm .Op Ar options .Nm -v .Nm -h .Sh DESCRIPTION .Nm takes data from standard input, most commonly some tool like .Xr ping 1 , .Xr snmpget 1 , .Xr netstat 8 , .Xr ifconfig 8 , .Xr sar 1 , .Xr vmstat 8 , etc., and plots in text mode on a terminal in real time. .Pp Supports rate calculation for counters and up to two graphs on a single display using reverse video for second line. .Pp The following options are supported: .Bl -tag -width Ds .It Fl 2 Read two values and draw two plots, the second in reverse video. .It Fl r Calculate counter rate and divide by measured sample interval. .It Fl c Ar plotchar Use .Ar plotchar for the plot line, e.g. .Ql @ # % \&. etc. .It Fl e Ar errcharmax Use .Ar errcharmax for plot error line when value exceeds hardmax. Default: .Ql e . .It Fl E Ar errcharmin Use .Ar errcharmin for plot error symbol, displayed when plot value is less than hardmin. Default: .Ql v . .It Fl s Ar softmax Use .Ar softmax as the initial maximum value but allow it to grow with input. .It Fl m Ar hardmax Use .Ar hardmax as a hard value limit after which an error line will be drawn .Po see .Fl e .Pc . Should be greater than hardmin, if set. .It Fl M Ar hardmin Use .Ar hardmin as a definite minimum limit of the plot range. If a plot value is less than this, error symbol will be drawn .Po see .Fl E .Pc . .It Fl t Ar title Use .Ar title as the plot title. .It Fl u Ar unit Label the vertical axis .Ar unit . .It Fl v Print the current version and exit. .It Fl h Print this help message and exit. .El .Sh KEY BINDINGS When reading data from a pipe, .Nm accepts the following commands typed at the terminal: .Bl -tag -width Ds .It Ic q Quit. .It Ic r Toggle "rate mode" on and off. .Sh EXAMPLES CPU usage from .Xr vmstat 8 using .Xr awk 1 to pick the right column: .Bd -literal -offset indent vmstat -n 1 \\ | gawk '{ print 100-int($(NF-2)); fflush(); }' \\ | ttyplot .Ed .Pp CPU usage from .Xr sar 1 with title and fixed scale to 100%: .Bd -literal -offset indent sar 1 \\ | gawk '{ print 100-int($NF); fflush(); }' \\ | ttyplot -s 100 -t "cpu usage" -u "%" .Ed .Pp Memory usage from .Xr sar 1 , using .Xr perl 1 , to pick the right column: .Bd -literal -offset indent sar -r 1 \\ | perl -lane 'BEGIN{$|=1} print "@F[5]"' \\ | ttyplot -s 100 -t "memory used %" -u "%" .Ed .Pp Number of processes in running and io blocked state: .Bd -literal -offset indent vmstat -n 1 \\ | perl -lane 'BEGIN{$|=1} print "@F[0,1]"' \\ | ttyplot -2 -t "procs in R and D state" .Ed .Pp Load average via .Xr uptime 1 and .Xr awk 1 : .Bd -literal -offset indent { while true; do uptime | gawk '{ gsub(/,/, ""); print $(NF-2) }' sleep 1 done } | ttyplot -t "load average" -s load .Ed .Pp Ping plot with .Xr sed 1 : .Bd -literal -offset indent ping 8.8.8.8 \\ | sed -u 's/^.*time=//g; s/ ms//g' \\ | ttyplot -t "ping to 8.8.8.8" -u ms .Ed .Pp WiFi signal level in -dBM (higher is worse) using .Xr iwconfig 8 : .Bd -literal -offset indent { while true; do iwconfig 2>/dev/null \\ | grep "Signal level" \\ | sed -u 's/^.*Signal level=-//g; s/dBm//g' sleep 1 done } | ttyplot -t "wifi signal" -u "-dBm" -s 90 .Ed .Pp CPU temperature from proc; .Bd -literal -offset indent { while true; do awk '{ printf("%.1f\n", $1/1000) }' \\ /sys/class/thermal/thermal_zone0/temp sleep 1 done } | ttyplot -t "cpu temp" -u C .Ed .Pp Fan speed from .Xr sensors 1 using .Xr grep 1 , .Xr tr 1 and .Xr cut 1 : .Bd -literal -offset indent { while true; do sensors | grep fan1: | tr -s " " | cut -d" " -f2 sleep 1 done } | ttyplot -t "fan speed" -u RPM .Ed .Pp Bitcoin price chart using .Xr curl 1 and .Xr jq 1 : .Bd -literal -offset indent { while true; do curl -sL https://api.coindesk.com/v1/bpi/currentprice.json \\ | jq .bpi.USD.rate_float sleep 600 done } | ttyplot -t "bitcoin price" -u usd .Ed .Pp Stock quote chart: .Bd -literal -offset indent { while true; do curl -sL https://api.iextrading.com/1.0/stock/googl/price echo sleep 600 done } | ttyplot -t "google stock price" -u usd .Ed .Pp Prometheus load average via .Ic node_exporter : .Bd -literal -offset indent { while true; do curl -s http://10.4.7.180:9100/metrics \\ | grep "^node_load1 " \\ | cut -d" " -f2; sleep 1 done } | ttyplot .Ed .Ss Network/disk throughput examples .Nm supports two-line plots for in/out or read/write. .Pp Local network throughput for all interfaces combined from .Xr sar 1 : .Bd -literal -offset indent sar -n DEV 1 | gawk '{ if($6 ~ /rxkB/) { print iin/1000; print out/1000; iin=0; out=0; fflush(); } iin=iin+$6; out=out+$7; }' | ttyplot -2 -u "MB/s" .Ed .Pp SNMP network throughput for an interface using .Ql ttg : .Bd -literal -offset indent ttg -i 10 -u Mb 10.23.73.254 public 9 \\ | gawk '{ print $5,$8; fflush(); }' \\ | ttyplot -2 -u Mb/s .Ed .Pp SNMP network throughput for an interface using .Xr snmpdelta 1 : .Bd -literal -offset indent snmpdelta -v 2c -c public -Cp 10 \\ 10.23.73.254 1.3.6.1.2.1.2.2.1.{10,16}.9 \\ | gawk '{ print $NF/1000/1000/10; fflush(); }' \\ | ttyplot -2 -t "interface 9 throughput" -u Mb/s .Ed .Pp Disk throughput from .Xr iostat 1 : .Bd -literal -offset indent iostat -xmy 1 nvme0n1 \\ | stdbuf -o0 tr -s " " \\ | stdbuf -o0 cut -d " " -f 4,5 \\ | ttyplot -2 -t "nvme0n1 throughput" -u MB/s .Ed .Ss Rate calculator for counters .Nm also supports counter style metrics, calculating a rate by measuring time difference between samples. .Pp SNMP network throughput for an interface using .Xr snmpget 1 : .Bd -literal -offset indent { while true; do snmpget -v 2c -c public \\ 10.23.73.254 1.3.6.1.2.1.2.2.1.{10,16}.9 \\ | awk '{ print $NF/1000/1000; }' sleep 10 done } | ttyplot -2 -r -u "MB/s" .Ed .Pp Local interface throughput using .Xr ip 8 and .Xr jq 1 : .Bd -literal -offset indent { while true; do ip -s -j link show enp0s31f6 \\ | jq '.[].stats64.rx.bytes/1024/1024, \\ .[].stats64.tx.bytes/1024/1024' sleep 1 done } | ttyplot -r -2 -u "MB/s" .Ed .Pp Prometheus node exporter disk throughput for .Pa /dev/sda : .Bd -literal -offset indent { while true; do curl -s http://10.11.0.173:9100/metrics \\ | awk '/^node_disk_.+_bytes_total{device="sda"}/ { printf("%f\n", $2/1024/1024); }' sleep 1 done } | ttyplot -r -2 -u MB/s -t "10.11.0.173 sda writes" .Ed .Sh AUTHORS .Nm is written by: .br .An Antoni Sawicki Aq Mt tenox@google.com , .An Edgar Bonet Aq Mt linux@edgar-bonet.org and .An Sebastian Pipping Aq Mt sebastian@pipping.org . .Pp Its readme was converted into this manual page by .An Sijmen J. Mulder Aq Mt ik@sjmulder.nl . .Sh BUGS By default in standard in- and output are is buffered. This can be worked around in various .Lk http://www.perkin.org.uk/posts/how-to-fix-stdio-buffering.html ways . .Pp .Nm quits and erases the screen when there is no more data. This is by design and can be worked around by adding .Xr sleep 1 or .Xr read 1 , for example: .Pp .Dl { echo "1 2 3"; sleep 1000; } | ttyplot .Pp When running interactively and non-numeric data is entered .Pq e.g. some key .Nm hangs. Press .Ql Ctrl^J to reset. ttyplot-1.7.0/ttyplot.c000066400000000000000000000575611465304244200151430ustar00rootroot00000000000000// // ttyplot: a realtime plotting utility for terminal with data input from stdin // Copyright (c) 2018-2024 by Antoni Sawicki // Copyright (c) 2019-2023 by Google LLC // Copyright (c) 2023-2024 by Edgar Bonet // Copyright (c) 2023-2024 by Sebastian Pipping // Apache License 2.0 // // This is needed on macOS to get the ncurses widechar API, and pkg-config fails to // define it. #ifdef __APPLE__ #define _XOPEN_SOURCE_EXTENDED #else // This is needed for musl libc #if ! defined(_XOPEN_SOURCE) || (_XOPEN_SOURCE < 500) #undef _XOPEN_SOURCE // to address warnings about potential re-definition #define _XOPEN_SOURCE 500 #endif #endif #include #include // isspace #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __OpenBSD__ #include #endif #define STR_(x) #x #define STR(x) STR_(x) #define VERSION_MAJOR 1 #define VERSION_MINOR 7 #define VERSION_PATCH 0 #define VERSION_STR STR(VERSION_MAJOR) "." STR(VERSION_MINOR) "." STR(VERSION_PATCH) #define T_RARR '>' #define T_UARR '^' #ifdef NOACS #define T_HLINE '-' #define T_VLINE '|' #define T_LLCR 'L' #else #define T_HLINE ACS_HLINE #define T_VLINE ACS_VLINE #define T_LLCR ACS_LLCORNER #endif enum Event { // These are made to have no set bits overlap to ease flag set testing EVENT_TIMEOUT = 1 << 0, EVENT_UNKNOWN = 1 << 1, EVENT_SIGNAL_READABLE = 1 << 2, EVENT_STDIN_READABLE = 1 << 3, EVENT_TTY_READABLE = 1 << 4, }; static int signal_read_fd, signal_write_fd; static cchar_t plotchar, max_errchar, min_errchar; static struct timeval now; static double td; static double softmax = 0.0, hardmax = FLT_MAX, softmin = 0.0, hardmin = -FLT_MAX; static char title[256] = ".: ttyplot :.", unit[64] = {0}, ls[256] = {0}; static double values1[1024] = {0}, values2[1024] = {0}; static int width = 0, height = 0, n = -1, v = 0, c = 0, rate = 0, two = 0, plotwidth = 0, plotheight = 0; static bool fake_clock = false; static char *errstr = NULL; static bool redraw_needed = false; static int plot_color = -1; // -1 means no color specified static const char *verstring = "https://github.com/tenox7/ttyplot " VERSION_STR; static void usage(void) { printf( "Usage:\n" " ttyplot [-2] [-r] [-c plotchar] [-s scale] [-m max] [-M min] [-t title] [-u " "unit]\n" " ttyplot -h\n" " ttyplot -v\n" "\n" " -2 read two values and draw two plots, the second one is in reverse video\n" " -r rate of a counter (divide value by measured sample interval)\n" " -c character to use for plot line, eg @ # %% . etc\n" " -e character to use for error line when value exceeds hardmax (default: e)\n" " -E character to use for error symbol displayed when value is less than " "hardmin (default: v)\n" " -s initial maximum value (can go above if data input has larger value)\n" " -S initial minimum value (can go below if data input has smaller value)\n" " -m maximum value, if exceeded draws error line (see -e), upper-limit of " "plot scale is fixed\n" " -M minimum value, if entered less than this, draws error symbol (see -E), " "lower-limit of the plot scale is fixed\n" " -t title of the plot\n" " -u unit displayed beside vertical bar\n" " -C color set the color of the plot line (0-7 for basic colors)\n" " -v print the current version and exit\n" " -h print this help message and exit\n" "\n" "Hotkeys:\n" " q quit\n" " r toggle rate mode\n"); } static void version(void) { printf("ttyplot %s\n", VERSION_STR); } // Replace *v1 and *v2 (if non-NULL) by their time derivatives. // - v1, v2: addresses of input data and storage for results // - now: current time // Return time since previous call. static double derivative(double *v1, double *v2, const struct timeval *now) { static double previous_v1, previous_v2, previous_t = DBL_MAX; const double t = now->tv_sec + 1e-6 * now->tv_usec; const double dt = t - previous_t; previous_t = t; if (v1) { const double dv1 = *v1 - previous_v1; previous_v1 = *v1; if (dt <= 0) *v1 = 0; else *v1 = dv1 / dt; } if (v2) { const double dv2 = *v2 - previous_v2; previous_v2 = *v2; if (dt <= 0) *v2 = 0; else *v2 = dv2 / dt; } return dt; } static void getminmax(int pw, double *values, double *min, double *max, double *avg, int v) { double tot = 0; int i = 0; *min = FLT_MAX; *max = -FLT_MAX; for (i = 0; i < pw && i < v; i++) { if (values[i] > *max) *max = values[i]; if (values[i] < *min) *min = values[i]; tot = tot + values[i]; } *avg = tot / i; } static void draw_axes(int h, int ph, int pw, double max, double min, char *unit) { mvhline(h - 3, 2, T_HLINE, pw); mvvline(2, 2, T_VLINE, ph); if (max - min >= 0.1) { mvprintw(1, 4, "%.1f %s", max, unit); mvprintw((ph / 4) + 1, 4, "%.1f %s", min / 4 + max * 3 / 4, unit); mvprintw((ph / 2) + 1, 4, "%.1f %s", min / 2 + max / 2, unit); mvprintw((ph * 3 / 4) + 1, 4, "%.1f %s", min * 3 / 4 + max / 4, unit); } mvaddch(h - 3, 2 + pw, T_RARR); mvaddch(1, 2, T_UARR); mvaddch(h - 3, 2, T_LLCR); } static void draw_line(int x, int ph, int l1, int l2, cchar_t *c1, cchar_t *c2, cchar_t *hce, cchar_t *lce) { static cchar_t space = {.attr = A_REVERSE, .chars = {' ', '\0'}}; cchar_t c1r = *c1, c2r = *c2; c1r.attr |= A_REVERSE; c2r.attr |= A_REVERSE; if (plot_color != -1) { c1->attr |= COLOR_PAIR(1); c2->attr |= COLOR_PAIR(1); c1r.attr |= COLOR_PAIR(1); c2r.attr |= COLOR_PAIR(1); space.attr |= COLOR_PAIR(1); } if (l1 > l2) { mvvline_set(ph + 1 - l1, x, c1, l1 - l2); mvvline_set(ph + 1 - l2, x, &c2r, l2); } else if (l1 < l2) { mvvline_set(ph + 1 - l2, x, (c2 == hce || c2 == lce) ? &c2r : &space, l2 - l1); mvvline_set(ph + 1 - l1, x, &c2r, l1); } else { mvvline_set(ph + 1 - l2, x, &c2r, l2); } if (plot_color != -1) { c1->attr &= ~COLOR_PAIR(1); c2->attr &= ~COLOR_PAIR(1); c1r.attr &= ~COLOR_PAIR(1); c2r.attr &= ~COLOR_PAIR(1); space.attr &= ~COLOR_PAIR(1); } } static void plot_values(int ph, int pw, double *v1, double *v2, double max, double min, int n, cchar_t *pc, cchar_t *hce, cchar_t *lce, double hardmax, double hardmin) { const int first_col = 3; int i = (n + 1) % pw; int x; int l1, l2; if (plot_color != -1) attron(COLOR_PAIR(1)); for (x = first_col; x < first_col + pw; x++, i = (i + 1) % pw) { /* suppress drawing uninitialized entries */ if (! v1 || isnan(v1[i])) continue; if (v1[i] > hardmax) l1 = ph; else if (v1[i] < hardmin) l1 = 1; else l1 = lrint((v1[i] - min) / (max - min) * ph); if (! v2 || isnan(v2[i])) l2 = 0; else if (v2[i] > hardmax) l2 = ph; else if (v2[i] < hardmin) l2 = 1; else l2 = lrint((v2[i] - min) / (max - min) * ph); draw_line(x, ph, l1, l2, (v1[i] > hardmax) ? hce : (v1[i] < hardmin) ? lce : pc, (v2 && v2[i] > hardmax) ? hce : (v2 && v2[i] < hardmin) ? lce : pc, hce, lce); } if (plot_color != -1) attroff(COLOR_PAIR(1)); } static void show_all_centered(const char *message) { const size_t message_len = strlen(message); const int x = ((int)message_len > width) ? 0 : (width / 2 - (int)message_len / 2); const int y = height / 2; mvaddnstr(y, x, message, width); } static int window_big_enough_to_draw(void) { return (width >= 68) && (height >= 5); } static void show_window_size_error(void) { show_all_centered("Window too small..."); } static void paint_plot(void) { double min, max; double min1 = FLT_MAX, max1 = -FLT_MAX, avg1 = 0; double min2 = FLT_MAX, max2 = -FLT_MAX, avg2 = 0; struct tm *lt; erase(); getmaxyx(stdscr, height, width); plotheight = height - 4; plotwidth = width - 4; if (plotwidth >= (int)((sizeof(values1) / sizeof(double)) - 1)) exit(0); getminmax(plotwidth, values1, &min1, &max1, &avg1, v); getminmax(plotwidth, values2, &min2, &max2, &avg2, v); max = max1 > max2 ? max1 : max2; if (max < softmax) max = softmax; if (hardmax != FLT_MAX) max = hardmax; min = min1 < min2 ? min1 : min2; if (min > softmin) min = softmin; if (hardmin != -FLT_MAX) min = hardmin; mvaddstr(height - 1, width - strlen(verstring) - 1, verstring); const char *clock_display; if (fake_clock) { clock_display = "Thu Jan 1 00:00:00 1970 "; } else { lt = localtime(&now.tv_sec); asctime_r(lt, ls); clock_display = ls; } mvaddstr(height - 2, width - strlen(clock_display), clock_display); mvvline_set(height - 2, 5, &plotchar, 1); if (v > 0) { mvprintw(height - 2, 7, "last=%.1f min=%.1f max=%.1f avg=%.1f %s ", values1[n], min1, max1, avg1, unit); if (rate) printw(" interval=%.3gs", td); } if (two) { mvaddch(height - 1, 5, ' ' | A_REVERSE); if (v > 0) { mvprintw(height - 1, 7, "last=%.1f min=%.1f max=%.1f avg=%.1f %s ", values2[n], min2, max2, avg2, unit); } } plot_values(plotheight, plotwidth, values1, two ? values2 : NULL, max, min, n, &plotchar, &max_errchar, &min_errchar, hardmax, hardmin); draw_axes(height, plotheight, plotwidth, max, min, unit); mvaddstr(0, (width / 2) - (strlen(title) / 2), title); move(0, 0); } // Send signals through a pipe, in order to catch them without race conditions. // pselect() could be an alternative, but it is unreliable on Linux. // (Related: https://stackoverflow.com/q/62315082) static void signal_handler(int signum) { const unsigned char signal_number = (unsigned char)signum; // signum is either 2 (SIGINT) or 28 (SIGWINCH) ssize_t write_res; do { write_res = write(signal_write_fd, &signal_number, 1); } while ((write_res == -1) && (errno == EINTR)); } static void redraw_screen(const char *errstr) { if (window_big_enough_to_draw()) { paint_plot(); if (errstr != NULL) { show_all_centered(errstr); } else if (v < 1) { show_all_centered("waiting for data from stdin"); } } else { show_window_size_error(); } refresh(); } // Return a pointer to the last occurrence within [s, s+n) of one of the bytes in the // string accept. static char *find_last(char *s, size_t n, const char *accept) { for (int pos = n - 1; pos >= 0; pos--) { if (strchr(accept, s[pos])) return s + pos; } return NULL; // not found } // Handle a single value from the input stream. // Return whether we got a full data record. static bool handle_value(double value) { static double saved_value; static int saved_value_valid = 0; // First value of a 2-value record: save it for later. if (two && ! saved_value_valid) { saved_value = value; saved_value_valid = 1; return false; } // Otherwise we have a full record. n = (n + 1) % plotwidth; if (two) { values1[n] = saved_value; values2[n] = value; saved_value_valid = 0; } else { values1[n] = value; } if (rate) td = derivative(&values1[n], two ? &values2[n] : NULL, &now); return true; } // Handle a chunk of input data: extract the numbers, store them, redraw if needed. // Return the number of bytes consumed. static size_t handle_input_data(char *buffer, size_t length) { static const char delimiters[] = " \t\r\n"; // white space // Find the last delimiter. char *end = find_last(buffer, length, delimiters); if (! end) return 0; *end = '\0'; // Tokenize and parse. int records = 0; // number or records found char *str = buffer; char *token; while ((token = strtok(str, delimiters)) != NULL) { str = NULL; // tell strtok() to stay on the same string next time char *number_end; double value = strtod(token, &number_end); if (*number_end != '\0') // garbage found continue; if (! isfinite(value)) continue; if (handle_value(value)) records++; } v += records; if (records > 0) redraw_needed = true; return end - buffer + 1; } // Handle an "input ready" event, where only a single read() is guaranteed to not block. // Return whether the input stream got closed. static bool handle_input_event(void) { static char buffer[4096]; static size_t buffer_pos = 0; // Buffer incoming data. ssize_t bytes_read = read(STDIN_FILENO, buffer + buffer_pos, sizeof(buffer) - 1 - buffer_pos); if (bytes_read < 0) { // read error if (errno == EINTR || errno == EAGAIN) // we should try again later return false; errstr = strerror(errno); // other errors are considered fatal redraw_needed = true; // redraw to display the error message return true; } if (bytes_read == 0) { errstr = "input stream closed"; buffer[buffer_pos++] = '\n'; // attempt to extract one last value handle_input_data(buffer, buffer_pos); redraw_needed = true; // redraw to display the error message return true; } // The data we read could contain null bytes, so we replace those // by one of the supported delimiters to not lose all input coming after. for (size_t i = buffer_pos; i < buffer_pos + bytes_read; i++) { if (buffer[i] == '\0') { buffer[i] = ' '; } } buffer_pos += bytes_read; // Handle this new data. size_t bytes_consumed = handle_input_data(buffer, buffer_pos); // If we have excessive garbage, discard a bunch. This is to ensure that we can // always ask read for >= 1K bytes, and keep good performance, especially with high // input pressure. if (buffer_pos - bytes_consumed > sizeof(buffer) / 2) bytes_consumed += sizeof(buffer) / 4; if (bytes_consumed > 0 && bytes_consumed < buffer_pos) memmove(buffer, buffer + bytes_consumed, buffer_pos - bytes_consumed); buffer_pos -= bytes_consumed; return false; } // Refresh the clock on the next full second (plus a few milliseconds). // // We will sleep for a duration of up to a full second here knowing that: // - we are technically putting two redraws apart by more than one second // - that extra is only a few milliseconds (<25 in practice, often <1) // - a few milliseconds is on the edge of what the human eye can notice // - we can save CPU time (and potentially battery life) through giving // up on these milliseconds more in clock refresh delay accuracy. // // We had a constant timeout of 500 milliseconds before (which translates // to twice the frequency of the maximum desired delay: redrawing at least // once per second, the Nyquist frequency at work) but it ran the loop twice // as much (including calling `select` twice as often) as the new approach. // So we decided for lower CPU usage and a timeout of up to a full second. // static struct timeval calculate_clock_refresh_timeout_from(suseconds_t now_tv_usec) { const int microseconds_per_second = 1e6; const int microseconds_remaining = microseconds_per_second - now_tv_usec; return (struct timeval){ .tv_sec = microseconds_remaining / microseconds_per_second, .tv_usec = microseconds_remaining % microseconds_per_second}; } // Block until (a) we receive a signal or (b) stdin can be read without blocking // or (c) timeout expires, in order to reduce use of CPU and power while idle // // Returns one of: // A) EVENT_TIMEOUT // B) EVENT_UNKNOWN // C) One or more of EVENT_*_READABLE or'ed together // static int wait_for_events(int signal_read_fd, int tty, bool stdin_is_open, struct timeval *timeout) { fd_set read_fds; FD_ZERO(&read_fds); FD_SET(signal_read_fd, &read_fds); int select_nfds = signal_read_fd + 1; if (stdin_is_open) { FD_SET(STDIN_FILENO, &read_fds); if (STDIN_FILENO >= select_nfds) select_nfds = STDIN_FILENO + 1; } if (tty != -1) { FD_SET(tty, &read_fds); if (tty >= select_nfds) select_nfds = tty + 1; } const int select_ret = select(select_nfds, &read_fds, NULL, NULL, timeout); if (select_ret == 0) { return EVENT_TIMEOUT; } if (select_ret > 0) { int ret = 0; if (FD_ISSET(signal_read_fd, &read_fds)) { ret |= EVENT_SIGNAL_READABLE; } if ((tty != -1) && FD_ISSET(tty, &read_fds)) { ret |= EVENT_TTY_READABLE; } if (FD_ISSET(STDIN_FILENO, &read_fds)) { ret |= EVENT_STDIN_READABLE; } assert(ret != 0); return ret; } return EVENT_UNKNOWN; } int main(int argc, char *argv[]) { int i; bool stdin_is_open = true; int cached_opterr; const char *optstring = "2rc:e:E:s:S:m:M:t:u:vhC:"; int show_ver; int show_usage; // Initialize values to NAN, rather than 0, so that we know when not to // draw them for (i = 0; i < (int)(sizeof(values1) / sizeof(*values1)); i++) { values1[i] = NAN; values2[i] = NAN; } // To make UI testing more robust, we display a clock that is frozen at // "Thu Jan 1 00:00:03 1970" when variable FAKETIME is set fake_clock = (getenv("FAKETIME") != NULL); setlocale(LC_ALL, ""); if (MB_CUR_MAX > 1) // if non-ASCII characters are supported: plotchar.chars[0] = 0x2502; // U+2502 box drawings light vertical else plotchar.chars[0] = '|'; // U+007C vertical line max_errchar.chars[0] = 'e'; min_errchar.chars[0] = 'v'; cached_opterr = opterr; opterr = 0; show_ver = 0; show_usage = 0; // Run a 1st iteration over the arguments to check for usage, // version or error. while ((c = getopt(argc, argv, optstring)) != -1) { switch (c) { case 'v': show_ver = 1; break; case 'h': show_usage = 1; break; case '?': // Upon error exit immediately. usage(); exit(1); } } if (show_usage) { usage(); exit(0); } if (show_ver) { version(); exit(0); } // Run a 2nd iteration over the arguments to actually process the options. // According to getopt's documentation this is done by setting optind to 1 // (or 0 in some special cases). On BSDs and Macs optreset must be set to 1 // in addition. optind = 1; #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ defined(__DragonFly__) || defined(__APPLE__) optreset = 1; #endif while ((c = getopt(argc, argv, optstring)) != -1) { switch (c) { case 'r': rate = 1; break; case '2': two = 1; break; case 'c': mbtowc(&plotchar.chars[0], optarg, MB_CUR_MAX); break; case 'e': mbtowc(&max_errchar.chars[0], optarg, MB_CUR_MAX); break; case 'E': mbtowc(&min_errchar.chars[0], optarg, MB_CUR_MAX); break; case 'C': plot_color = atoi(optarg); break; case 's': softmax = atof(optarg); break; case 'S': softmin = atof(optarg); break; case 'm': hardmax = atof(optarg); break; case 'M': hardmin = atof(optarg); break; case 't': snprintf(title, sizeof(title), "%s", optarg); break; case 'u': snprintf(unit, sizeof(unit), "%s", optarg); break; } } opterr = cached_opterr; if (softmax <= hardmin) softmax = hardmin + 1; if (hardmax <= hardmin) hardmax = FLT_MAX; initscr(); /* uses filesystem, so before pledge */ #ifdef __OpenBSD__ if (pledge("stdio tty", NULL) == -1) err(1, "pledge"); #endif if (plot_color != -1) { start_color(); use_default_colors(); init_pair(1, plot_color, -1); // -1 for default background } gettimeofday(&now, NULL); noecho(); curs_set(FALSE); erase(); refresh(); getmaxyx(stdscr, height, width); redraw_screen(errstr); // If stdin is redirected, open the terminal for reading user's keystrokes. int tty = -1; if (! isatty(STDIN_FILENO)) tty = open("/dev/tty", O_RDONLY); if (tty != -1) { // Disable input line buffering. The function below works even when stdin // is redirected: it searches for a terminal in stdout and stderr. cbreak(); } int signal_fds[2]; if (pipe(signal_fds) != 0) { perror("pipe"); exit(1); } signal_read_fd = signal_fds[0]; signal_write_fd = signal_fds[1]; signal(SIGWINCH, signal_handler); signal(SIGINT, signal_handler); while (1) { struct timeval timeout = calculate_clock_refresh_timeout_from(now.tv_usec); const int events = wait_for_events(signal_read_fd, tty, stdin_is_open, &timeout); // Refresh the clock if the seconds have changed. const time_t displayed_time = now.tv_sec; gettimeofday(&now, NULL); if (now.tv_sec != displayed_time) redraw_needed = true; // Handle signals. if (events & EVENT_SIGNAL_READABLE) { unsigned char signal_number; const ssize_t count = read(signal_read_fd, &signal_number, 1); if (count > 0) { if (signal_number == SIGINT) break; if (signal_number == SIGWINCH) { endwin(); initscr(); erase(); refresh(); getmaxyx(stdscr, height, width); redraw_needed = true; } } } // Handle user's keystrokes. if (events & EVENT_TTY_READABLE) { char key; int count = read(tty, &key, 1); if (count == 1) { // we did catch a keystroke if (key == 'r') // 'r' = toggle rate mode rate = ! rate; else if (key == 'q') // 'q' = quit break; } else if (count == 0) { close(tty); tty = -1; } } // Handle input data. if (events & EVENT_STDIN_READABLE) { bool input_closed = handle_input_event(); if (input_closed) { close(STDIN_FILENO); stdin_is_open = false; } } // Refresh the screen if needed. if (redraw_needed) { redraw_screen(errstr); redraw_needed = false; } } endwin(); return 0; }