]> git.ipfire.org Git - thirdparty/util-linux.git/blob - disk-utils/cfdisk.c
libfdisk: remove dependence on libsmartcols
[thirdparty/util-linux.git] / disk-utils / cfdisk.c
1 /*
2 * cfdisk.c - Display or manipulate a disk partition table.
3 *
4 * Copyright (C) 2014 Karel Zak <kzak@redhat.com>
5 * Copyright (C) 1994 Kevin E. Martin (martin@cs.unc.edu)
6 *
7 * The original cfdisk was inspired by the fdisk program
8 * by A. V. Le Blanc (leblanc@mcc.ac.uk.
9 *
10 * cfdisk is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 */
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <errno.h>
18 #include <signal.h>
19 #include <ctype.h>
20 #include <getopt.h>
21 #include <libsmartcols.h>
22 #include <sys/ioctl.h>
23
24 #ifdef HAVE_SLANG_H
25 # include <slang.h>
26 #elif defined(HAVE_SLANG_SLANG_H)
27 # include <slang/slang.h>
28 #endif
29
30 #ifdef HAVE_SLCURSES_H
31 # include <slcurses.h>
32 #elif defined(HAVE_SLANG_SLCURSES_H)
33 # include <slang/slcurses.h>
34 #elif defined(HAVE_NCURSESW_NCURSES_H) && defined(HAVE_WIDECHAR)
35 # include <ncursesw/ncurses.h>
36 #elif defined(HAVE_NCURSES_H)
37 # include <ncurses.h>
38 #elif defined(HAVE_NCURSES_NCURSES_H)
39 # include <ncurses/ncurses.h>
40 #endif
41
42 #ifdef HAVE_WIDECHAR
43 # include <wctype.h>
44 # include <wchar.h>
45 #endif
46
47 #include "c.h"
48 #include "closestream.h"
49 #include "nls.h"
50 #include "strutils.h"
51 #include "xalloc.h"
52 #include "mbsalign.h"
53 #include "colors.h"
54
55 #include "fdiskP.h"
56
57 #ifdef __GNU__
58 # define DEFAULT_DEVICE "/dev/hd0"
59 # define ALTERNATE_DEVICE "/dev/sd0"
60 #elif defined(__FreeBSD__)
61 # define DEFAULT_DEVICE "/dev/ad0"
62 # define ALTERNATE_DEVICE "/dev/da0"
63 #else
64 # define DEFAULT_DEVICE "/dev/sda"
65 # define ALTERNATE_DEVICE "/dev/hda"
66 #endif
67
68 #define ARROW_CURSOR_STRING ">> "
69 #define ARROW_CURSOR_DUMMY " "
70 #define ARROW_CURSOR_WIDTH (sizeof(ARROW_CURSOR_STRING) - 1)
71
72 #define MENU_PADDING 2
73 #define TABLE_START_LINE 4
74 #define MENU_START_LINE ((size_t) LINES - 5)
75 #define INFO_LINE ((size_t) LINES - 2)
76 #define HINT_LINE ((size_t) LINES - 1)
77
78 #define CFDISK_ERR_ESC 5000
79
80 #ifndef KEY_ESC
81 # define KEY_ESC '\033'
82 #endif
83 #ifndef KEY_DELETE
84 # define KEY_DELETE '\177'
85 #endif
86
87 /* colors */
88 enum {
89 CFDISK_CL_NONE = 0,
90 CFDISK_CL_WARNING,
91 CFDISK_CL_FREESPACE,
92 };
93 static const int color_pairs[][2] = {
94 /* color foreground, background */
95 [CFDISK_CL_WARNING] = { COLOR_RED, -1 },
96 [CFDISK_CL_FREESPACE] = { COLOR_GREEN, -1 }
97 };
98
99 struct cfdisk;
100
101 static struct cfdisk_menuitem *menu_get_menuitem(struct cfdisk *cf, size_t idx);
102 static struct cfdisk_menuitem *menu_get_menuitem_by_key(struct cfdisk *cf, int key, size_t *idx);
103 static struct cfdisk_menu *menu_push(struct cfdisk *cf, struct cfdisk_menuitem *item);
104 static struct cfdisk_menu *menu_pop(struct cfdisk *cf);
105 static void menu_refresh_size(struct cfdisk *cf);
106
107 static int ui_refresh(struct cfdisk *cf);
108 static void ui_warnx(const char *fmt, ...);
109 static void ui_warn(const char *fmt, ...);
110 static void ui_info(const char *fmt, ...);
111 static void ui_draw_menu(struct cfdisk *cf);
112 static int ui_menu_move(struct cfdisk *cf, int key);
113 static void ui_menu_resize(struct cfdisk *cf);
114
115 static int ui_get_size(struct cfdisk *cf, const char *prompt, uintmax_t *res,
116 uintmax_t low, uintmax_t up);
117
118 static int ui_enabled;
119 static int ui_resize;
120
121 /* menu item */
122 struct cfdisk_menuitem {
123 int key; /* keyboard shortcut */
124 const char *name; /* item name */
125 const char *desc; /* item description (hint) */
126 void *userdata;
127 };
128
129 /* menu */
130 struct cfdisk_menu {
131 char *title; /* optional menu title */
132 struct cfdisk_menuitem *items; /* array with menu items */
133 char *ignore;/* string with keys to ignore */
134 size_t width; /* maximal width of the menu item */
135 size_t nitems; /* number of the active menu items */
136 size_t page_sz;/* when menu longer than screen */
137 size_t idx; /* the current menu item */
138 struct cfdisk_menu *prev;
139
140 /* @ignore keys generator */
141 int (*ignore_cb) (struct cfdisk *, char *, size_t);
142
143 unsigned int vertical : 1; /* enable vertical mode */
144 };
145
146 /* main menu */
147 static struct cfdisk_menuitem main_menuitems[] = {
148 { 'b', N_("Bootable"), N_("Toggle bootable flag of the current partition") },
149 { 'd', N_("Delete"), N_("Delete the current partition") },
150 { 'n', N_("New"), N_("Create new partition from free space") },
151 { 'q', N_("Quit"), N_("Quit program without writing partition table") },
152 { 't', N_("Type"), N_("Change the partition type") },
153 { 'h', N_("Help"), N_("Print help screen") },
154 { 's', N_("Sort"), N_("Fix partitions order") },
155 { 'W', N_("Write"), N_("Write partition table to disk (this might destroy data)") },
156 { 0, NULL, NULL }
157 };
158
159 /* top level control struct */
160 struct cfdisk {
161 struct fdisk_context *cxt; /* libfdisk context */
162 struct fdisk_table *table; /* partition table */
163 struct cfdisk_menu *menu; /* the current menu */
164
165 int *cols; /* output columns */
166 size_t ncols; /* number of columns */
167
168 char *linesbuf; /* table as string */
169 size_t linesbufsz; /* size of the tb_buf */
170
171 char **lines; /* array with lines */
172 size_t nlines; /* number of lines */
173 size_t lines_idx; /* current line <0..N>, exclude header */
174 size_t page_sz;
175
176 unsigned int nwrites; /* fdisk_write_disklabel() counter */
177
178 unsigned int wrong_order :1, /* PT not in right order */
179 zero_start :1; /* ignore existing partition table */
180 };
181
182 /* Initialize output columns -- we follow libcfdisk columns (usually specific
183 * to the label type.
184 */
185 static int cols_init(struct cfdisk *cf)
186 {
187 assert(cf);
188
189 free(cf->cols);
190 cf->cols = NULL;
191 cf->ncols = 0;
192
193 return fdisk_get_columns(cf->cxt, 0, &cf->cols, &cf->ncols);
194 }
195
196 static void resize(void)
197 {
198 struct winsize ws;
199
200 if (ioctl(fileno(stdout), TIOCGWINSZ, &ws) != -1
201 && ws.ws_row && ws.ws_col) {
202 LINES = ws.ws_row;
203 COLS = ws.ws_col;
204 #if HAVE_RESIZETERM
205 resizeterm(ws.ws_row, ws.ws_col);
206 #endif
207 clearok(stdscr, TRUE);
208 }
209 touchwin(stdscr);
210
211 DBG(FRONTEND, ul_debug("ui: resize refresh COLS=%d, LINES=%d", COLS, LINES));
212 ui_resize = 0;
213 }
214
215 /* Reads partition in tree-like order from scols
216 */
217 static int partition_from_scols(struct fdisk_table *tb,
218 struct libscols_line *ln)
219 {
220 struct fdisk_partition *pa = scols_line_get_userdata(ln);
221
222 fdisk_table_add_partition(tb, pa);
223 fdisk_unref_partition(pa);
224
225 if (scols_line_has_children(ln)) {
226 struct libscols_line *chln;
227 struct libscols_iter *itr = scols_new_iter(SCOLS_ITER_FORWARD);
228
229 if (!itr)
230 return -EINVAL;
231 while (scols_line_next_child(ln, itr, &chln) == 0)
232 partition_from_scols(tb, chln);
233 scols_free_iter(itr);
234 }
235 return 0;
236 }
237
238 static char *table_to_string(struct cfdisk *cf, struct fdisk_table *tb)
239 {
240 const struct fdisk_column *col;
241 struct fdisk_partition *pa;
242 struct fdisk_label *lb;
243 struct fdisk_iter *itr = NULL;
244 struct libscols_table *table = NULL;
245 struct libscols_iter *s_itr = NULL;
246 char *res = NULL;
247 size_t i;
248 int tree = 0;
249 struct libscols_line *ln, *ln_cont = NULL;
250
251 DBG(FRONTEND, ul_debug("table: convert to string"));
252
253 assert(cf);
254 assert(cf->cxt);
255 assert(cf->cols);
256 assert(tb);
257
258 lb = fdisk_context_get_label(cf->cxt, NULL);
259 assert(lb);
260
261 itr = fdisk_new_iter(FDISK_ITER_FORWARD);
262 if (!itr)
263 goto done;
264
265 /* get container (e.g. extended partition) */
266 while (fdisk_table_next_partition(tb, itr, &pa) == 0) {
267 if (fdisk_partition_is_nested(pa)) {
268 DBG(FRONTEND, ul_debug("table: nested detected, using tree"));
269 tree = SCOLS_FL_TREE;
270 break;
271 }
272 }
273
274 table = scols_new_table();
275 if (!table)
276 goto done;
277 scols_table_enable_maxout(table, 1);
278
279 /* headers */
280 for (i = 0; i < cf->ncols; i++) {
281 col = fdisk_label_get_column(lb, cf->cols[i]);
282 if (col) {
283 int fl = 0;
284
285 if (fdisk_column_is_number(col))
286 fl |= SCOLS_FL_RIGHT;
287 if (fdisk_column_get_id(col) == FDISK_COL_TYPE)
288 fl |= SCOLS_FL_TRUNC;
289 if (tree && fdisk_column_get_id(col) == FDISK_COL_DEVICE)
290 fl |= SCOLS_FL_TREE;
291
292 if (!scols_table_new_column(table,
293 fdisk_column_get_name(col),
294 fdisk_column_get_width(col), fl))
295 goto done;
296 }
297 }
298
299 /* data */
300 fdisk_reset_iter(itr, FDISK_ITER_FORWARD);
301
302 while (fdisk_table_next_partition(tb, itr, &pa) == 0) {
303 struct libscols_line *parent = fdisk_partition_is_nested(pa) ? ln_cont : NULL;
304
305 ln = scols_table_new_line(table, parent);
306 if (!ln)
307 goto done;
308 for (i = 0; i < cf->ncols; i++) {
309 char *cdata = NULL;
310 col = fdisk_label_get_column(lb, cf->cols[i]);
311 if (!col)
312 continue;
313 if (fdisk_partition_to_string(pa, cf->cxt,
314 fdisk_column_get_id(col), &cdata))
315 continue;
316 scols_line_refer_data(ln, i, cdata);
317 }
318 if (tree && fdisk_partition_is_container(pa))
319 ln_cont = ln;
320
321 scols_line_set_userdata(ln, (void *) pa);
322 fdisk_ref_partition(pa);
323 }
324
325 if (scols_table_is_empty(table))
326 goto done;
327
328 scols_table_reduce_termwidth(table, ARROW_CURSOR_WIDTH);
329 scols_print_table_to_string(table, &res);
330
331 /* scols_* code might reorder lines, let's reorder @tb according to the
332 * final output (it's no problem because partitions are addressed by
333 * parno stored within struct fdisk_partition) */
334
335 /* remove all */
336 fdisk_reset_iter(itr, FDISK_ITER_FORWARD);
337 while (fdisk_table_next_partition(tb, itr, &pa) == 0)
338 fdisk_table_remove_partition(tb, pa);
339
340 s_itr = scols_new_iter(SCOLS_ITER_FORWARD);
341 if (!s_itr)
342 goto done;
343
344 /* add all in the right order (don't forget the output is tree) */
345 while (scols_table_next_line(table, s_itr, &ln) == 0) {
346 if (scols_line_get_parent(ln))
347 continue;
348 if (partition_from_scols(tb, ln))
349 break;
350 }
351 done:
352 scols_unref_table(table);
353 scols_free_iter(s_itr);
354 fdisk_free_iter(itr);
355
356 return res;
357 }
358
359 /*
360 * Read data about partitions from libfdisk and prepare output lines.
361 */
362 static int lines_refresh(struct cfdisk *cf)
363 {
364 int rc;
365 char *p;
366 size_t i;
367
368 assert(cf);
369
370 DBG(FRONTEND, ul_debug("refreshing buffer"));
371
372 free(cf->linesbuf);
373 free(cf->lines);
374 cf->linesbuf = NULL;
375 cf->linesbufsz = 0;
376 cf->lines = NULL;
377 cf->nlines = 0;
378
379 fdisk_unref_table(cf->table);
380 cf->table = NULL;
381
382 /* read partitions and free spaces into cf->table */
383 rc = fdisk_get_partitions(cf->cxt, &cf->table);
384 if (!rc)
385 rc = fdisk_get_freespaces(cf->cxt, &cf->table);
386 if (rc)
387 return rc;
388
389 cf->linesbuf = table_to_string(cf, cf->table);
390 if (!cf->linesbuf)
391 return -ENOMEM;
392
393 cf->linesbufsz = strlen(cf->linesbuf);
394 cf->nlines = fdisk_table_get_nents(cf->table) + 1; /* 1 for header line */
395 cf->page_sz = 0;
396 cf->wrong_order = fdisk_table_wrong_order(cf->table) ? 1 : 0;
397
398 if (MENU_START_LINE - TABLE_START_LINE < cf->nlines)
399 cf->page_sz = MENU_START_LINE - TABLE_START_LINE - 1;
400
401 cf->lines = xcalloc(cf->nlines, sizeof(char *));
402
403 for (p = cf->linesbuf, i = 0; p && i < cf->nlines; i++) {
404 cf->lines[i] = p;
405 p = strchr(p, '\n');
406 if (p) {
407 *p = '\0';
408 p++;
409 }
410 }
411
412 return 0;
413 }
414
415 static struct fdisk_partition *get_current_partition(struct cfdisk *cf)
416 {
417 assert(cf);
418 assert(cf->table);
419
420 return fdisk_table_get_partition(cf->table, cf->lines_idx);
421 }
422
423 static int is_freespace(struct cfdisk *cf, size_t i)
424 {
425 struct fdisk_partition *pa;
426
427 assert(cf);
428 assert(cf->table);
429
430 pa = fdisk_table_get_partition(cf->table, i);
431 return fdisk_partition_is_freespace(pa);
432 }
433
434 /* converts libfdisk FDISK_ASKTYPE_MENU to cfdisk menu and returns user's
435 * responseback to libfdisk
436 */
437 static int ask_menu(struct fdisk_ask *ask, struct cfdisk *cf)
438 {
439 struct cfdisk_menuitem *d, *cm;
440 int key;
441 size_t i = 0, nitems;
442 const char *name, *desc;
443
444 assert(ask);
445 assert(cf);
446
447 /* create cfdisk menu according to libfdisk ask-menu, note that the
448 * last cm[] item has to be empty -- so nitems + 1 */
449 nitems = fdisk_ask_menu_get_nitems(ask);
450 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
451
452 for (i = 0; i < nitems; i++) {
453 if (fdisk_ask_menu_get_item(ask, i, &key, &name, &desc))
454 break;
455 cm[i].key = key;
456 cm[i].desc = desc;
457 cm[i].name = name;
458 }
459
460 /* make the new menu active */
461 menu_push(cf, cm);
462 ui_draw_menu(cf);
463 refresh();
464
465 /* wait for keys */
466 do {
467 int key = getch();
468
469 if (ui_resize)
470 ui_menu_resize(cf);
471 if (ui_menu_move(cf, key) == 0)
472 continue;
473
474 switch (key) {
475 case KEY_ENTER:
476 case '\n':
477 case '\r':
478 d = menu_get_menuitem(cf, cf->menu->idx);
479 if (d)
480 fdisk_ask_menu_set_result(ask, d->key);
481 menu_pop(cf);
482 free(cm);
483 return 0;
484 }
485 } while (1);
486
487 menu_pop(cf);
488 free(cm);
489 return -1;
490 }
491
492 /* libfdisk callback
493 */
494 static int ask_callback(struct fdisk_context *cxt, struct fdisk_ask *ask,
495 void *data __attribute__((__unused__)))
496 {
497 int rc = 0;
498
499 assert(cxt);
500 assert(ask);
501
502 switch(fdisk_ask_get_type(ask)) {
503 case FDISK_ASKTYPE_INFO:
504 ui_info(fdisk_ask_print_get_mesg(ask));
505 break;
506 case FDISK_ASKTYPE_WARNX:
507 ui_warnx(fdisk_ask_print_get_mesg(ask));
508 break;
509 case FDISK_ASKTYPE_WARN:
510 ui_warn(fdisk_ask_print_get_mesg(ask));
511 break;
512 case FDISK_ASKTYPE_MENU:
513 ask_menu(ask, (struct cfdisk *) data);
514 break;
515 default:
516 ui_warnx(_("internal error: unsupported dialog type %d"),
517 fdisk_ask_get_type(ask));
518 return -EINVAL;
519 }
520 return rc;
521 }
522
523 static int ui_end(void)
524 {
525 if (!ui_enabled)
526 return -EINVAL;
527
528 #if defined(HAVE_SLCURSES_H) || defined(HAVE_SLANG_SLCURSES_H)
529 SLsmg_gotorc(LINES - 1, 0);
530 SLsmg_refresh();
531 #else
532 mvcur(0, COLS - 1, LINES-1, 0);
533 #endif
534 curs_set(1);
535 nl();
536 endwin();
537 printf("\n");
538 ui_enabled = 0;
539 return 0;
540 }
541
542 static void ui_vprint_center(int line, int attrs, const char *fmt, va_list ap)
543 {
544 size_t width;
545 char *buf = NULL;
546
547 move(line, 0);
548 clrtoeol();
549
550 xvasprintf(&buf, fmt, ap);
551
552 width = mbs_safe_width(buf);
553 if (width > (size_t) COLS) {
554 char *p = strrchr(buf + COLS, ' ');
555 if (!p)
556 p = buf + COLS;
557 *p = '\0';
558 if (line + 1 >= LINES)
559 line--;
560 attron(attrs);
561 mvaddstr(line, 0, buf);
562 mvaddstr(line + 1, 0, p+1);
563 attroff(attrs);
564 } else {
565 attron(attrs);
566 mvaddstr(line, (COLS - width) / 2, buf);
567 attroff(attrs);
568 }
569 free(buf);
570 }
571
572 static void ui_center(int line, const char *fmt, ...)
573 {
574 va_list ap;
575 va_start(ap, fmt);
576 ui_vprint_center(line, 0, fmt, ap);
577 va_end(ap);
578 }
579
580 static void ui_warnx(const char *fmt, ...)
581 {
582 va_list ap;
583 va_start(ap, fmt);
584 if (ui_enabled)
585 ui_vprint_center(INFO_LINE,
586 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING) : 0,
587 fmt, ap);
588 else {
589 vfprintf(stderr, fmt, ap);
590 fputc('\n', stderr);
591 }
592 va_end(ap);
593 }
594
595 static void ui_warn(const char *fmt, ...)
596 {
597 char *fmt_m;
598 va_list ap;
599
600 xasprintf(&fmt_m, "%s: %m", fmt);
601
602 va_start(ap, fmt);
603 if (ui_enabled)
604 ui_vprint_center(INFO_LINE,
605 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING) : 0,
606 fmt_m, ap);
607 else {
608 vfprintf(stderr, fmt_m, ap);
609 fputc('\n', stderr);
610 }
611 va_end(ap);
612 free(fmt_m);
613 }
614
615 static int __attribute__((__noreturn__)) ui_errx(int rc, const char *fmt, ...)
616 {
617 va_list ap;
618 ui_end();
619
620 va_start(ap, fmt);
621 fprintf(stderr, "%s: ", program_invocation_short_name);
622 vfprintf(stderr, fmt, ap);
623 fputc('\n', stderr);
624 va_end(ap);
625
626 exit(rc);
627 }
628
629 static void ui_info(const char *fmt, ...)
630 {
631 va_list ap;
632 va_start(ap, fmt);
633 if (ui_enabled)
634 ui_vprint_center(INFO_LINE, A_BOLD, fmt, ap);
635 else {
636 vfprintf(stdout, fmt, ap);
637 fputc('\n', stdout);
638 }
639 va_end(ap);
640 }
641
642 static void ui_clean_info(void)
643 {
644 move(INFO_LINE, 0);
645 clrtoeol();
646 }
647
648 static void ui_hint(const char *fmt, ...)
649 {
650 va_list ap;
651 va_start(ap, fmt);
652 if (ui_enabled)
653 ui_vprint_center(HINT_LINE, A_BOLD, fmt, ap);
654 else {
655 vfprintf(stdout, fmt, ap);
656 fputc('\n', stdout);
657 }
658 va_end(ap);
659 }
660
661 static void ui_clean_hint(void)
662 {
663 move(HINT_LINE, 0);
664 clrtoeol();
665 }
666
667 static void die_on_signal(int dummy __attribute__((__unused__)))
668 {
669 DBG(FRONTEND, ul_debug("die on signal."));
670 ui_end();
671 exit(EXIT_FAILURE);
672 }
673
674 static void resize_on_signal(int dummy __attribute__((__unused__)))
675 {
676 DBG(FRONTEND, ul_debug("resize on signal."));
677 ui_resize = 1;
678 }
679
680 static void menu_refresh_size(struct cfdisk *cf)
681 {
682 if (cf->menu && cf->menu->nitems)
683 cf->menu->page_sz = (cf->menu->nitems / (LINES - 4)) ? LINES - 4 : 0;
684 }
685
686 static void menu_update_ignore(struct cfdisk *cf)
687 {
688 char ignore[128] = { 0 };
689 int i = 0;
690 struct cfdisk_menu *m;
691 struct cfdisk_menuitem *d, *org;
692 size_t idx;
693
694 assert(cf);
695 assert(cf->menu);
696 assert(cf->menu->ignore_cb);
697
698 m = cf->menu;
699 org = menu_get_menuitem(cf, m->idx);
700
701 DBG(FRONTEND, ul_debug("menu: update menu ignored keys"));
702
703 i = m->ignore_cb(cf, ignore, sizeof(ignore));
704 ignore[i] = '\0';
705
706 /* return if no change */
707 if ( (!m->ignore && !*ignore)
708 || (m->ignore && *ignore && strcmp(m->ignore, ignore) == 0)) {
709 return;
710 }
711
712 free(m->ignore);
713 m->ignore = xstrdup(ignore);
714 m->nitems = 0;
715
716 for (d = m->items; d->name; d++) {
717 if (m->ignore && strchr(m->ignore, d->key))
718 continue;
719 m->nitems++;
720 }
721
722 /* refresh menu index to be at the same menuitem or go to the first */
723 if (org && menu_get_menuitem_by_key(cf, org->key, &idx))
724 m->idx = idx;
725 else
726 m->idx = 0;
727
728 menu_refresh_size(cf);
729 }
730
731 static struct cfdisk_menu *menu_push(
732 struct cfdisk *cf,
733 struct cfdisk_menuitem *items)
734 {
735 struct cfdisk_menu *m = xcalloc(1, sizeof(*m));
736 struct cfdisk_menuitem *d;
737
738 assert(cf);
739
740 DBG(FRONTEND, ul_debug("menu: new menu"));
741
742 m->prev = cf->menu;
743 m->items = items;
744
745 for (d = m->items; d->name; d++) {
746 const char *name = _(d->name);
747 size_t len = mbs_safe_width(name);
748 if (len > m->width)
749 m->width = len;
750 m->nitems++;
751 }
752
753 cf->menu = m;
754 menu_refresh_size(cf);
755 return m;
756 }
757
758 static struct cfdisk_menu *menu_pop(struct cfdisk *cf)
759 {
760 struct cfdisk_menu *m = NULL;
761
762 assert(cf);
763
764 DBG(FRONTEND, ul_debug("menu: rem menu"));
765
766 if (cf->menu) {
767 m = cf->menu->prev;
768 free(cf->menu->ignore);
769 free(cf->menu->title);
770 free(cf->menu);
771 }
772 cf->menu = m;
773 return cf->menu;
774 }
775
776 static void menu_set_title(struct cfdisk_menu *m, const char *title)
777 {
778 char *str = NULL;
779
780 if (title) {
781 size_t len = mbs_safe_width(title);
782 if (len + 3 > m->width)
783 m->width = len + 3;
784 str = xstrdup(title);
785 }
786 m->title = str;
787 }
788
789
790 static int ui_init(struct cfdisk *cf __attribute__((__unused__)))
791 {
792 struct sigaction sa;
793
794 DBG(FRONTEND, ul_debug("ui: init"));
795
796 /* setup SIGCHLD handler */
797 sigemptyset(&sa.sa_mask);
798 sa.sa_flags = 0;
799 sa.sa_handler = die_on_signal;
800 sigaction(SIGINT, &sa, NULL);
801 sigaction(SIGTERM, &sa, NULL);
802
803 sa.sa_handler = resize_on_signal;
804 sigaction(SIGWINCH, &sa, NULL);
805
806 ui_enabled = 1;
807 initscr();
808
809 #ifdef HAVE_USE_DEFAULT_COLORS
810 if (colors_wanted() && has_colors()) {
811 size_t i;
812
813 start_color();
814 use_default_colors();
815 for (i = 1; i < ARRAY_SIZE(color_pairs); i++) /* yeah, start from 1! */
816 init_pair(i, color_pairs[i][0], color_pairs[i][1]);
817 }
818 #else
819 colors_off();
820 #endif
821
822 cbreak();
823 noecho();
824 nonl();
825 curs_set(0);
826 keypad(stdscr, TRUE);
827
828 return 0;
829 }
830
831 static size_t menuitem_get_line(struct cfdisk *cf, size_t idx)
832 {
833 struct cfdisk_menu *m = cf->menu;
834
835 if (m->vertical) {
836 if (!m->page_sz) /* small menu */
837 return (LINES - (cf->menu->nitems + 1)) / 2 + idx;
838 return (idx % m->page_sz) + 1;
839 } else {
840 size_t len = m->width + 4 + MENU_PADDING; /* item width */
841 size_t items = COLS / len; /* items per line */
842
843 if (items == 0)
844 return 0;
845
846 return MENU_START_LINE + ((idx / items));
847 }
848 }
849
850 static int menuitem_get_column(struct cfdisk *cf, size_t idx)
851 {
852 if (cf->menu->vertical) {
853 size_t nc = cf->menu->width + MENU_PADDING;
854 if ((size_t) COLS <= nc)
855 return 0;
856 return (COLS - nc) / 2;
857 } else {
858 size_t len = cf->menu->width + 4 + MENU_PADDING; /* item width */
859 size_t items = COLS / len; /* items per line */
860 size_t extra = items < cf->menu->nitems ? /* extra space on line */
861 COLS % len : /* - multi-line menu */
862 COLS - (cf->menu->nitems * len); /* - one line menu */
863
864 if (items == 0)
865 return 0; /* hmm... no space */
866
867 extra += MENU_PADDING; /* add padding after last item to extra */
868
869 if (idx < items)
870 return (idx * len) + (extra / 2);
871 return ((idx % items) * len) + (extra / 2);
872 }
873 }
874
875 static int menuitem_on_page(struct cfdisk *cf, size_t idx)
876 {
877 struct cfdisk_menu *m = cf->menu;
878
879 if (m->page_sz == 0 ||
880 m->idx / m->page_sz == idx / m->page_sz)
881 return 1;
882 return 0;
883 }
884
885 static struct cfdisk_menuitem *menu_get_menuitem(struct cfdisk *cf, size_t idx)
886 {
887 struct cfdisk_menuitem *d;
888 size_t i;
889
890 for (i = 0, d = cf->menu->items; d->name; d++) {
891 if (cf->menu->ignore && strchr(cf->menu->ignore, d->key))
892 continue;
893 if (i++ == idx)
894 return d;
895 }
896
897 return NULL;
898 }
899
900 static struct cfdisk_menuitem *menu_get_menuitem_by_key(struct cfdisk *cf,
901 int key, size_t *idx)
902 {
903 struct cfdisk_menuitem *d;
904
905 for (*idx = 0, d = cf->menu->items; d->name; d++) {
906 if (cf->menu->ignore && strchr(cf->menu->ignore, d->key))
907 continue;
908 if (key == d->key)
909 return d;
910 (*idx)++;
911 }
912
913 return NULL;
914 }
915
916 static void ui_draw_menuitem(struct cfdisk *cf,
917 struct cfdisk_menuitem *d,
918 size_t idx)
919 {
920 char buf[80 * MB_CUR_MAX];
921 const char *name;
922 size_t width = cf->menu->width + 2; /* 2 = blank around string */
923 int ln, cl, vert = cf->menu->vertical;
924
925 if (!menuitem_on_page(cf, idx))
926 return; /* no visible item */
927 ln = menuitem_get_line(cf, idx);
928 cl = menuitem_get_column(cf, idx);
929
930 name = _(d->name);
931 mbsalign(name, buf, sizeof(buf), &width,
932 vert ? MBS_ALIGN_LEFT : MBS_ALIGN_CENTER,
933 0);
934
935 DBG(FRONTEND, ul_debug("ui: menuitem: cl=%d, ln=%d, item='%s'",
936 cl, ln, buf));
937
938 if (vert) {
939 mvaddch(ln, cl - 1, ACS_VLINE);
940 mvaddch(ln, cl + cf->menu->width + 4, ACS_VLINE);
941 }
942
943 if (cf->menu->idx == idx) {
944 standout();
945 mvprintw(ln, cl, vert ? " %s " : "[%s]", buf);
946 standend();
947 if (d->desc)
948 ui_hint(d->desc);
949 } else
950 mvprintw(ln, cl, vert ? " %s " : "[%s]", buf);
951 }
952
953 static void ui_clean_menu(struct cfdisk *cf)
954 {
955 size_t i;
956 size_t nlines;
957 struct cfdisk_menu *m = cf->menu;
958 size_t ln = menuitem_get_line(cf, 0);
959
960 if (m->vertical)
961 nlines = m->page_sz ? m->page_sz : m->nitems;
962 else
963 nlines = menuitem_get_line(cf, m->nitems);
964
965 for (i = ln; i <= ln + nlines; i++) {
966 move(i, 0);
967 clrtoeol();
968 }
969 if (m->vertical) {
970 move(ln - 1, 0);
971 clrtoeol();
972 }
973 ui_clean_hint();
974 }
975
976 static void ui_draw_menu(struct cfdisk *cf)
977 {
978 struct cfdisk_menuitem *d;
979 struct cfdisk_menu *m;
980 size_t i = 0;
981 size_t ln = menuitem_get_line(cf, 0);
982 size_t nlines;
983
984 assert(cf);
985 assert(cf->menu);
986
987 DBG(FRONTEND, ul_debug("ui: menu: draw start"));
988
989 ui_clean_menu(cf);
990 m = cf->menu;
991
992 if (m->vertical)
993 nlines = m->page_sz ? m->page_sz : m->nitems;
994 else
995 nlines = menuitem_get_line(cf, m->nitems);
996
997 if (m->ignore_cb)
998 menu_update_ignore(cf);
999 i = 0;
1000 while ((d = menu_get_menuitem(cf, i)))
1001 ui_draw_menuitem(cf, d, i++);
1002
1003 if (m->vertical) {
1004 size_t cl = menuitem_get_column(cf, 0);
1005 size_t curpg = m->page_sz ? m->idx / m->page_sz : 0;
1006
1007 /* corners and horizontal lines */
1008 mvaddch(ln - 1, cl - 1, ACS_ULCORNER);
1009 mvaddch(ln + nlines, cl - 1, ACS_LLCORNER);
1010
1011 for (i = 0; i < m->width + 4; i++) {
1012 mvaddch(ln - 1, cl + i, ACS_HLINE);
1013 mvaddch(ln + nlines, cl + i, ACS_HLINE);
1014 }
1015
1016 mvaddch(ln - 1, cl + i, ACS_URCORNER);
1017 mvaddch(ln + nlines, cl + i, ACS_LRCORNER);
1018
1019 /* draw also lines around empty lines on last page */
1020 if (m->page_sz &&
1021 m->nitems / m->page_sz == m->idx / m->page_sz) {
1022 for (i = m->nitems % m->page_sz + 1; i <= m->page_sz; i++) {
1023 mvaddch(i, cl - 1, ACS_VLINE);
1024 mvaddch(i, cl + cf->menu->width + 4, ACS_VLINE);
1025 }
1026 }
1027 if (m->title) {
1028 attron(A_BOLD);
1029 mvprintw(ln - 1, cl, " %s ", m->title);
1030 attroff(A_BOLD);
1031 }
1032 if (curpg != 0)
1033 mvaddch(ln - 1, cl + m->width + 3, ACS_UARROW);
1034 if (m->page_sz && curpg < m->nitems / m->page_sz)
1035 mvaddch(ln + nlines, cl + m->width + 3, ACS_DARROW);
1036 }
1037
1038 DBG(FRONTEND, ul_debug("ui: menu: draw end."));
1039 }
1040
1041 static void ui_menu_goto(struct cfdisk *cf, int where)
1042 {
1043 struct cfdisk_menuitem *d;
1044 size_t old;
1045
1046 /* stop and begin/end for vertical menus */
1047 if (cf->menu->vertical) {
1048 if (where < 0)
1049 where = 0;
1050 else if (where > (int) cf->menu->nitems - 1)
1051 where = cf->menu->nitems - 1;
1052 } else {
1053 /* continue from begin/end */
1054 if (where < 0)
1055 where = cf->menu->nitems - 1;
1056 else if ((size_t) where > cf->menu->nitems - 1)
1057 where = 0;
1058 }
1059 if ((size_t) where == cf->menu->idx)
1060 return;
1061
1062 ui_clean_info();
1063
1064 old = cf->menu->idx;
1065 cf->menu->idx = where;
1066
1067 if (!menuitem_on_page(cf, old)) {
1068 ui_draw_menu(cf);
1069 return;
1070 }
1071
1072 d = menu_get_menuitem(cf, old);
1073 ui_draw_menuitem(cf, d, old);
1074
1075 d = menu_get_menuitem(cf, where);
1076 ui_draw_menuitem(cf, d, where);
1077 }
1078
1079 static int ui_menu_move(struct cfdisk *cf, int key)
1080 {
1081 struct cfdisk_menu *m;
1082
1083 assert(cf);
1084 assert(cf->menu);
1085
1086 if (key == ERR)
1087 return 0; /* ignore errors */
1088
1089 m = cf->menu;
1090
1091 DBG(FRONTEND, ul_debug("ui: menu move key >%c<.", key));
1092
1093 if (m->vertical)
1094 {
1095 switch (key) {
1096 case KEY_DOWN:
1097 case '\016': /* ^N */
1098 case 'j': /* Vi-like alternative */
1099 ui_menu_goto(cf, m->idx + 1);
1100 return 0;
1101 case KEY_UP:
1102 case '\020': /* ^P */
1103 case 'k': /* Vi-like alternative */
1104 ui_menu_goto(cf, (int) m->idx - 1);
1105 return 0;
1106 case KEY_PPAGE:
1107 if (m->page_sz) {
1108 ui_menu_goto(cf, (int) m->idx - m->page_sz);
1109 return 0;
1110 }
1111 /* fallthrough */
1112 case KEY_HOME:
1113 ui_menu_goto(cf, 0);
1114 return 0;
1115 case KEY_NPAGE:
1116 if (m->page_sz) {
1117 ui_menu_goto(cf, m->idx + m->page_sz);
1118 return 0;
1119 }
1120 /* fallthrough */
1121 case KEY_END:
1122 ui_menu_goto(cf, m->nitems);
1123 return 0;
1124 }
1125 } else {
1126 switch (key) {
1127 case KEY_RIGHT:
1128 case '\t':
1129 ui_menu_goto(cf, m->idx + 1);
1130 return 0;
1131 case KEY_LEFT:
1132 #ifdef KEY_BTAB
1133 case KEY_BTAB:
1134 #endif
1135 ui_menu_goto(cf, (int) m->idx - 1);
1136 return 0;
1137 }
1138 }
1139
1140 return 1; /* key irrelevant for menu move */
1141 }
1142
1143 /* but don't call me from ui_run(), this is for pop-up menus only */
1144 static void ui_menu_resize(struct cfdisk *cf)
1145 {
1146 resize();
1147 ui_clean_menu(cf);
1148 menu_refresh_size(cf);
1149 ui_draw_menu(cf);
1150 refresh();
1151 }
1152
1153 static int partition_on_page(struct cfdisk *cf, size_t i)
1154 {
1155 if (cf->page_sz == 0 ||
1156 cf->lines_idx / cf->page_sz == i / cf->page_sz)
1157 return 1;
1158 return 0;
1159 }
1160
1161 static void ui_draw_partition(struct cfdisk *cf, size_t i)
1162 {
1163 int ln = TABLE_START_LINE + 1 + i; /* skip table header */
1164 int cl = ARROW_CURSOR_WIDTH; /* we need extra space for cursor */
1165 int cur = cf->lines_idx == i;
1166 size_t curpg = 0;
1167
1168 if (cf->page_sz) {
1169 if (!partition_on_page(cf, i))
1170 return;
1171 ln = TABLE_START_LINE + (i % cf->page_sz) + 1;
1172 curpg = cf->lines_idx / cf->page_sz;
1173 }
1174
1175 DBG(FRONTEND, ul_debug(
1176 "ui: draw partition %zu [page_sz=%zu, "
1177 "line=%d, idx=%zu]",
1178 i, cf->page_sz, ln, cf->lines_idx));
1179
1180 if (cur) {
1181 attron(A_REVERSE);
1182 mvaddstr(ln, 0, ARROW_CURSOR_STRING);
1183 mvaddstr(ln, cl, cf->lines[i + 1]);
1184 attroff(A_REVERSE);
1185 } else {
1186 int at = 0;
1187
1188 if (colors_wanted() && is_freespace(cf, i)) {
1189 attron(COLOR_PAIR(CFDISK_CL_FREESPACE));
1190 at = 1;
1191 }
1192 mvaddstr(ln, 0, ARROW_CURSOR_DUMMY);
1193 mvaddstr(ln, cl, cf->lines[i + 1]);
1194 if (at)
1195 attroff(COLOR_PAIR(CFDISK_CL_FREESPACE));
1196 }
1197
1198 if ((size_t) ln == MENU_START_LINE - 1 &&
1199 cf->page_sz && curpg < cf->nlines / cf->page_sz) {
1200 if (cur)
1201 attron(A_REVERSE);
1202 mvaddch(ln, COLS - 1, ACS_DARROW);
1203 mvaddch(ln, 0, ACS_DARROW);
1204 if (cur)
1205 attroff(A_REVERSE);
1206 }
1207 }
1208
1209 static int ui_draw_table(struct cfdisk *cf)
1210 {
1211 int cl = ARROW_CURSOR_WIDTH;
1212 size_t i, nparts = fdisk_table_get_nents(cf->table);
1213 size_t curpg = cf->page_sz ? cf->lines_idx / cf->page_sz : 0;
1214
1215 DBG(FRONTEND, ul_debug("ui: draw table"));
1216
1217 for (i = TABLE_START_LINE; i <= TABLE_START_LINE + cf->page_sz; i++) {
1218 move(i, 0);
1219 clrtoeol();
1220 }
1221
1222 if ((size_t) cf->lines_idx > nparts - 1)
1223 cf->lines_idx = nparts ? nparts - 1 : 0;
1224
1225 /* print header */
1226 attron(A_BOLD);
1227 mvaddstr(TABLE_START_LINE, cl, cf->lines[0]);
1228 attroff(A_BOLD);
1229
1230 /* print partitions */
1231 for (i = 0; i < nparts; i++)
1232 ui_draw_partition(cf, i);
1233
1234 if (curpg != 0) {
1235 mvaddch(TABLE_START_LINE, COLS - 1, ACS_UARROW);
1236 mvaddch(TABLE_START_LINE, 0, ACS_UARROW);
1237 }
1238 if (cf->page_sz && curpg < cf->nlines / cf->page_sz) {
1239 mvaddch(MENU_START_LINE - 1, COLS - 1, ACS_DARROW);
1240 mvaddch(MENU_START_LINE - 1, 0, ACS_DARROW);
1241 }
1242 return 0;
1243 }
1244
1245 static int ui_table_goto(struct cfdisk *cf, int where)
1246 {
1247 size_t old;
1248 size_t nparts = fdisk_table_get_nents(cf->table);
1249
1250 DBG(FRONTEND, ul_debug("ui: goto table %d", where));
1251
1252 if (where < 0)
1253 where = 0;
1254 else if ((size_t) where > nparts - 1)
1255 where = nparts - 1;
1256
1257 if ((size_t) where == cf->lines_idx)
1258 return 0;
1259
1260 old = cf->lines_idx;
1261 cf->lines_idx = where;
1262
1263 if (!partition_on_page(cf, old) ||!partition_on_page(cf, where))
1264 ui_draw_table(cf);
1265 else {
1266 ui_draw_partition(cf, old); /* cleanup old */
1267 ui_draw_partition(cf, where); /* draw new */
1268 }
1269 ui_clean_info();
1270 ui_draw_menu(cf);
1271 refresh();
1272 return 0;
1273 }
1274
1275 static int ui_refresh(struct cfdisk *cf)
1276 {
1277 char *id = NULL;
1278 uint64_t bytes = cf->cxt->total_sectors * cf->cxt->sector_size;
1279 char *strsz = size_to_human_string(SIZE_SUFFIX_SPACE
1280 | SIZE_SUFFIX_3LETTER, bytes);
1281 erase();
1282
1283 if (!ui_enabled)
1284 return -EINVAL;
1285
1286 /* header */
1287 attron(A_BOLD);
1288 ui_center(0, _("Disk: %s"), cf->cxt->dev_path);
1289 attroff(A_BOLD);
1290 ui_center(1, _("Size: %s, %ju bytes, %ju sectors"),
1291 strsz, bytes, (uintmax_t) cf->cxt->total_sectors);
1292 if (fdisk_get_disklabel_id(cf->cxt, &id) == 0 && id)
1293 ui_center(2, _("Label: %s, identifier: %s"),
1294 cf->cxt->label->name, id);
1295 else
1296 ui_center(2, _("Label: %s"), cf->cxt->label->name);
1297 free(strsz);
1298
1299 ui_draw_table(cf);
1300 ui_draw_menu(cf);
1301 refresh();
1302 return 0;
1303 }
1304
1305 static ssize_t ui_get_string(struct cfdisk *cf, const char *prompt,
1306 const char *hint, char *buf, size_t len)
1307 {
1308 size_t cells = 0;
1309 ssize_t i = 0, rc = -1;
1310 int ln = MENU_START_LINE, cl = 1;
1311
1312 assert(cf);
1313 assert(buf);
1314 assert(len);
1315
1316 move(ln, 0);
1317 clrtoeol();
1318
1319 if (prompt) {
1320 mvaddstr(ln, cl, (char *) prompt);
1321 cl += mbs_safe_width(prompt);
1322 }
1323
1324 /* default value */
1325 if (*buf) {
1326 i = strlen(buf);
1327 cells = mbs_safe_width(buf);
1328 mvaddstr(ln, cl, buf);
1329 }
1330
1331 if (hint)
1332 ui_hint(hint);
1333 else
1334 ui_clean_hint();
1335
1336 move(ln, cl + cells);
1337 curs_set(1);
1338 refresh();
1339
1340 while (1) {
1341 #if !defined(HAVE_SLCURSES_H) && !defined(HAVE_SLANG_SLCURSES_H) && \
1342 defined(HAVE_LIBNCURSESW) && defined(HAVE_WIDECHAR)
1343 wint_t c;
1344 if (get_wch(&c) == ERR) {
1345 #else
1346 int c;
1347 if ((c = getch()) == ERR) {
1348 #endif
1349 if (ui_resize) {
1350 resize();
1351 continue;
1352 }
1353 if (!isatty(STDIN_FILENO))
1354 exit(2);
1355 else
1356 goto done;
1357 }
1358 if (c == '\r' || c == '\n' || c == KEY_ENTER)
1359 break;
1360
1361 switch (c) {
1362 case KEY_ESC:
1363 rc = -CFDISK_ERR_ESC;
1364 goto done;
1365 case KEY_DELETE:
1366 case '\b':
1367 case KEY_BACKSPACE:
1368 if (i > 0) {
1369 cells--;
1370 i = mbs_truncate(buf, &cells);
1371 if (i < 0)
1372 goto done;
1373 mvaddch(ln, cl + cells, ' ');
1374 move(ln, cl + cells);
1375 } else
1376 beep();
1377 break;
1378 default:
1379 #if defined(HAVE_LIBNCURSESW) && defined(HAVE_WIDECHAR)
1380 if (i + 1 < (ssize_t) len && iswprint(c)) {
1381 wchar_t wc = (wchar_t) c;
1382 char s[MB_CUR_MAX + 1];
1383 int sz = wctomb(s, wc);
1384
1385 if (sz > 0 && sz + i < (ssize_t) len) {
1386 s[sz] = '\0';
1387 mvaddnstr(ln, cl + cells, s, sz);
1388 memcpy(buf + i, s, sz);
1389 i += sz;
1390 buf[i] = '\0';
1391 cells += wcwidth(wc);
1392 } else
1393 beep();
1394 }
1395 #else
1396 if (i + 1 < (ssize_t) len && isprint(c)) {
1397 mvaddch(ln, cl + cells, c);
1398 buf[i++] = c;
1399 buf[i] = '\0';
1400 cells++;
1401 }
1402 #endif
1403 else
1404 beep();
1405 }
1406 refresh();
1407 }
1408
1409 rc = i; /* success */
1410 done:
1411 move(ln, 0);
1412 clrtoeol();
1413 curs_set(0);
1414 refresh();
1415
1416 return rc;
1417 }
1418
1419 /* @res is default value as well as result in bytes */
1420 static int ui_get_size(struct cfdisk *cf, const char *prompt, uintmax_t *res,
1421 uintmax_t low, uintmax_t up)
1422 {
1423 char buf[128];
1424 uintmax_t user = 0;
1425 ssize_t rc;
1426 char *dflt = size_to_human_string(0, *res);
1427
1428 DBG(FRONTEND, ul_debug("ui: get_size (default=%ju)", *res));
1429
1430 ui_clean_info();
1431
1432 do {
1433 int pwr = 0, insec = 0;
1434
1435 snprintf(buf, sizeof(buf), "%s", dflt);
1436 rc = ui_get_string(cf, prompt,
1437 _("May be followed by {M,B,G,T}iB "
1438 "(the \"iB\" is optional) or S for sectors."),
1439 buf, sizeof(buf));
1440 if (rc == 0) {
1441 ui_warnx(_("Please, specify size."));
1442 continue; /* nothing specified */
1443 } else if (rc == -CFDISK_ERR_ESC)
1444 break; /* cancel dialog */
1445
1446 if (strcmp(buf, dflt) == 0)
1447 user = *res, rc = 0; /* no change, use default */
1448 else {
1449 size_t len = strlen(buf);
1450 if (buf[len - 1] == 'S' || buf[len - 1] == 's') {
1451 insec = 1;
1452 buf[len - 1] = '\0';
1453 }
1454 rc = parse_size(buf, &user, &pwr); /* parse */
1455 }
1456
1457 if (rc == 0) {
1458 DBG(FRONTEND, ul_debug("ui: get_size user=%ju, power=%d, sectors=%s",
1459 user, pwr, insec ? "yes" : "no"));
1460 if (insec)
1461 user *= cf->cxt->sector_size;
1462 if (user < low) {
1463 ui_warnx(_("Minimal size is %ju"), low);
1464 rc = -ERANGE;
1465 }
1466 if (user > up && pwr && user < up + (1ULL << pwr * 10))
1467 /* ignore when the user specified size overflow
1468 * with in range specified by suffix (e.g. MiB) */
1469 user = up;
1470
1471 if (user > up) {
1472 ui_warnx(_("Maximal size is %ju bytes."), up);
1473 rc = -ERANGE;
1474 }
1475 } else
1476 ui_warnx(_("Failed to parse size."));
1477 } while (rc != 0);
1478
1479 if (rc == 0)
1480 *res = user;
1481 free(dflt);
1482
1483 DBG(FRONTEND, ul_debug("ui: get_size (result=%ju, rc=%zd)", *res, rc));
1484 return rc;
1485 }
1486
1487 static struct fdisk_parttype *ui_get_parttype(struct cfdisk *cf,
1488 struct fdisk_parttype *cur)
1489 {
1490 struct cfdisk_menuitem *d, *cm;
1491 size_t i = 0, nitems, idx = 0;
1492 struct fdisk_parttype *t = NULL;
1493 int has_typestr = 0;
1494
1495 DBG(FRONTEND, ul_debug("ui: asking for parttype."));
1496
1497 /* create cfdisk menu according to label types, note that the
1498 * last cm[] item has to be empty -- so nitems + 1 */
1499 nitems = cf->cxt->label->nparttypes;
1500 if (!nitems)
1501 return NULL;
1502 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
1503 if (!cm)
1504 return NULL;
1505
1506 has_typestr = cf->cxt->label->parttypes[0].typestr &&
1507 *cf->cxt->label->parttypes[0].typestr;
1508
1509 for (i = 0; i < nitems; i++) {
1510 struct fdisk_parttype *x = &cf->cxt->label->parttypes[i];
1511 char *name;
1512
1513 if (!x || !x->name)
1514 continue;
1515 cm[i].userdata = x;
1516 if (!has_typestr)
1517 xasprintf(&name, "%2x %s", x->type, _(x->name));
1518 else {
1519 name = (char *) _(x->name);
1520 cm[i].desc = x->typestr;
1521 }
1522 cm[i].name = name;
1523 if (x == cur)
1524 idx = i;
1525 }
1526
1527 /* make the new menu active */
1528 menu_push(cf, cm);
1529 cf->menu->vertical = 1;
1530 cf->menu->idx = idx;
1531 menu_set_title(cf->menu, _("Select partition type"));
1532 ui_draw_menu(cf);
1533 refresh();
1534
1535 do {
1536 int key = getch();
1537
1538 if (ui_resize)
1539 ui_menu_resize(cf);
1540 if (ui_menu_move(cf, key) == 0)
1541 continue;
1542
1543 switch (key) {
1544 case KEY_ENTER:
1545 case '\n':
1546 case '\r':
1547 d = menu_get_menuitem(cf, cf->menu->idx);
1548 if (d)
1549 t = (struct fdisk_parttype *) d->userdata;
1550 goto done;
1551 case KEY_ESC:
1552 case 'q':
1553 case 'Q':
1554 goto done;
1555 }
1556 } while (1);
1557
1558 done:
1559 menu_pop(cf);
1560 if (!has_typestr) {
1561 for (i = 0; i < nitems; i++)
1562 free((char *) cm[i].name);
1563 }
1564 free(cm);
1565 DBG(FRONTEND, ul_debug("ui: get parrtype done [type=%s] ", t ? t->name : NULL));
1566 return t;
1567 }
1568
1569 /* prints menu with libfdisk labels and waits for users response */
1570 static int ui_create_label(struct cfdisk *cf)
1571 {
1572 struct cfdisk_menuitem *d, *cm;
1573 int rc = 1;
1574 size_t i = 0, nitems;
1575 struct fdisk_label *lb = NULL;
1576
1577 assert(cf);
1578
1579 DBG(FRONTEND, ul_debug("ui: asking for new disklabe."));
1580
1581 /* create cfdisk menu according to libfdisk labels, note that the
1582 * last cm[] item has to be empty -- so nitems + 1 */
1583 nitems = fdisk_context_get_nlabels(cf->cxt);
1584 cm = xcalloc(nitems + 1, sizeof(struct cfdisk_menuitem));
1585
1586 while (fdisk_context_next_label(cf->cxt, &lb) == 0) {
1587 if (fdisk_label_is_disabled(lb) || strcmp(lb->name, "bsd") == 0)
1588 continue;
1589 cm[i++].name = lb->name;
1590 }
1591
1592 erase();
1593 ui_center(LINES - 4,
1594 _("Device does not contain a recognized partition table."));
1595 ui_center(LINES - 3,
1596 _("Please, select a type to create a new disk label."));
1597
1598 /* make the new menu active */
1599 menu_push(cf, cm);
1600 cf->menu->vertical = 1;
1601 menu_set_title(cf->menu, _("Select label type"));
1602 ui_draw_menu(cf);
1603 refresh();
1604
1605 do {
1606 int key = getch();
1607
1608 if (ui_resize)
1609 ui_menu_resize(cf);
1610 if (ui_menu_move(cf, key) == 0)
1611 continue;
1612 switch (key) {
1613 case KEY_ENTER:
1614 case '\n':
1615 case '\r':
1616 d = menu_get_menuitem(cf, cf->menu->idx);
1617 if (d)
1618 rc = fdisk_create_disklabel(cf->cxt, d->name);
1619 goto done;
1620 case KEY_ESC:
1621 case 'q':
1622 case 'Q':
1623 goto done;
1624 }
1625 } while (1);
1626
1627 done:
1628 menu_pop(cf);
1629 free(cm);
1630 DBG(FRONTEND, ul_debug("ui: create label done [rc=%d] ", rc));
1631 return rc;
1632 }
1633
1634 static int ui_help(void)
1635 {
1636 size_t i;
1637 static const char *help[] = {
1638 N_("Help Screen for cfdisk"),
1639 "",
1640 N_("This is cfdisk, a curses based disk partitioning program, which"),
1641 N_("allows you to create, delete and modify partitions on your hard"),
1642 N_("disk drive."),
1643 "",
1644 N_("Copyright (C) 2014 Karel Zak <kzak@redhat.com> "),
1645 N_("Based on the original cfdisk from Kevin E. Martin & aeb."),
1646 "",
1647 N_("Command Meaning"),
1648 N_("------- -------"),
1649 N_(" b Toggle bootable flag of the current partition"),
1650 N_(" d Delete the current partition"),
1651 N_(" h Print this screen"),
1652 N_(" n Create new partition from free space"),
1653 N_(" q Quit program without writing partition table"),
1654 N_(" t Change the partition type"),
1655 N_(" s Fix partitions order (only when in disarray)"),
1656 N_(" W Write partition table to disk (must enter upper case W)"),
1657 N_(" Since this might destroy data on the disk, you must"),
1658 N_(" either confirm or deny the write by entering `yes' or"),
1659 N_(" `no'"),
1660 N_("Up Arrow Move cursor to the previous partition"),
1661 N_("Down Arrow Move cursor to the next partition"),
1662 N_("Left Arrow Move cursor to the previous menu item"),
1663 N_("Right Arrow Move cursor to the next menu item"),
1664
1665 "",
1666 N_("Note: All of the commands can be entered with either upper or lower"),
1667 N_("case letters (except for Writes)."),
1668 "",
1669 N_("Use lsblk(8) or partx(8) to see more details about the device.")
1670 };
1671
1672 erase();
1673 for (i = 0; i < ARRAY_SIZE(help); i++)
1674 mvaddstr(i, 1, _(help[i]));
1675
1676 ui_info(_("Press a key to continue."));
1677
1678 getch();
1679 return 0;
1680 }
1681
1682 /* TODO: use @sz, now 128bytes */
1683 static int main_menu_ignore_keys(struct cfdisk *cf, char *ignore,
1684 size_t sz __attribute__((__unused__)))
1685 {
1686 struct fdisk_partition *pa = get_current_partition(cf);
1687 size_t i = 0;
1688
1689 if (!pa)
1690 return 0;
1691 if (fdisk_partition_is_freespace(pa)) {
1692 ignore[i++] = 'd'; /* delete */
1693 ignore[i++] = 't'; /* set type */
1694 ignore[i++] = 'b'; /* set bootable */
1695 } else {
1696 ignore[i++] = 'n';
1697 if (!fdisk_is_disklabel(cf->cxt, DOS) &&
1698 !fdisk_is_disklabel(cf->cxt, SGI))
1699 ignore[i++] = 'b';
1700 }
1701
1702 if (!cf->wrong_order)
1703 ignore[i++] = 's';
1704 if (fdisk_context_is_readonly(cf->cxt))
1705 ignore[i++] = 'W';
1706 return i;
1707 }
1708
1709
1710 /* returns: error: < 0, success: 0, quit: 1 */
1711 static int main_menu_action(struct cfdisk *cf, int key)
1712 {
1713 size_t n;
1714 int ref = 0, rc, org_order = cf->wrong_order;
1715 const char *info = NULL, *warn = NULL;
1716 struct fdisk_partition *pa;
1717
1718 assert(cf);
1719 assert(cf->cxt);
1720 assert(cf->menu);
1721
1722 if (key == 0) {
1723 struct cfdisk_menuitem *d = menu_get_menuitem(cf, cf->menu->idx);
1724 if (!d)
1725 return 0;
1726 key = d->key;
1727
1728 } else if (key != 'w' && key != 'W')
1729 key = tolower(key); /* case insensitive except 'W'rite */
1730
1731 DBG(FRONTEND, ul_debug("ui: main menu action: key=%c", key));
1732
1733 if (cf->menu->ignore && strchr(cf->menu->ignore, key)) {
1734 DBG(FRONTEND, ul_debug(" ignore '%c'", key));
1735 return 0;
1736 }
1737
1738 pa = get_current_partition(cf);
1739 n = fdisk_partition_get_partno(pa);
1740
1741 DBG(FRONTEND, ul_debug("menu action on %p", pa));
1742 ui_clean_hint();
1743 ui_clean_info();
1744
1745 switch (key) {
1746 case 'b': /* Bootable flag */
1747 {
1748 int fl = fdisk_is_disklabel(cf->cxt, DOS) ? DOS_FLAG_ACTIVE :
1749 fdisk_is_disklabel(cf->cxt, SGI) ? SGI_FLAG_BOOT : 0;
1750
1751 if (fl && fdisk_partition_toggle_flag(cf->cxt, n, fl))
1752 warn = _("Could not toggle the flag.");
1753 else if (fl)
1754 ref = 1;
1755 break;
1756 }
1757 #ifdef KEY_DC
1758 case KEY_DC:
1759 #endif
1760 case 'd': /* Delete */
1761 if (fdisk_delete_partition(cf->cxt, n) != 0)
1762 warn = _("Could not delete partition %zu.");
1763 else
1764 info = _("Partition %zu has been deleted.");
1765 ref = 1;
1766 break;
1767 case 'h': /* help */
1768 ui_help();
1769 ref = 1;
1770 break;
1771 case 'n': /* New */
1772 {
1773 uint64_t start, size, dflt_size;
1774 struct fdisk_partition *npa; /* the new partition */
1775
1776 if (!pa || !fdisk_partition_is_freespace(pa))
1777 return -EINVAL;
1778 npa = fdisk_new_partition();
1779 if (!npa)
1780 return -ENOMEM;
1781 /* free space range */
1782 start = fdisk_partition_get_start(pa);
1783 size = dflt_size = fdisk_partition_get_size(pa) * cf->cxt->sector_size;
1784
1785 if (ui_get_size(cf, _("Partition size: "), &size, 1, size)
1786 == -CFDISK_ERR_ESC)
1787 break;
1788
1789 if (dflt_size == size) /* default is to fillin all free space */
1790 fdisk_partition_end_follow_default(npa, 1);
1791 else /* set relative size of the partition */
1792 fdisk_partition_set_size(npa, size / cf->cxt->sector_size);
1793
1794 fdisk_partition_set_start(npa, start);
1795 fdisk_partition_partno_follow_default(npa, 1);
1796 /* add to disk label -- libfdisk will ask for missing details */
1797 rc = fdisk_add_partition(cf->cxt, npa);
1798 fdisk_unref_partition(npa);
1799 if (rc == 0)
1800 ref = 1;
1801 break;
1802 }
1803 case 'q': /* Quit */
1804 return 1;
1805 case 't': /* Type */
1806 {
1807 struct fdisk_parttype *t;
1808
1809 if (!pa || fdisk_partition_is_freespace(pa))
1810 return -EINVAL;
1811 t = (struct fdisk_parttype *) fdisk_partition_get_type(pa);
1812 t = ui_get_parttype(cf, t);
1813 ref = 1;
1814
1815 if (t && fdisk_set_partition_type(cf->cxt, n, t) == 0)
1816 info = _("Changed type of partition %zu.");
1817 else
1818 info = _("The type of partition %zu is unchanged.");
1819 break;
1820 }
1821 case 's': /* fix order */
1822 if (cf->wrong_order) {
1823 fdisk_reorder_partitions(cf->cxt);
1824 ref = 1;
1825 }
1826 break;
1827 case 'W': /* Write */
1828 {
1829 char buf[64] = { 0 };
1830 int rc;
1831
1832 if (fdisk_context_is_readonly(cf->cxt)) {
1833 warn = _("Device open in read-only mode");
1834 break;
1835 }
1836
1837 rc = ui_get_string(cf,
1838 _("Are you sure you want to write the partition "
1839 "table to disk? "),
1840 _("Type \"yes\" or \"no\", or press ESC to leave this dialog."),
1841 buf, sizeof(buf));
1842
1843 ref = 1;
1844 if (rc <= 0 || strcasecmp(buf, "yes") != 0
1845 || strcasecmp(buf, _("yes")) != 0) {
1846 info = _("Did not write partition table to disk");
1847 break;
1848 }
1849 rc = fdisk_write_disklabel(cf->cxt);
1850 if (rc)
1851 warn = _("Failed to write disklabel");
1852 else {
1853 fdisk_reread_partition_table(cf->cxt);
1854 info = _("The partition table has been altered.");
1855 }
1856 cf->nwrites++;
1857 break;
1858 }
1859 default:
1860 break;
1861 }
1862
1863 if (ref) {
1864 lines_refresh(cf);
1865 ui_refresh(cf);
1866 }
1867
1868 ui_clean_hint();
1869 if (warn)
1870 ui_warnx(warn, n + 1);
1871 else if (info)
1872 ui_info(info, n + 1);
1873 else if (key == 'n' && cf->wrong_order && org_order == 0)
1874 ui_info(_("Note that partition table entries are not in disk order now."));
1875
1876 return 0;
1877 }
1878
1879 static void ui_resize_refresh(struct cfdisk *cf)
1880 {
1881 resize();
1882 menu_refresh_size(cf);
1883 lines_refresh(cf);
1884 ui_refresh(cf);
1885 }
1886
1887 static int ui_run(struct cfdisk *cf)
1888 {
1889 int rc = 0;
1890
1891 DBG(FRONTEND, ul_debug("ui: start COLS=%d, LINES=%d", COLS, LINES));
1892
1893 if (!fdisk_dev_has_disklabel(cf->cxt) || cf->zero_start) {
1894 rc = ui_create_label(cf);
1895 if (rc < 0)
1896 ui_errx(EXIT_FAILURE,
1897 _("failed to create a new disklabel"));
1898 if (rc)
1899 return rc;
1900 }
1901
1902 cols_init(cf);
1903 rc = lines_refresh(cf);
1904 if (rc)
1905 ui_errx(EXIT_FAILURE, _("failed to read partitions"));
1906
1907 menu_push(cf, main_menuitems);
1908 cf->menu->ignore_cb = main_menu_ignore_keys;
1909
1910 rc = ui_refresh(cf);
1911 if (rc)
1912 return rc;
1913
1914 if (fdisk_context_is_readonly(cf->cxt))
1915 ui_warnx(_("Device open in read-only mode."));
1916
1917 do {
1918 int rc = 0, key = getch();
1919
1920 if (ui_resize)
1921 /* Note that ncurses getch() returns ERR when interrupted
1922 * by signal, but SLang does not interrupt at all. */
1923 ui_resize_refresh(cf);
1924 if (key == ERR)
1925 continue;
1926 if (ui_menu_move(cf, key) == 0)
1927 continue;
1928
1929 DBG(FRONTEND, ul_debug("ui: main action key >%c<.", key));
1930
1931 switch (key) {
1932 case KEY_DOWN:
1933 case '\016': /* ^N */
1934 case 'j': /* Vi-like alternative */
1935 ui_table_goto(cf, cf->lines_idx + 1);
1936 break;
1937 case KEY_UP:
1938 case '\020': /* ^P */
1939 case 'k': /* Vi-like alternative */
1940 ui_table_goto(cf, (int) cf->lines_idx - 1);
1941 break;
1942 case KEY_PPAGE:
1943 if (cf->page_sz) {
1944 ui_table_goto(cf, (int) cf->lines_idx - cf->page_sz);
1945 break;
1946 }
1947 case KEY_HOME:
1948 ui_table_goto(cf, 0);
1949 break;
1950 case KEY_NPAGE:
1951 if (cf->page_sz) {
1952 ui_table_goto(cf, cf->lines_idx + cf->page_sz);
1953 break;
1954 }
1955 case KEY_END:
1956 ui_table_goto(cf, (int) cf->nlines - 1);
1957 break;
1958 case KEY_ENTER:
1959 case '\n':
1960 case '\r':
1961 rc = main_menu_action(cf, 0);
1962 break;
1963 default:
1964 rc = main_menu_action(cf, key);
1965 if (rc < 0)
1966 beep();
1967 break;
1968 }
1969
1970 if (rc == 1)
1971 break; /* quit */
1972 } while (1);
1973
1974 menu_pop(cf);
1975
1976 DBG(FRONTEND, ul_debug("ui: end"));
1977 return 0;
1978 }
1979
1980 static void __attribute__ ((__noreturn__)) usage(FILE *out)
1981 {
1982 fputs(USAGE_HEADER, out);
1983
1984 fprintf(out,
1985 _(" %1$s [options] <disk>\n"), program_invocation_short_name);
1986
1987 fputs(USAGE_OPTIONS, out);
1988 fputs(_(" -L --color[=<when>] colorize output (auto, always or never)\n"), out);
1989 fputs(_(" -z --zero start with zeroed partition table\n"), out);
1990
1991 fputs(USAGE_SEPARATOR, out);
1992 fputs(USAGE_HELP, out);
1993 fputs(USAGE_VERSION, out);
1994
1995 fprintf(out, USAGE_MAN_TAIL("cfdisk(8)"));
1996 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
1997 }
1998
1999 int main(int argc, char *argv[])
2000 {
2001 const char *diskpath;
2002 int rc, c, colormode = UL_COLORMODE_UNDEF;
2003 struct cfdisk _cf = { .lines_idx = 0 },
2004 *cf = &_cf;
2005
2006 static const struct option longopts[] = {
2007 { "color", optional_argument, NULL, 'L' },
2008 { "help", no_argument, NULL, 'h' },
2009 { "version", no_argument, NULL, 'V' },
2010 { "zero", no_argument, NULL, 'z' },
2011 { NULL, 0, 0, 0 },
2012 };
2013
2014 setlocale(LC_ALL, "");
2015 bindtextdomain(PACKAGE, LOCALEDIR);
2016 textdomain(PACKAGE);
2017 atexit(close_stdout);
2018
2019 while((c = getopt_long(argc, argv, "L::hVz", longopts, NULL)) != -1) {
2020 switch(c) {
2021 case 'h':
2022 usage(stdout);
2023 break;
2024 case 'L':
2025 colormode = UL_COLORMODE_AUTO;
2026 if (optarg)
2027 colormode = colormode_or_err(optarg,
2028 _("unsupported color mode"));
2029 break;
2030 case 'V':
2031 printf(_("%s from %s\n"), program_invocation_short_name,
2032 PACKAGE_STRING);
2033 return EXIT_SUCCESS;
2034 case 'z':
2035 cf->zero_start = 1;
2036 break;
2037 }
2038 }
2039
2040 colors_init(colormode, "cfdisk");
2041
2042 fdisk_init_debug(0);
2043 scols_init_debug(0);
2044
2045 cf->cxt = fdisk_new_context();
2046 if (!cf->cxt)
2047 err(EXIT_FAILURE, _("failed to allocate libfdisk context"));
2048
2049 fdisk_context_set_ask(cf->cxt, ask_callback, (void *) cf);
2050
2051 if (optind == argc)
2052 diskpath = access(DEFAULT_DEVICE, F_OK) == 0 ?
2053 DEFAULT_DEVICE : ALTERNATE_DEVICE;
2054 else
2055 diskpath = argv[optind];
2056
2057 rc = fdisk_context_assign_device(cf->cxt, diskpath, 0);
2058 if (rc == -EACCES)
2059 rc = fdisk_context_assign_device(cf->cxt, diskpath, 1);
2060 if (rc != 0)
2061 err(EXIT_FAILURE, _("cannot open %s"),
2062 optind == argc ? DEFAULT_DEVICE : diskpath);
2063
2064 /* Don't use err(), warn() from this point */
2065 ui_init(cf);
2066 ui_run(cf);
2067 ui_end();
2068
2069 free(cf->lines);
2070 free(cf->linesbuf);
2071 fdisk_unref_table(cf->table);
2072
2073 rc = fdisk_context_deassign_device(cf->cxt, cf->nwrites == 0);
2074 fdisk_free_context(cf->cxt);
2075 DBG(FRONTEND, ul_debug("bye! [rc=%d]", rc));
2076 return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2077 }