NCurses簡介 —— 譯文

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 [email protected].

關於 NCURSES 更詳細的歷史,請參閱源碼分佈(文件目錄)中的 NEWS 文件。該文件包由 Thomas Dickey 維護。你能通過 [email protected] 聯繫到他。

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 [email protected]

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章