当前位置: 首页 > 工具软件 > NCurses > 使用案例 >

NCurses简介 —— 译文

符俊材
2023-12-01

1. Introduction

In the olden days of teletype terminals, terminals were away from computers and were connected to them through serial cables. The terminals could be configured by sending a series of bytes. All the capabilities (such as moving the cursor to a new location, erasing part of the screen, scrolling the screen, changing modes etc.) of terminals could be accessed through these series of bytes. These control sequences are usually called escape sequences, because they start with an escape(0x1B) character. Even today, with proper emulation, we can send escape sequences to the emulator and achieve the same effect on a terminal window.

在古老的电传打字机终端时代,终端机(terminals),这个远不如个人计算机的设备需要通过很多电缆连接使用。终端机可以通过发送一些字节序列来进行(信号的)确认。终端机的所有能力(例如移动光标到新的位置,擦掉屏幕的一部分,滚动屏幕,改变模式等)可以通过这些字节序列来表现。这种控制序列(control sequences)通常被称为 ESCAPE序列,因为他们通常都以 ESCPAPE控制字符(0x1B)起头。即使是今天,只要合适的模拟,我们同样可以发送 ESCAPE序列到(终端机)模拟器,并得到和终端机窗口一模一样的结果。

Suppose you wanted to print a line in color. Try typing this on your console.

假设你想打印一行带颜色的字符。在命令行界面试试下面的操作。

echo "^[[0;31;40mIn Color"

