Reader small image

You're reading from  Practical System Programming for Rust Developers

Product typeBook
Published inDec 2020
PublisherPackt
ISBN-139781800560963
Edition1st Edition
Tools
Right arrow
Author (1)
Prabhu Eshwarla
Prabhu Eshwarla
author image
Prabhu Eshwarla

Prabhu Eshwarla has been shipping high-quality, business-critical software to large enterprises and running IT operations for over 25 years. He is also a passionate teacher of complex technologies. Prabhu has worked with Hewlett Packard and has deep experience in software engineering, engineering management, and IT operations. Prabhu is passionate about Rust and blockchain and specializes in distributed systems. He considers coding to be a creative craft, and an excellent tool to create new digital worlds (and experiences) sustained through rigorous software engineering.
Read more about Prabhu Eshwarla

Right arrow

Chapter 7: Implementing Terminal I/O in Rust

In the previous chapter, we looked at how to work with files and directories. We also built a shell command in Rust that generates consolidated source code metrics for Rust source files in a project directory.

In this chapter, we will look at building terminal-based applications in Rust. Terminal applications are an integral part of many software programs, including games, text editors, and terminal emulators. For developing these types of programs, it helps to understand how to build customized terminal interface-based applications. This is the focus of this chapter.

For this chapter, we will review the basics of how terminals work, and then look at how to perform various types of actions on a terminal, such as setting colors and styles, performing cursor operations (such as clearing and positioning), and working with keyboard and mouse inputs.

We will cover the topics in the following order:

  • Introducing terminal I/O fundamentals...

Technical requirements

The Git repo for the code in this chapter can be found at https://github.com/PacktPublishing/Practical-System-Programming-for-Rust-Developers/tree/master/Chapter07/tui.

For those working on the Windows platform, a virtual machine needs to be installed for this chapter, as the third-party crate used for terminal management does not support the Windows platform (at the time of writing this book). It is recommended to install a virtual machine such as VirtualBox or equivalent running Linux for working with the code in this chapter. Instructions to install VirtualBox can be found at https://www.virtualbox.org.

For working with terminals, Rust provides several features to read keypresses and to control standard input and standard output for a process. When a user types characters in the command line, the bytes generated are available to the program when the user presses the Enter key. This is useful for several types of programs. But for some types of programs...

Introducing terminal I/O fundamentals

In this section, we'll cover the key characteristics of terminals, see an overview of the Termion crate, and define the scope of what we will be building in this project.

Let's first look at some fundamentals of terminals.

Characteristics of terminals

Terminals are devices with which users can interact with a computer. Using a terminal, a user can get command-line access to interact with the computer's operating system. A shell typically acts as the controlling program to drive the terminal on one hand and the interface with the operating system on the other hand.

Originally, UNIX systems were accessed using a terminal (also called a console) connected to a serial line. These terminals typically had a 24 x 80 row x column character-based interface, or in some cases, had rudimentary graphics capabilities. In order to perform operations on the terminal, such as clearing the screen or moving the cursor, specific escape sequences...

Working with the terminal UI (size, color, styles) and cursors

In this section, we will build the first iteration of the text viewer. At the end of this section, we will have a program that will accept a filename from the command line, display its contents, and display a header and footer bar. We will use a Termion crate to set the color and style, get the terminal size, position the cursor at specific coordinates, and clear the screen.

The code in this section is organized as follows:

  • Writing data structures and the main() function
  • Initializing the text viewer and getting the terminal size
  • Displaying a document and styling the terminal color, styles, and cursor position
  • Exiting the text viewer

Let's start with data structures and the main() function of the text viewer

Writing data structures and the main() function

In this section, we'll define the data structures needed to represent the text viewer in memory. We'll also write the...

Processing keyboard inputs and scrolling

In the previous section, we built the first iteration of our text viewer terminal-oriented application. We were able to display a file with fewer than 24 lines and see the header and footer bar containing some information. Finally, we were able to exit the program with Ctrl + Q.

In this section, we will add the following features to the text viewer:

  • Provide the ability to display files of any size.
  • Provide the ability for the user to scroll through the document using arrow keys.
  • Add cursor position coordinates to the footer bar.

Let's begin by creating a new version of the code.

Copy the original code to a new file, as shown:

cp src/bin/text-viewer1.rs src/bin/text-viewer2.rs

This section is organized into three parts. First, we'll implement the logic to respond to the following keystrokes from a user: up, down, left, right, and backspace. Next, we'll implement the functionality to update the...

Processing mouse inputs

Like keyboard events, the Termion crate also supports the ability to listen for mouse events, track the mouse cursor location, and react to it in code. Let's see how to do this here.

Create a new source file called mouse-events.rs under src/bin.

Here is the code logic:

  1. Import the needed modules.
  2. Enable mouse support in the terminal.
  3. Clear the screen.
  4. Create an iterator over incoming events.
  5. Listen to mouse presses, release and hold events, and display the mouse cursor location on the terminal screen.

The code is explained in snippets corresponding to each of these points.

Let's first look at module imports:

  1. We're importing the termion crate modules for switching to raw mode, detecting the cursor position, and listening to mouse events:
    use std::io::{self, Write};
    use termion::cursor::{self, DetectCursorPos};
    use termion::event::*;
    use termion::input::{MouseTerminal, TermRead};
    use termion::raw::IntoRawMode...

Summary

In this chapter, we learned the basics of terminal management by writing a mini text viewer. We learned how to use the Termion library to get the terminal size, set the foreground and background colors, and set styles. After this, we learned how to work with cursors on the terminal, including clearing the screen, positioning the cursor at a particular set of coordinates, and keeping track of the current cursor position.

We learned how to listen to user inputs and track the keyboard arrow keys for scrolling operations, including left, right, up, and down. We wrote code to display document contents dynamically as the user scrolls through it, keeping the constraints of the terminal size in mind. As an exercise, you can refine the text viewer, and also add functionality to convert the text viewer into a full-fledged editor.

Learning these features is important to write applications such as terminal-based games, editing and viewing applications and terminal graphical interfaces...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Practical System Programming for Rust Developers
Published in: Dec 2020Publisher: PacktISBN-13: 9781800560963
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Prabhu Eshwarla

Prabhu Eshwarla has been shipping high-quality, business-critical software to large enterprises and running IT operations for over 25 years. He is also a passionate teacher of complex technologies. Prabhu has worked with Hewlett Packard and has deep experience in software engineering, engineering management, and IT operations. Prabhu is passionate about Rust and blockchain and specializes in distributed systems. He considers coding to be a creative craft, and an excellent tool to create new digital worlds (and experiences) sustained through rigorous software engineering.
Read more about Prabhu Eshwarla