source: mainline/uspace/app/bdsh/cmds/modules/cat/cat.c@ ea15a89a

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since ea15a89a was 07b7c48, checked in by Jiri Svoboda <jiri@…>, 13 years ago

Extend console library API to support different event types.

  • Property mode set to 100644
File size: 9.3 KB
Line 
1/*
2 * Copyright (c) 2008 Tim Post
3 * Copyright (c) 2011, Martin Sucha
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include <stdio.h>
31#include <stdlib.h>
32#include <unistd.h>
33#include <getopt.h>
34#include <str.h>
35#include <fcntl.h>
36#include <io/console.h>
37#include <io/color.h>
38#include <io/style.h>
39#include <io/keycode.h>
40#include <errno.h>
41#include <vfs/vfs.h>
42#include <assert.h>
43
44#include "config.h"
45#include "util.h"
46#include "errors.h"
47#include "entry.h"
48#include "cat.h"
49#include "cmds.h"
50
51static const char *cmdname = "cat";
52#define CAT_VERSION "0.0.1"
53#define CAT_DEFAULT_BUFLEN 1024
54#define CAT_FULL_FILE 0
55
56static const char *hexchars = "0123456789abcdef";
57
58static bool paging_enabled = false;
59static size_t chars_remaining = 0;
60static size_t lines_remaining = 0;
61static sysarg_t console_cols = 0;
62static sysarg_t console_rows = 0;
63static bool should_quit = false;
64static bool dash_represents_stdin = false;
65
66static console_ctrl_t *console = NULL;
67
68static struct option const long_options[] = {
69 { "help", no_argument, 0, 'h' },
70 { "version", no_argument, 0, 'v' },
71 { "head", required_argument, 0, 'H' },
72 { "tail", required_argument, 0, 't' },
73 { "buffer", required_argument, 0, 'b' },
74 { "more", no_argument, 0, 'm' },
75 { "hex", no_argument, 0, 'x' },
76 { "stdin", no_argument, 0, 's' },
77 { 0, 0, 0, 0 }
78};
79
80/* Dispays help for cat in various levels */
81void help_cmd_cat(unsigned int level)
82{
83 if (level == HELP_SHORT) {
84 printf("`%s' shows the contents of files\n", cmdname);
85 } else {
86 help_cmd_cat(HELP_SHORT);
87 printf(
88 "Usage: %s [options] <file1> [file2] [...]\n"
89 "Options:\n"
90 " -h, --help A short option summary\n"
91 " -v, --version Print version information and exit\n"
92 " -H, --head ## Print only the first ## bytes\n"
93 " -t, --tail ## Print only the last ## bytes\n"
94 " -b, --buffer ## Set the read buffer size to ##\n"
95 " -m, --more Pause after each screen full\n"
96 " -x, --hex Print bytes as hex values\n"
97 " -s --stdin Treat `-' in file list as standard input\n"
98 "Currently, %s is under development, some options don't work.\n",
99 cmdname, cmdname);
100 }
101
102 return;
103}
104
105static void waitprompt()
106{
107 console_set_pos(console, 0, console_rows-1);
108 console_set_color(console, COLOR_WHITE, COLOR_BLUE, 0);
109
110 printf("ENTER/SPACE/PAGE DOWN - next page, "
111 "ESC/Q - quit, C - continue unpaged");
112 fflush(stdout);
113
114 console_set_style(console, STYLE_NORMAL);
115}
116
117static void waitkey()
118{
119 cons_event_t ev;
120 kbd_event_t *kev;
121
122 while (true) {
123 if (!console_get_event(console, &ev)) {
124 return;
125 }
126 if (ev.type == CEV_KEY && ev.ev.key.type == KEY_PRESS) {
127 kev = &ev.ev.key;
128
129 if (kev->key == KC_ESCAPE || kev->key == KC_Q) {
130 should_quit = true;
131 return;
132 }
133 if (kev->key == KC_C) {
134 paging_enabled = false;
135 return;
136 }
137 if (kev->key == KC_ENTER || kev->key == KC_SPACE ||
138 kev->key == KC_PAGE_DOWN) {
139 return;
140 }
141 }
142 }
143 assert(false);
144}
145
146static void newpage()
147{
148 console_clear(console);
149 chars_remaining = console_cols;
150 lines_remaining = console_rows - 1;
151}
152
153static void paged_char(wchar_t c)
154{
155 putchar(c);
156 if (paging_enabled) {
157 chars_remaining--;
158 if (c == '\n' || chars_remaining == 0) {
159 chars_remaining = console_cols;
160 lines_remaining--;
161 }
162 if (lines_remaining == 0) {
163 fflush(stdout);
164 waitprompt();
165 waitkey();
166 newpage();
167 }
168 }
169}
170
171static unsigned int cat_file(const char *fname, size_t blen, bool hex,
172 off64_t head, off64_t tail, bool tail_first)
173{
174 int fd, bytes = 0, count = 0, reads = 0;
175 char *buff = NULL;
176 int i;
177 size_t offset = 0, copied_bytes = 0;
178 off64_t file_size = 0, length = 0;
179
180 bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
181
182 if (reading_stdin) {
183 fd = fileno(stdin);
184 /* Allow storing the whole UTF-8 character. */
185 blen = STR_BOUNDS(1);
186 } else
187 fd = open(fname, O_RDONLY);
188
189 if (fd < 0) {
190 printf("Unable to open %s\n", fname);
191 return 1;
192 }
193
194 if (NULL == (buff = (char *) malloc(blen + 1))) {
195 close(fd);
196 printf("Unable to allocate enough memory to read %s\n",
197 fname);
198 return 1;
199 }
200
201 if (tail != CAT_FULL_FILE) {
202 file_size = lseek(fd, 0, SEEK_END);
203 if (head == CAT_FULL_FILE) {
204 head = file_size;
205 length = tail;
206 } else if (tail_first) {
207 length = head;
208 } else {
209 if (tail > head)
210 tail = head;
211 length = tail;
212 }
213
214 if (tail_first) {
215 lseek(fd, (tail >= file_size) ? 0 : (file_size - tail), SEEK_SET);
216 } else {
217 lseek(fd, ((head - tail) >= file_size) ? 0 : (head - tail), SEEK_SET);
218 }
219 } else
220 length = head;
221
222 do {
223 size_t bytes_to_read;
224 if (reading_stdin) {
225 bytes_to_read = 1;
226 } else {
227 if ((length != CAT_FULL_FILE) &&
228 (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
229 bytes_to_read = (size_t) (length - count);
230 } else {
231 bytes_to_read = blen - copied_bytes;
232 }
233 }
234
235 bytes = read(fd, buff + copied_bytes, bytes_to_read);
236 bytes += copied_bytes;
237 copied_bytes = 0;
238
239 if (bytes > 0) {
240 buff[bytes] = '\0';
241 offset = 0;
242 for (i = 0; i < bytes && !should_quit; i++) {
243 if (hex) {
244 paged_char(hexchars[((uint8_t)buff[i])/16]);
245 paged_char(hexchars[((uint8_t)buff[i])%16]);
246 paged_char(((count+i+1) & 0xf) == 0 ? '\n' : ' ');
247 }
248 else {
249 wchar_t c = str_decode(buff, &offset, bytes);
250 if (c == 0) {
251 /* Reached end of string */
252 break;
253 } else if (c == U_SPECIAL && offset + 2 >= (size_t)bytes) {
254 /* If an extended character is cut off due to the size of the buffer,
255 we will copy it over to the next buffer so it can be read correctly. */
256 copied_bytes = bytes - offset + 1;
257 memcpy(buff, buff + offset - 1, copied_bytes);
258 break;
259 }
260 paged_char(c);
261 }
262
263 }
264 count += bytes;
265 reads++;
266 }
267
268 if (reading_stdin)
269 fflush(stdout);
270 } while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
271
272 close(fd);
273 if (bytes == -1) {
274 printf("Error reading %s\n", fname);
275 free(buff);
276 return 1;
277 }
278
279 free(buff);
280
281 return 0;
282}
283
284/* Main entry point for cat, accepts an array of arguments */
285int cmd_cat(char **argv)
286{
287 unsigned int argc, i, ret = 0;
288 size_t buffer = 0;
289 int c, opt_ind;
290 aoff64_t head = CAT_FULL_FILE, tail = CAT_FULL_FILE;
291 bool hex = false;
292 bool more = false;
293 bool tailFirst = false;
294 sysarg_t rows, cols;
295 int rc;
296
297 /*
298 * reset global state
299 * TODO: move to structure?
300 */
301 paging_enabled = false;
302 chars_remaining = 0;
303 lines_remaining = 0;
304 console_cols = 0;
305 console_rows = 0;
306 should_quit = false;
307 console = console_init(stdin, stdout);
308
309 argc = cli_count_args(argv);
310
311 for (c = 0, optind = 0, opt_ind = 0; c != -1;) {
312 c = getopt_long(argc, argv, "xhvmH:t:b:s", long_options, &opt_ind);
313 switch (c) {
314 case 'h':
315 help_cmd_cat(HELP_LONG);
316 return CMD_SUCCESS;
317 case 'v':
318 printf("%s\n", CAT_VERSION);
319 return CMD_SUCCESS;
320 case 'H':
321 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &head) != EOK ) {
322 puts("Invalid head size\n");
323 return CMD_FAILURE;
324 }
325 break;
326 case 't':
327 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &tail) != EOK ) {
328 puts("Invalid tail size\n");
329 return CMD_FAILURE;
330 }
331 if (head == CAT_FULL_FILE)
332 tailFirst = true;
333 break;
334 case 'b':
335 if (!optarg || str_size_t(optarg, NULL, 10, false, &buffer) != EOK ) {
336 puts("Invalid buffer size\n");
337 return CMD_FAILURE;
338 }
339 break;
340 case 'm':
341 more = true;
342 break;
343 case 'x':
344 hex = true;
345 break;
346 case 's':
347 dash_represents_stdin = true;
348 break;
349 }
350 }
351
352 argc -= optind;
353
354 if (argc < 1) {
355 printf("%s - incorrect number of arguments. Try `%s --help'\n",
356 cmdname, cmdname);
357 return CMD_FAILURE;
358 }
359
360 if (buffer < 4)
361 buffer = CAT_DEFAULT_BUFLEN;
362
363 if (more) {
364 rc = console_get_size(console, &cols, &rows);
365 if (rc != EOK) {
366 printf("%s - cannot get console size\n", cmdname);
367 return CMD_FAILURE;
368 }
369 console_cols = cols;
370 console_rows = rows;
371 paging_enabled = true;
372 newpage();
373 }
374
375 for (i = optind; argv[i] != NULL && !should_quit; i++)
376 ret += cat_file(argv[i], buffer, hex, head, tail, tailFirst);
377
378 if (ret)
379 return CMD_FAILURE;
380 else
381 return CMD_SUCCESS;
382}
383
Note: See TracBrowser for help on using the repository browser.