The first character is an escape character, which looks like two characters ^ and [. To be able to print it, you have to press CTRL+V and then the ESC key. All the others are normal printable characters. You should be able to see the string “In Color” in red. It stays that way and to revert back to the original mode type this.

第一个字符就是 ESCAPE(控制)字符,它看上去像是由 ^ 和 [ 组成的两个字符。但是实际上,它是通过先敲击 CTRL+V,再敲击 ESC 键打印出来的。剩下的所有字符都是普通的可打印字符(可打印字符区别于控制字符,是直接在键盘上敲什么就会在命令行窗口显示什么的字符)。你应该能看到红色的 “In Color” 字符串。这就表示,(你的命令行窗口)依然支持原始的打印方式,让你可以回味那逝去的时光。

echo "^[[0;37;40m"

Now, what do these magic characters mean? Difficult to comprehend? They might even be different for different terminals. So the designers of UNIX invented a mechanism named termcap. It is a file that lists all the capabilities of a particular terminal, along with the escape sequences needed to achieve a particular effect. In the later years, this was replaced by terminfo. Without delving too much into details, this mechanism allows application programs to query the terminfo database and obtain the control characters to be sent to a terminal or terminal emulator.

现在,这坨神秘字符串啥意思?是不是很难理解?它可能在不同的终端机上有不同的意义。所以,UNIX的设计师们发明了一个名叫 termcap 的机制(项目)。它是个文件,列出了指定的终端机的所有功能,包括如何使用 ESCAPE序列 实现指定的效果。在后面的几年,它被新的项目 terminfo 代替了。根据不太深入的研究,这个(新)机制允许应用程序查询 terminfo 数据库,获取控制字符,并发送至终端机或者终端机模拟器。

1.1. What is NCURSES?

You might be wondering, what the import of all this technical gibberish is. In the above scenario, every application program is supposed to query the terminfo and perform the necessary stuff (sending control characters etc.). It soon became difficult to manage this complexity and this gave birth to ‘CURSES’. Curses is a pun on the name “cursor optimization”. The Curses library forms a wrapper over working with raw terminal codes, and provides highly flexible and efficient API (Application Programming Interface). It provides functions to move the cursor, create windows, produce colors, play with mouse etc. The application programs need not worry about the underlying terminal capabilities.

你可能很疑惑:这篇狗屁不通的技术文章,重点是什么?在上面的章节(的结尾处说到),每个应用程序都可以访问 terminfo 并且做出必要的表现(通过发送控制字符的方式等)。很快程序变得复杂且难于管理,CURSES 项目 为此以孕育而生。curses 是个双关语,代表 cursor optimization (光标优化)。curses 库对于原始的终端代码(大概就是控制字符)做了一层包装,提供非常灵活且高效的API。这些函数此次移动光标、创建窗口、指定颜色、玩转鼠标等。应用程序并不需要考虑底层的终端功能如何(像是 termcap 和 terminfo 就需要在编程时对终端机的功能足够了解)。

So what is NCURSES? NCURSES is a clone of the original System V Release 4.0 (SVr4) curses. It is a freely distributable library, fully compatible with older version of curses. In short, it is a library of functions that manages an application’s display on character-cell terminals. In the remainder of the document, the terms curses and ncurses are used interchangeably.

啥又是 NCURSES 呢? NCURSES 就是原生的 System V Release 4.0(SVr4) curses 的一个备份。他是个自由分布的库(共享库),和老版本的 curses 完全兼容。简而言之,这个库包含的函数可以用来处理字符终端。在本文接下来的部分,curses 和 ncurses 这两个专业术语是混用的,代表同一个东西。

A detailed history of NCURSES can be found in the NEWS file from the source distribution. The current package is maintained by Thomas Dickey. You can contact the maintainers at bug-ncurses@gnu.org.

关于 NCURSES 更详细的历史,请参阅源码分布(文件目录)中的 NEWS 文件。该文件包由 Thomas Dickey 维护。你能通过 bug-ncurses@gnu.org 联系到他。

1.2. What we can do with NCURSES

NCURSES not only creates a wrapper over terminal capabilities, but also gives a robust framework to create nice looking UI (User Interface)s in text mode. It provides functions to create windows etc. Its sister libraries panel, menu and form provide an extension to the basic curses library. These libraries usually come along with curses. One can create applications that contain multiple windows, menus, panels and forms. Windows can be managed independently, can provide ‘scrollability’ and even can be hidden.

NCURSES 不仅将终端的功能包装起来,而且提供一个健壮的架构来使用文本模式创建好看的 UI。它提供函数创建窗口等等。它的姐妹库 panel menu 以及 form 扩展了基本的 curses 库。这些库通常和 curses 一起存在。这样创建的应用程序就能包含复合窗口、菜单、面板和表格。窗口都能被独立管理,而且提供 ‘滚动性’,甚至可以被隐藏。

Menus provide the user with an easy command selection option. Forms allow the creation of easy-to-use data entry and display windows. Panels extend the capabilities of ncurses to deal with overlapping and stacked windows.

菜单为用户提供建议的选项命令。表格提供方便的输入输入和展示。面板扩展了 ncurses 处理窗口的层叠关系、栈结构的功能。

These are just some of the basic things we can do with ncurses. As we move along, We will see all the capabilities of these libraries.

使用 ncurses 我们智能做一些基本的事情。在接下来的内容中。我们会逐渐看到这些库的所有功能。

1.3. Where to get it

All right, now that you know what you can do with ncurses, you must be rearing to get started. NCURSES is usually shipped with your installation. In case you don’t have the library or want to compile it on your own, read on.

好的,现在里知道 ncurses 可以用来干嘛了,那你肯定已经跃跃欲试了。 NCURSES 通常会包含在你的(操作系统)安装程序中。假如你确实没有这个库,或者想自己编译,请继续读下去。

Compiling the package

NCURSES can be obtained from ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz or any of the ftp sites mentioned in http://www.gnu.org/order/ftp.html.

NCURSES 可以从 ftp://ftp.gnu.org/gnu/ncurses 获取,或者在 http://www.gnu.org/order/ftp.html 提到的任何一个 FTP 网站。

Read the README and INSTALL files for details on to how to install it. It usually involves the following operations.

阅读 README 和 INSTALL 文件来获取安装的详细信息。通常会推荐你进行下面的操作。

    tar zxvf ncurses<version>.tar.gz  # unzip and untar the archive
    cd ncurses<version>               # cd to the directory
    ./configure                             # configure the build according to your 
                                            # environment
    make                                    # make it
    su root                                 # become root
    make install                            # install it

Using the RPM

NCURSES RPM can be found and downloaded from http://rpmfind.net . The RPM can be installed with the following command after becoming root.

NCURSES RPM 能从 http://rpmfind.net 找到并下载。 RPM 安装包可以通过下面的命令进行安装,并且需要重启。

    rpm -i <downloaded rpm>

1.4. Purpose/Scope of the document

This document is intended to be a “All in One” guide for programming with ncurses and its sister libraries. We graduate from a simple “Hello World” program to more complex form manipulation. No prior experience in ncurses is assumed. The writing is informal, but a lot of detail is provided for each of the examples.

本教程偏向于成为“大一统”的编程指南,用于指导使用 ncurses 以及其他姐妹库。我们从一个简单的 “Hello World” 程序开始,并慢慢接触到复杂的骚操作。我们假设(每个读者)之前没有任何 ncurses 的使用经验。文风虽然比较非正式,但是会讨论每个例子的很多细节。

1.5. About the Programs

All the programs in the document are available in zipped form here. Unzip and untar it. The directory structure looks like this.

教程中所有的程序源码放到 zip 文件中,可以通过 here 获得。解压并解包,目录结构将看上去是这样。

ncurses
   |
   |----> JustForFun     -- just for fun programs
   |----> basics         -- basic programs
   |----> demo           -- output files go into this directory after make
   |          |
   |          |----> exe -- exe files of all example programs
   |----> forms          -- programs related to form library
   |----> menus          -- programs related to menus library
   |----> panels         -- programs related to panels library
   |----> perl           -- perl equivalents of the examples (contributed
   |                            by Anuradha Ratnaweera)
   |----> Makefile       -- the top level Makefile
   |----> README         -- the top level README file. contains instructions
   |----> COPYING        -- copyright notice
The individual directories contain the following files.

Description of files in each directory

每个目录中的文件解释如下

--------------------------------------
JustForFun
    |
    |----> hanoi.c   -- The Towers of Hanoi Solver
    |----> life.c    -- The Game of Life demo
    |----> magic.c   -- An Odd Order Magic Square builder 
    |----> queens.c  -- The famous N-Queens Solver
    |----> shuffle.c -- A fun game, if you have time to kill
    |----> tt.c      -- A very trivial typing tutor

  basics
    |
    |----> acs_vars.c            -- ACS_ variables example
    |----> hello_world.c         -- Simple "Hello World" Program
    |----> init_func_example.c   -- Initialization functions example
    |----> key_code.c            -- Shows the scan code of the key pressed
    |----> mouse_menu.c          -- A menu accessible by mouse
    |----> other_border.c        -- Shows usage of other border functions apa
    |                               -- rt from box()
    |----> printw_example.c      -- A very simple printw() example
    |----> scanw_example.c       -- A very simple getstr() example
    |----> simple_attr.c         -- A program that can print a c file with 
    |                               -- comments in attribute
    |----> simple_color.c        -- A simple example demonstrating colors
    |----> simple_key.c          -- A menu accessible with keyboard UP, DOWN 
    |                               -- arrows
    |----> temp_leave.c          -- Demonstrates temporarily leaving curses mode
    |----> win_border.c          -- Shows Creation of windows and borders
    |----> with_chgat.c          -- chgat() usage example

  forms 
    |
    |----> form_attrib.c     -- Usage of field attributes
    |----> form_options.c    -- Usage of field options
    |----> form_simple.c     -- A simple form example
    |----> form_win.c        -- Demo of windows associated with forms

  menus 
    |
    |----> menu_attrib.c     -- Usage of menu attributes
    |----> menu_item_data.c  -- Usage of item_name() etc.. functions
    |----> menu_multi_column.c    -- Creates multi columnar menus
    |----> menu_scroll.c     -- Demonstrates scrolling capability of menus
    |----> menu_simple.c     -- A simple menu accessed by arrow keys
    |----> menu_toggle.c     -- Creates multi valued menus and explains
    |                           -- REQ_TOGGLE_ITEM
    |----> menu_userptr.c    -- Usage of user pointer
    |----> menu_win.c        -- Demo of windows associated with menus

  panels 
    |
    |----> panel_browse.c    -- Panel browsing through tab. Usage of user 
    |                           -- pointer
    |----> panel_hide.c      -- Hiding and Un hiding of panels
    |----> panel_resize.c    -- Moving and resizing of panels
    |----> panel_simple.c    -- A simple panel example

  perl
    |----> 01-10.pl          -- Perl equivalents of first ten example programs

There is a top level Makefile included in the main directory. It builds all the files and puts the ready-to-use exes in demo/exe directory. You can also do selective make by going into the corresponding directory. Each directory contains a README file explaining the purpose of each c file in the directory.

顶层目录就有个 Makefile 文件。它会构建所有的文件,并且将现成的(ready-to-use)可执行文件(这里的 exe 指的还是 Linux 的 ELF,不是 Windows 的概念。curses/ncurses 仅支持 Linux 下编译使用)放到 demo/exe 子目录。当然你可以对单个目录执行 make 命令。每个目录都包含 README 文件来解释这个目录下 C 文件想要实现的功能。

For every example, I have included path name for the file relative to the examples directory.

对于每个示例,我都建立好了示例目录和它用到的头文件(ncurses库)的映射关系(例如 forms 示例目录下的 C 文件都会 #include <form.h>)。

If you prefer browsing individual programs, point your browser to http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/

如果你想(在线)浏览独立的项目(而不想下载),直接将你的浏览器转到 http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/ (目录已丢失,或者未开放权限)。

All the programs are released under the same license that is used by ncurses (MIT-style). This gives you the ability to do pretty much anything other than claiming them as yours. Feel free to use them in your programs as appropriate.

所有的程序遵循的许可证和 ncurses 保持一致(MIT-style)。这让了你拥有足够的权限用来搞事情,除了声明它们是你的(发明)。把它用在你的程序中,去感受自由的感觉吧!

1.6. Other Formats of the document

This howto is also availabe in various other formats on the tldp.org site. Here are the links to other formats of this document.

本篇 HOWTO 教程可以通过多种文件载体获取,他们都放在 tldp.org 网站上。下面是下载链接。

1.6.1. Readily available formats from tldp.org

1.6.2. Building from source

If above links are broken or if you want to experiment with sgml read on.

如果上面的链接失效了,或者你想获取 sgml 格式的教程,请看下方。

    Get both the source and the tar,gzipped programs, available at
        http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
        NCURSES-HOWTO/NCURSES-Programming-HOWTO.sgml
        http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
        NCURSES-HOWTO/ncurses_programs.tar.gz

    Unzip ncurses_programs.tar.gz with
    tar zxvf ncurses_programs.tar.gz

    Use jade to create various formats. For example if you just want to create
    the multiple html files, you would use
        jade -t sgml -i html -d <path to docbook html stylesheet>
        NCURSES-Programming-HOWTO.sgml
    to get pdf, first create a single html file of the HOWTO with 
        jade -t sgml -i html -d <path to docbook html stylesheet> -V nochunks
        NCURSES-Programming-HOWTO.sgml > NCURSES-ONE-BIG-FILE.html
    then use htmldoc to get pdf file with
        htmldoc --size universal -t pdf --firstpage p1 -f <output file name.pdf>
        NCURSES-ONE-BIG-FILE.html
    for ps, you would use
        htmldoc --size universal -t ps --firstpage p1 -f <output file name.ps>
        NCURSES-ONE-BIG-FILE.html

See LDP Author guide for more details. If all else failes, mail me at ppadala@gmail.com

1.7. Credits

I thank Sharath and Emre Akbas for helping me with few sections. The introduction was initially written by sharath. I rewrote it with few excerpts taken from his initial work. Emre helped in writing printw and scanw sections.

我要感谢 Sharath 和 Emre Akbas 在一些章节对我的帮助。最开始 介绍 这一章是 Sharath 写的。我从他的文章节选了一部分来重写。Emre 在 printw 和 scanw 章节提供了帮助。

Perl equivalents of the example programs are contributed by Anuradha Ratnaweera.

Perl 相关的示例程序是由 Anuradha Ratnaweera 贡献的。

Then comes Ravi Parimi, my dearest friend, who has been on this project before even one line was written. He constantly bombarded me with suggestions and patiently reviewed the whole text. He also checked each program on Linux and Solaris.

接着就是 Ravi Parimi,我最亲爱的朋友,他在我们一行代码(或者文字)都没开始写的时候就加入到这个项目了。他一直连珠炮式地向我提供建议,并且非常有耐心地校对所有的文字。他还把每个程序放到了 Linux 和 Solaris 上做测试。

1.8. Wish List

This is the wish list, in the order of priority. If you have a wish or you want to work on completing the wish, mail me.

下面是我的梦想清单,而且排名有先后。如果这其中也有你的梦想,或者你想通过努力来实现梦想,请邮件我。

Add examples to last parts of forms section.

在 forms 章节的最后部分,加上一些示例。

Prepare a Demo showing all the programs and allow the user to browse through description of each program. Let the user compile and see the program in action. A dialog based interface is preferred.

制作一个 Demo 用来展示所有的程序,并且可以让用户自由浏览每个程序的说明。这样就可以让用户(方便地)动起手来编译并欣赏这些程序。最好是一个基于对话框的界面。

Add debug info. _tracef, _tracemouse stuff.

加上调试信息。_tracef(跟踪栈/调用栈),_tracemouse(跟踪鼠标)之类。

Accessing termcap, terminfo using functions provided by ncurses package.

在 ncurses 包中提供了访问 termcap,terminfo 的函数,想介绍一下它们。

Working on two terminals simultaneously.

怎么做到同时在两个终端窗口上工作。

Add more stuff to miscellaneous section.

还有好多奇技淫巧需要做个章节介绍。

1.9. Copyright

Copyright © 2001 by Pradeep Padala.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, distribute with modifications, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization.

个人总结

原文链接

NCURSES-Programming-HOWTO 是一部用来学习ncurses很不错的文档。其中的第一章的介绍很重要——给我ncurses程序的大概轮廓。后续的内容,按键信息的捕获、字符属性设置等等,都是细枝末节的东西了,可以当作查字典的方式学习。

ncurses目前仅支持Unix/Linux平台,为了实现兼容,我还额外了解了支持Windows平台的PDCurses。比较ncurses和PDCurses的demo,可知道前者有form menu panel等额外库的支持,后者是没有的,但是后者能支持更多Windows控制台特有的特性,只是这种支持需要很多静态库做支撑。PDCurses实际上还有两个版本老版本号称功能更强大的新版本对于入门和实用性来说,老版本已经满足我的需要了,唯一需要做的就是给老本写CMakeLists.txt构建VS工程。

了解ncurses的目的是为了做出一个TUI(Text User Interface)向的程序,以至于在我编写仅需要文本界面的程序时,避免去接触所谓的控件的分类、控件的类型,图片资源加载等过于繁琐的内容。ncurses同时也是RogueLike游戏的基础。为此,我融合ECS架构做了个简单的地形编辑器

为了使一份代码跨平台编译,我避免使用 form menu panel,以及Windows平台下的新特性,用有限而简单的方式去创建选择菜单、地形显示、运行时场景更新、操作信息窗口等。

参考资料

https://invisible-island.net/ncurses/man/

https://pdcurses.org/

https://github.com/wmcbrine/PDCurses

 类似资料: