2 * cfdisk.c - Display or manipulate a disk partition table.
4 * Copyright (C) 2014-2015 Karel Zak <kzak@redhat.com>
5 * Copyright (C) 1994 Kevin E. Martin (martin@cs.unc.edu)
7 * The original cfdisk was inspired by the fdisk program
8 * by A. V. Le Blanc (leblanc@mcc.ac.uk.
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.
22 #include <libsmartcols.h>
23 #include <sys/ioctl.h>
27 # include <libmount.h> /* keep it optional for non-linux systems */
32 #elif defined(HAVE_SLANG_SLANG_H)
33 # include <slang/slang.h>
37 # define _XOPEN_SOURCE 500 /* for inclusion of get_wch */
40 #ifdef HAVE_SLCURSES_H
41 # include <slcurses.h>
42 #elif defined(HAVE_SLANG_SLCURSES_H)
43 # include <slang/slcurses.h>
44 #elif defined(HAVE_NCURSESW_NCURSES_H) && defined(HAVE_WIDECHAR)
45 # include <ncursesw/ncurses.h>
46 #elif defined(HAVE_NCURSES_H)
48 #elif defined(HAVE_NCURSES_NCURSES_H)
49 # include <ncurses/ncurses.h>
58 #include "closestream.h"
69 static const char *default_disks
[] = {
73 #elif defined(__FreeBSD__)
83 #define ARROW_CURSOR_STRING ">> "
84 #define ARROW_CURSOR_DUMMY " "
85 #define ARROW_CURSOR_WIDTH (sizeof(ARROW_CURSOR_STRING) - 1)
88 #define MENU_V_SPADDING 1 /* space around menu item string */
91 #define MENU_H_SPADDING 0 /* space around menu item string */
92 #define MENU_H_BETWEEN 2 /* space between menu items */
93 #define MENU_H_PRESTR "["
94 #define MENU_H_POSTSTR "]"
96 #define MENU_TITLE_PADDING 3
98 #define MENU_H_PRESTR_SZ (sizeof(MENU_H_PRESTR) - 1)
99 #define MENU_H_POSTSTR_SZ (sizeof(MENU_H_POSTSTR) - 1)
101 #define TABLE_START_LINE 4
102 #define MENU_START_LINE (ui_lines - 4) /* The menu maybe use two lines */
103 #define INFO_LINE (ui_lines - 2)
104 #define WARN_LINE INFO_LINE
105 #define HINT_LINE (ui_lines - 1)
107 #define CFDISK_ERR_ESC 5000
110 # define KEY_ESC '\033'
113 # define KEY_DELETE '\177'
127 #ifdef HAVE_USE_DEFAULT_COLORS
128 static const int color_pairs
[][2] = {
129 /* color foreground, background */
130 [CFDISK_CL_WARNING
] = { COLOR_RED
, -1 },
131 [CFDISK_CL_FREESPACE
] = { COLOR_GREEN
, -1 },
132 [CFDISK_CL_INFO
] = { COLOR_BLUE
, -1 }
138 static struct cfdisk_menuitem
*menu_get_menuitem(struct cfdisk
*cf
, size_t idx
);
139 static struct cfdisk_menuitem
*menu_get_menuitem_by_key(struct cfdisk
*cf
, int key
, size_t *idx
);
140 static struct cfdisk_menu
*menu_push(struct cfdisk
*cf
, struct cfdisk_menuitem
*item
);
141 static struct cfdisk_menu
*menu_pop(struct cfdisk
*cf
);
142 static void menu_refresh_size(struct cfdisk
*cf
);
144 static int ui_end(void);
145 static int ui_refresh(struct cfdisk
*cf
);
147 static void ui_warnx(const char *fmt
, ...)
148 __attribute__((__format__ (__printf__
, 1, 2)));
149 static void ui_warn(const char *fmt
, ...)
150 __attribute__((__format__ (__printf__
, 1, 2)));
151 static void ui_info(const char *fmt
, ...)
152 __attribute__((__format__ (__printf__
, 1, 2)));
154 static void ui_draw_menu(struct cfdisk
*cf
);
155 static int ui_menu_move(struct cfdisk
*cf
, int key
);
156 static void ui_menu_resize(struct cfdisk
*cf
);
158 static int ui_get_size(struct cfdisk
*cf
, const char *prompt
, uint64_t *res
,
159 uint64_t low
, uint64_t up
, int *expsize
);
161 static int ui_enabled
;
162 static volatile sig_atomic_t sig_resize
;
163 static volatile sig_atomic_t sig_die
;
165 /* ncurses LINES and COLS may be actual variables or *macros*, but we need
166 * something portable and writable */
167 static size_t ui_lines
;
168 static size_t ui_cols
;
171 struct cfdisk_menuitem
{
172 int key
; /* keyboard shortcut */
173 const char *name
; /* item name */
174 const char *desc
; /* item description (hint) */
180 char *title
; /* optional menu title */
181 struct cfdisk_menuitem
*items
; /* array with menu items */
182 char *ignore
;/* string with keys to ignore */
183 size_t width
; /* maximal width of the menu item */
184 size_t nitems
; /* number of the active menu items */
185 size_t page_sz
;/* when menu longer than screen */
186 size_t idx
; /* the current menu item */
187 int prefkey
;/* preferred menu item */
188 struct cfdisk_menu
*prev
;
190 /* @ignore keys generator */
191 int (*ignore_cb
) (struct cfdisk
*, char *, size_t);
193 unsigned int vertical
: 1; /* enable vertical mode */
197 static struct cfdisk_menuitem main_menuitems
[] = {
198 { 'b', N_("Bootable"), N_("Toggle bootable flag of the current partition") },
199 { 'd', N_("Delete"), N_("Delete the current partition") },
200 { 'r', N_("Resize"), N_("Reduce or enlarge the current partition") },
201 { 'n', N_("New"), N_("Create new partition from free space") },
202 { 'q', N_("Quit"), N_("Quit program without writing changes") },
203 { 't', N_("Type"), N_("Change the partition type") },
204 { 'h', N_("Help"), N_("Print help screen") },
205 { 's', N_("Sort"), N_("Fix partitions order") },
206 { 'W', N_("Write"), N_("Write partition table to disk (this might destroy data)") },
207 { 'u', N_("Dump"), N_("Dump partition table to sfdisk compatible script file") },
211 /* extra partinfo in name:value pairs */
212 struct cfdisk_extra
{
216 struct list_head exs
;
219 /* line and extra partinfo list_head */
221 char *data
; /* line data */
222 struct libscols_table
*extra
; /* extra info ('X') */
223 WINDOW
*w
; /* window with extra info */
226 /* top level control struct */
228 struct fdisk_context
*cxt
; /* libfdisk context */
229 struct fdisk_table
*table
; /* partition table */
230 struct fdisk_table
*original_layout
; /* original on-disk PT */
232 struct cfdisk_menu
*menu
; /* the current menu */
234 int *fields
; /* output columns IDs */
235 size_t nfields
; /* number of columns IDs */
237 char *linesbuf
; /* table as string */
238 size_t linesbufsz
; /* size of the tb_buf */
240 struct cfdisk_line
*lines
; /* list of lines */
242 size_t nlines
; /* number of lines */
243 size_t lines_idx
; /* current line <0..N>, exclude header */
246 unsigned int nwrites
; /* fdisk_write_disklabel() counter */
248 WINDOW
*act_win
; /* the window currently on the screen */
251 struct libmnt_table
*mtab
;
252 struct libmnt_table
*fstab
;
253 struct libmnt_cache
*mntcache
;
255 unsigned int wrong_order
:1, /* PT not in right order */
256 zero_start
:1, /* ignore existing partition table */
257 device_is_used
: 1, /* don't use re-read ioctl */
258 show_extra
:1; /* show extra partinfo */
263 * let's use include/debug.h stuff for cfdisk too
265 static UL_DEBUG_DEFINE_MASK(cfdisk
);
266 UL_DEBUG_DEFINE_MASKNAMES(cfdisk
) = UL_DEBUG_EMPTY_MASKNAMES
;
268 #define CFDISK_DEBUG_INIT (1 << 1)
269 #define CFDISK_DEBUG_UI (1 << 2)
270 #define CFDISK_DEBUG_MENU (1 << 3)
271 #define CFDISK_DEBUG_MISC (1 << 4)
272 #define CFDISK_DEBUG_TABLE (1 << 5)
273 #define CFDISK_DEBUG_ALL 0xFFFF
275 #define DBG(m, x) __UL_DBG(cfdisk, CFDISK_DEBUG_, m, x)
277 static void cfdisk_init_debug(void)
279 __UL_INIT_DEBUG_FROM_ENV(cfdisk
, CFDISK_DEBUG_
, 0, CFDISK_DEBUG
);
282 /* Initialize output columns -- we follow libfdisk fields (usually specific
285 static int cols_init(struct cfdisk
*cf
)
293 return fdisk_label_get_fields_ids(NULL
, cf
->cxt
, &cf
->fields
, &cf
->nfields
);
296 static void die_on_signal(void)
298 DBG(MISC
, ul_debug("die on signal."));
303 static void resize(void)
307 if (ioctl(fileno(stdout
), TIOCGWINSZ
, &ws
) != -1
308 && ws
.ws_row
&& ws
.ws_col
) {
309 ui_lines
= ws
.ws_row
;
312 resizeterm(ws
.ws_row
, ws
.ws_col
);
314 clearok(stdscr
, TRUE
);
318 DBG(UI
, ul_debug("ui: resize refresh ui_cols=%zu, ui_lines=%zu",
323 /* Reads partition in tree-like order from scols
325 static int partition_from_scols(struct fdisk_table
*tb
,
326 struct libscols_line
*ln
)
328 struct fdisk_partition
*pa
= scols_line_get_userdata(ln
);
330 fdisk_table_add_partition(tb
, pa
);
331 fdisk_unref_partition(pa
);
333 if (scols_line_has_children(ln
)) {
334 struct libscols_line
*chln
;
335 struct libscols_iter
*itr
= scols_new_iter(SCOLS_ITER_FORWARD
);
339 while (scols_line_next_child(ln
, itr
, &chln
) == 0)
340 partition_from_scols(tb
, chln
);
341 scols_free_iter(itr
);
346 static char *table_to_string(struct cfdisk
*cf
, struct fdisk_table
*tb
)
348 struct fdisk_partition
*pa
;
349 struct fdisk_label
*lb
;
350 struct fdisk_iter
*itr
;
351 struct libscols_table
*table
= NULL
;
352 struct libscols_iter
*s_itr
= NULL
;
356 struct libscols_line
*ln
, *ln_cont
= NULL
;
358 DBG(TABLE
, ul_debug("convert to string"));
365 lb
= fdisk_get_label(cf
->cxt
, NULL
);
368 itr
= fdisk_new_iter(FDISK_ITER_FORWARD
);
372 /* get container (e.g. extended partition) */
373 while (fdisk_table_next_partition(tb
, itr
, &pa
) == 0) {
374 if (fdisk_partition_is_nested(pa
)) {
375 DBG(TABLE
, ul_debug("nested detected, using tree"));
376 tree
= SCOLS_FL_TREE
;
381 table
= scols_new_table();
384 scols_table_enable_maxout(table
, 1);
385 scols_table_enable_nowrap(table
, 1);
387 #if !defined(HAVE_LIBNCURSESW) || !defined(HAVE_WIDECHAR)
388 scols_table_enable_ascii(table
, 1);
392 for (i
= 0; i
< cf
->nfields
; i
++) {
394 const struct fdisk_field
*field
=
395 fdisk_label_get_field(lb
, cf
->fields
[i
]);
399 if (fdisk_field_is_number(field
))
400 fl
|= SCOLS_FL_RIGHT
;
401 if (fdisk_field_get_id(field
) == FDISK_FIELD_TYPE
)
402 fl
|= SCOLS_FL_TRUNC
;
403 if (tree
&& fdisk_field_get_id(field
) == FDISK_FIELD_DEVICE
)
406 if (!scols_table_new_column(table
,
407 _(fdisk_field_get_name(field
)),
408 fdisk_field_get_width(field
), fl
))
413 fdisk_reset_iter(itr
, FDISK_ITER_FORWARD
);
415 while (fdisk_table_next_partition(tb
, itr
, &pa
) == 0) {
416 struct libscols_line
*parent
= fdisk_partition_is_nested(pa
) ? ln_cont
: NULL
;
418 ln
= scols_table_new_line(table
, parent
);
421 for (i
= 0; i
< cf
->nfields
; i
++) {
424 if (fdisk_partition_to_string(pa
, cf
->cxt
,
425 cf
->fields
[i
], &cdata
))
427 scols_line_refer_data(ln
, i
, cdata
);
429 if (tree
&& fdisk_partition_is_container(pa
))
432 scols_line_set_userdata(ln
, (void *) pa
);
433 fdisk_ref_partition(pa
);
436 if (scols_table_is_empty(table
))
439 scols_table_reduce_termwidth(table
, ARROW_CURSOR_WIDTH
);
440 scols_print_table_to_string(table
, &res
);
442 /* scols_* code might reorder lines, let's reorder @tb according to the
443 * final output (it's no problem because partitions are addressed by
444 * parno stored within struct fdisk_partition) */
447 fdisk_reset_table(tb
);
449 s_itr
= scols_new_iter(SCOLS_ITER_FORWARD
);
453 /* add all in the right order (don't forget the output is tree) */
454 while (scols_table_next_line(table
, s_itr
, &ln
) == 0) {
455 if (scols_line_get_parent(ln
))
457 if (partition_from_scols(tb
, ln
))
461 scols_unref_table(table
);
462 scols_free_iter(s_itr
);
463 fdisk_free_iter(itr
);
468 static void cfdisk_free_lines(struct cfdisk
*cf
)
471 while(i
< cf
->nlines
) {
472 scols_unref_table(cf
->lines
[i
].extra
);
474 DBG(UI
, ul_debug("delete window: %p",
478 delwin(cf
->lines
[i
].w
);
479 cf
->lines
[i
].w
= NULL
;
487 * Read data about partitions from libfdisk and prepare output lines.
489 static int lines_refresh(struct cfdisk
*cf
)
497 DBG(TABLE
, ul_debug("refreshing buffer"));
500 cfdisk_free_lines(cf
);
506 fdisk_unref_table(cf
->table
);
509 /* read partitions and free spaces into cf->table */
510 rc
= fdisk_get_partitions(cf
->cxt
, &cf
->table
);
512 rc
= fdisk_get_freespaces(cf
->cxt
, &cf
->table
);
516 cf
->linesbuf
= table_to_string(cf
, cf
->table
);
520 cf
->linesbufsz
= strlen(cf
->linesbuf
);
521 cf
->nlines
= fdisk_table_get_nents(cf
->table
) + 1; /* 1 for header line */
523 cf
->wrong_order
= fdisk_table_wrong_order(cf
->table
) ? 1 : 0;
525 if (MENU_START_LINE
- TABLE_START_LINE
< cf
->nlines
)
526 cf
->page_sz
= MENU_START_LINE
- TABLE_START_LINE
- 1;
528 cf
->lines
= xcalloc(cf
->nlines
, sizeof(struct cfdisk_line
));
530 for (p
= cf
->linesbuf
, i
= 0; p
&& i
< cf
->nlines
; i
++) {
531 cf
->lines
[i
].data
= p
;
537 cf
->lines
[i
].extra
= scols_new_table();
538 scols_table_enable_noheadings(cf
->lines
[i
].extra
, 1);
539 scols_table_new_column(cf
->lines
[i
].extra
, NULL
, 0, SCOLS_FL_RIGHT
);
540 scols_table_new_column(cf
->lines
[i
].extra
, NULL
, 0, SCOLS_FL_TRUNC
);
546 static struct fdisk_partition
*get_current_partition(struct cfdisk
*cf
)
551 return fdisk_table_get_partition(cf
->table
, cf
->lines_idx
);
554 static int is_freespace(struct cfdisk
*cf
, size_t i
)
556 struct fdisk_partition
*pa
;
561 pa
= fdisk_table_get_partition(cf
->table
, i
);
562 return fdisk_partition_is_freespace(pa
);
565 /* converts libfdisk FDISK_ASKTYPE_MENU to cfdisk menu and returns user's
566 * response back to libfdisk
568 static int ask_menu(struct fdisk_ask
*ask
, struct cfdisk
*cf
)
570 struct cfdisk_menuitem
*d
, *cm
;
572 size_t i
= 0, nitems
;
573 const char *name
, *desc
;
578 /* create cfdisk menu according to libfdisk ask-menu, note that the
579 * last cm[] item has to be empty -- so nitems + 1 */
580 nitems
= fdisk_ask_menu_get_nitems(ask
);
581 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
583 for (i
= 0; i
< nitems
; i
++) {
584 if (fdisk_ask_menu_get_item(ask
, i
, &key
, &name
, &desc
))
591 /* make the new menu active */
604 if (ui_menu_move(cf
, key
) == 0)
611 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
613 fdisk_ask_menu_set_result(ask
, d
->key
);
630 static int ask_callback(struct fdisk_context
*cxt
__attribute__((__unused__
)),
631 struct fdisk_ask
*ask
,
632 void *data
__attribute__((__unused__
)))
638 switch(fdisk_ask_get_type(ask
)) {
639 case FDISK_ASKTYPE_INFO
:
640 ui_info("%s", fdisk_ask_print_get_mesg(ask
));
642 case FDISK_ASKTYPE_WARNX
:
643 ui_warnx("%s", fdisk_ask_print_get_mesg(ask
));
645 case FDISK_ASKTYPE_WARN
:
646 ui_warn("%s", fdisk_ask_print_get_mesg(ask
));
648 case FDISK_ASKTYPE_MENU
:
649 ask_menu(ask
, (struct cfdisk
*) data
);
652 ui_warnx(_("internal error: unsupported dialog type %d"),
653 fdisk_ask_get_type(ask
));
659 static int ui_end(void)
664 #if defined(HAVE_SLCURSES_H) || defined(HAVE_SLANG_SLCURSES_H)
665 SLsmg_gotorc(ui_lines
- 1, 0);
668 mvcur(0, ui_cols
- 1, ui_lines
-1, 0);
678 static void __attribute__((__format__ (__printf__
, 3, 0)))
679 ui_vprint_center(size_t line
, int attrs
, const char *fmt
, va_list ap
)
687 xvasprintf(&buf
, fmt
, ap
);
689 width
= mbs_safe_width(buf
);
690 if (width
> (size_t) ui_cols
) {
691 char *p
= strrchr(buf
+ ui_cols
, ' ');
695 if (line
+ 1 >= ui_lines
)
698 mvaddstr(line
, 0, buf
);
699 mvaddstr(line
+ 1, 0, p
+1);
703 mvaddstr(line
, (ui_cols
- width
) / 2, buf
);
709 static void __attribute__((__format__ (__printf__
, 2, 3)))
710 ui_center(size_t line
, const char *fmt
, ...)
714 ui_vprint_center(line
, 0, fmt
, ap
);
718 static void __attribute__((__format__ (__printf__
, 1, 2)))
719 ui_warnx(const char *fmt
, ...)
724 ui_vprint_center(WARN_LINE
,
725 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING
) : 0,
728 vfprintf(stderr
, fmt
, ap
);
734 static void __attribute__((__format__ (__printf__
, 1, 2)))
735 ui_warn(const char *fmt
, ...)
740 xasprintf(&fmt_m
, "%s: %m", fmt
);
744 ui_vprint_center(WARN_LINE
,
745 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING
) : 0,
748 vfprintf(stderr
, fmt_m
, ap
);
755 static void ui_clean_warn(void)
761 static int __attribute__((__noreturn__
))
762 __attribute__((__format__ (__printf__
, 2, 3)))
763 ui_err(int rc
, const char *fmt
, ...)
769 fprintf(stderr
, "%s: ", program_invocation_short_name
);
770 vfprintf(stderr
, fmt
, ap
);
771 fprintf(stderr
, ": %s\n", strerror(errno
));
777 static int __attribute__((__noreturn__
))
778 __attribute__((__format__ (__printf__
, 2, 3)))
779 ui_errx(int rc
, const char *fmt
, ...)
785 fprintf(stderr
, "%s: ", program_invocation_short_name
);
786 vfprintf(stderr
, fmt
, ap
);
793 static void __attribute__((__format__ (__printf__
, 1, 2)))
794 ui_info(const char *fmt
, ...)
799 ui_vprint_center(INFO_LINE
,
800 colors_wanted() ? COLOR_PAIR(CFDISK_CL_INFO
) : 0,
803 vfprintf(stdout
, fmt
, ap
);
809 static void ui_clean_info(void)
815 static void __attribute__((__format__ (__printf__
, 1, 2)))
816 ui_hint(const char *fmt
, ...)
821 ui_vprint_center(HINT_LINE
, A_BOLD
, fmt
, ap
);
823 vfprintf(stdout
, fmt
, ap
);
829 static void ui_clean_hint(void)
836 static void sig_handler_die(int dummy
__attribute__((__unused__
)))
841 static void sig_handler_resize(int dummy
__attribute__((__unused__
)))
846 static void menu_refresh_size(struct cfdisk
*cf
)
848 if (cf
->menu
&& cf
->menu
->nitems
)
849 cf
->menu
->page_sz
= (cf
->menu
->nitems
/ (ui_lines
- 4)) ? ui_lines
- 4 : 0;
852 static void menu_update_ignore(struct cfdisk
*cf
)
854 char ignore
[128] = { 0 };
856 struct cfdisk_menu
*m
;
857 struct cfdisk_menuitem
*d
, *org
= NULL
;
862 assert(cf
->menu
->ignore_cb
);
865 DBG(MENU
, ul_debug("update menu ignored keys"));
867 i
= m
->ignore_cb(cf
, ignore
, sizeof(ignore
));
870 /* return if no change */
871 if ((!m
->ignore
&& !*ignore
)
872 || (m
->ignore
&& *ignore
&& strcmp(m
->ignore
, ignore
) == 0)) {
877 org
= menu_get_menuitem(cf
, m
->idx
);
880 m
->ignore
= xstrdup(ignore
);
883 for (d
= m
->items
; d
->name
; d
++) {
884 if (m
->ignore
&& strchr(m
->ignore
, d
->key
))
889 DBG(MENU
, ul_debug("update menu preferred keys"));
891 /* refresh menu index to be at the same menuitem or go to the first */
892 if (org
&& menu_get_menuitem_by_key(cf
, org
->key
, &idx
))
894 else if (m
->prefkey
&& menu_get_menuitem_by_key(cf
, m
->prefkey
, &idx
))
899 menu_refresh_size(cf
);
902 static struct cfdisk_menu
*menu_push(
904 struct cfdisk_menuitem
*items
)
906 struct cfdisk_menu
*m
= xcalloc(1, sizeof(*m
));
907 struct cfdisk_menuitem
*d
;
911 DBG(MENU
, ul_debug("new menu"));
916 for (d
= m
->items
; d
->name
; d
++) {
917 const char *name
= _(d
->name
);
918 size_t len
= mbs_safe_width(name
);
926 menu_refresh_size(cf
);
930 static struct cfdisk_menu
*menu_pop(struct cfdisk
*cf
)
932 struct cfdisk_menu
*m
= NULL
;
936 DBG(MENU
, ul_debug("pop menu"));
940 free(cf
->menu
->ignore
);
941 free(cf
->menu
->title
);
948 static void menu_set_title(struct cfdisk_menu
*m
, const char *title
)
953 size_t len
= mbs_safe_width(title
);
954 if (len
+ MENU_TITLE_PADDING
> m
->width
)
955 m
->width
= len
+ MENU_TITLE_PADDING
;
956 str
= xstrdup(title
);
962 static int ui_init(struct cfdisk
*cf
__attribute__((__unused__
)))
966 DBG(UI
, ul_debug("init"));
968 /* setup SIGCHLD handler */
969 sigemptyset(&sa
.sa_mask
);
971 sa
.sa_handler
= sig_handler_die
;
972 sigaction(SIGINT
, &sa
, NULL
);
973 sigaction(SIGTERM
, &sa
, NULL
);
975 sa
.sa_handler
= sig_handler_resize
;
976 sigaction(SIGWINCH
, &sa
, NULL
);
981 #ifdef HAVE_USE_DEFAULT_COLORS
982 if (colors_wanted() && has_colors()) {
986 use_default_colors();
987 for (i
= 1; i
< ARRAY_SIZE(color_pairs
); i
++) /* yeah, start from 1! */
988 init_pair(i
, color_pairs
[i
][0], color_pairs
[i
][1]);
998 keypad(stdscr
, TRUE
);
1004 #define MENU_H_ITEMWIDTH(m) ( MENU_H_PRESTR_SZ \
1008 + MENU_H_POSTSTR_SZ)
1010 #define MENU_V_ITEMWIDTH(m) (MENU_V_SPADDING + (m)->width + MENU_V_SPADDING)
1013 static size_t menuitem_get_line(struct cfdisk
*cf
, size_t idx
)
1015 struct cfdisk_menu
*m
= cf
->menu
;
1018 if (!m
->page_sz
) /* small menu */
1019 return (ui_lines
- (cf
->menu
->nitems
+ 1)) / 2 + idx
;
1020 return (idx
% m
->page_sz
) + 1;
1024 size_t len
= MENU_H_ITEMWIDTH(m
) + MENU_H_BETWEEN
; /** item width */
1025 size_t items
= ui_cols
/ len
; /* items per line */
1029 return MENU_START_LINE
+ ((idx
/ items
));
1033 static int menuitem_get_column(struct cfdisk
*cf
, size_t idx
)
1035 if (cf
->menu
->vertical
) {
1036 size_t nc
= MENU_V_ITEMWIDTH(cf
->menu
);
1037 if ((size_t) ui_cols
<= nc
)
1039 return (ui_cols
- nc
) / 2;
1043 size_t len
= MENU_H_ITEMWIDTH(cf
->menu
) + MENU_H_BETWEEN
; /* item width */
1044 size_t items
= ui_cols
/ len
; /* items per line */
1045 size_t extra
= items
< cf
->menu
->nitems
? /* extra space on line */
1046 ui_cols
% len
: /* - multi-line menu */
1047 ui_cols
- (cf
->menu
->nitems
* len
); /* - one line menu */
1050 return 0; /* hmm... no space */
1052 extra
+= MENU_H_BETWEEN
; /* add padding after last item to extra */
1055 return (idx
* len
) + (extra
/ 2);
1056 return ((idx
% items
) * len
) + (extra
/ 2);
1060 static int menuitem_on_page(struct cfdisk
*cf
, size_t idx
)
1062 struct cfdisk_menu
*m
= cf
->menu
;
1064 if (m
->page_sz
== 0 ||
1065 m
->idx
/ m
->page_sz
== idx
/ m
->page_sz
)
1070 static struct cfdisk_menuitem
*menu_get_menuitem(struct cfdisk
*cf
, size_t idx
)
1072 struct cfdisk_menuitem
*d
;
1075 for (i
= 0, d
= cf
->menu
->items
; d
->name
; d
++) {
1076 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, d
->key
))
1085 static struct cfdisk_menuitem
*menu_get_menuitem_by_key(struct cfdisk
*cf
,
1086 int key
, size_t *idx
)
1088 struct cfdisk_menuitem
*d
;
1090 for (*idx
= 0, d
= cf
->menu
->items
; d
->name
; d
++) {
1091 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, d
->key
))
1101 static void ui_draw_menuitem(struct cfdisk
*cf
,
1102 struct cfdisk_menuitem
*d
,
1108 const size_t buf_sz
= 80 * MB_CUR_MAX
;
1109 int ln
, cl
, vert
= cf
->menu
->vertical
;
1111 if (!menuitem_on_page(cf
, idx
))
1112 return; /* no visible item */
1113 ln
= menuitem_get_line(cf
, idx
);
1114 cl
= menuitem_get_column(cf
, idx
);
1116 ptr
= buf
= xmalloc(buf_sz
);
1119 width
= cf
->menu
->width
+ MENU_V_SPADDING
;
1120 memset(ptr
, ' ', MENU_V_SPADDING
);
1121 ptr
+= MENU_V_SPADDING
;
1123 width
= MENU_H_SPADDING
+ cf
->menu
->width
+ MENU_H_SPADDING
;
1126 mbsalign(name
, ptr
, buf_sz
, &width
,
1127 vert
? MBS_ALIGN_LEFT
: MBS_ALIGN_CENTER
,
1130 DBG(MENU
, ul_debug("menuitem: cl=%d, ln=%d, item='%s'",
1134 mvaddch(ln
, cl
- 1, ACS_VLINE
);
1135 mvaddch(ln
, cl
+ MENU_V_ITEMWIDTH(cf
->menu
), ACS_VLINE
);
1138 if (cf
->menu
->idx
== idx
)
1142 mvprintw(ln
, cl
, "%s", buf
);
1144 mvprintw(ln
, cl
, "%s%s%s", MENU_H_PRESTR
, buf
, MENU_H_POSTSTR
);
1147 if (cf
->menu
->idx
== idx
) {
1150 ui_hint("%s", _(d
->desc
));
1154 static void ui_clean_menu(struct cfdisk
*cf
)
1158 struct cfdisk_menu
*m
= cf
->menu
;
1159 size_t ln
= menuitem_get_line(cf
, 0);
1162 lastline
= ln
+ (m
->page_sz
? m
->page_sz
: m
->nitems
);
1164 lastline
= menuitem_get_line(cf
, m
->nitems
);
1166 for (i
= ln
; i
<= lastline
; i
++) {
1169 DBG(MENU
, ul_debug("clean_menu: line %zu", i
));
1178 static void ui_draw_menu(struct cfdisk
*cf
)
1180 struct cfdisk_menuitem
*d
;
1181 struct cfdisk_menu
*m
;
1183 size_t ln
= menuitem_get_line(cf
, 0);
1189 DBG(MENU
, ul_debug("draw start"));
1195 nlines
= m
->page_sz
? m
->page_sz
: m
->nitems
;
1197 nlines
= menuitem_get_line(cf
, m
->nitems
);
1200 menu_update_ignore(cf
);
1202 while ((d
= menu_get_menuitem(cf
, i
)))
1203 ui_draw_menuitem(cf
, d
, i
++);
1206 size_t cl
= menuitem_get_column(cf
, 0);
1207 size_t curpg
= m
->page_sz
? m
->idx
/ m
->page_sz
: 0;
1209 /* corners and horizontal lines */
1210 mvaddch(ln
- 1, cl
- 1, ACS_ULCORNER
);
1211 mvaddch(ln
+ nlines
, cl
- 1, ACS_LLCORNER
);
1213 for (i
= 0; i
< MENU_V_ITEMWIDTH(m
); i
++) {
1214 mvaddch(ln
- 1, cl
+ i
, ACS_HLINE
);
1215 mvaddch(ln
+ nlines
, cl
+ i
, ACS_HLINE
);
1218 mvaddch(ln
- 1, cl
+ i
, ACS_URCORNER
);
1219 mvaddch(ln
+ nlines
, cl
+ i
, ACS_LRCORNER
);
1221 /* draw also lines around empty lines on last page */
1223 m
->nitems
/ m
->page_sz
== m
->idx
/ m
->page_sz
) {
1224 for (i
= m
->nitems
% m
->page_sz
+ 1; i
<= m
->page_sz
; i
++) {
1225 mvaddch(i
, cl
- 1, ACS_VLINE
);
1226 mvaddch(i
, cl
+ MENU_V_ITEMWIDTH(m
), ACS_VLINE
);
1231 mvprintw(ln
- 1, cl
, " %s ", m
->title
);
1235 mvaddch(ln
- 1, cl
+ MENU_V_ITEMWIDTH(m
) - 2, ACS_UARROW
);
1236 if (m
->page_sz
&& curpg
< m
->nitems
/ m
->page_sz
)
1237 mvaddch(ln
+ nlines
, cl
+ MENU_V_ITEMWIDTH(m
) - 2, ACS_DARROW
);
1240 DBG(MENU
, ul_debug("draw end."));
1243 inline static int extra_insert_pair(struct cfdisk_line
*l
, const char *name
, const char *data
)
1245 struct libscols_line
*lsl
;
1251 if (!data
|| !*data
)
1254 lsl
= scols_table_new_line(l
->extra
, NULL
);
1258 rc
= scols_line_set_data(lsl
, 0, name
);
1260 rc
= scols_line_set_data(lsl
, 1, data
);
1265 #ifndef HAVE_LIBMOUNT
1266 static char *get_mountpoint( struct cfdisk
*cf
__attribute__((unused
)),
1267 const char *tagname
__attribute__((unused
)),
1268 const char *tagdata
__attribute__((unused
)))
1273 static char *get_mountpoint(struct cfdisk
*cf
, const char *tagname
, const char *tagdata
)
1275 struct libmnt_fs
*fs
= NULL
;
1276 char *target
= NULL
;
1282 DBG(UI
, ul_debug("asking for mountpoint [%s=%s]", tagname
, tagdata
));
1285 cf
->mntcache
= mnt_new_cache();
1287 /* 1st try between mounted filesystems */
1289 cf
->mtab
= mnt_new_table();
1291 mnt_table_set_cache(cf
->mtab
, cf
->mntcache
);
1292 mnt_table_parse_mtab(cf
->mtab
, NULL
);
1297 fs
= mnt_table_find_tag(cf
->mtab
, tagname
, tagdata
, MNT_ITER_FORWARD
);
1302 cf
->fstab
= mnt_new_table();
1304 mnt_table_set_cache(cf
->fstab
, cf
->mntcache
);
1305 if (mnt_table_parse_fstab(cf
->fstab
, NULL
) != 0) {
1306 mnt_unref_table(cf
->fstab
);
1312 fs
= mnt_table_find_tag(cf
->fstab
, tagname
, tagdata
, MNT_ITER_FORWARD
);
1318 xasprintf(&target
, _("%s (mounted)"), mnt_fs_get_target(fs
));
1320 target
= xstrdup(mnt_fs_get_target(fs
));
1325 #endif /* HAVE_LIBMOUNT */
1327 static inline int iszero(const char *str
)
1331 for (p
= str
; p
&& *p
== '0'; p
++);
1333 return !p
|| *p
== '\0';
1336 static int has_uuid(struct fdisk_table
*tb
, const char *uuid
)
1338 struct fdisk_partition
*pa
;
1339 struct fdisk_iter
*itr
;
1342 if (!tb
|| !uuid
|| fdisk_table_is_empty(tb
))
1345 itr
= fdisk_new_iter(FDISK_ITER_FORWARD
);
1346 while (rc
== 0 && fdisk_table_next_partition(tb
, itr
, &pa
) == 0) {
1347 const char *x
= fdisk_partition_get_uuid(pa
);
1349 rc
= strcmp(x
, uuid
) == 0;
1351 fdisk_free_iter(itr
);
1355 static void extra_prepare_data(struct cfdisk
*cf
)
1357 struct fdisk_partition
*pa
= get_current_partition(cf
);
1358 struct cfdisk_line
*l
= &cf
->lines
[cf
->lines_idx
];
1360 char *mountpoint
= NULL
;
1362 DBG(UI
, ul_debug("preparing extra data"));
1364 /* string data should not equal an empty string */
1365 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_NAME
, &data
) && data
) {
1366 extra_insert_pair(l
, _("Partition name:"), data
);
1368 mountpoint
= get_mountpoint(cf
, "PARTLABEL", data
);
1372 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_UUID
, &data
) && data
) {
1373 extra_insert_pair(l
, _("Partition UUID:"), data
);
1375 /* Search for mountpoint by PARTUUID= means that we need to
1376 * check fstab and convert PARTUUID to the device name. This is
1377 * unnecessary and overkill for newly created partitions. Let's
1378 * check if the UUID already exist in the old layout, otherwise
1381 if (!mountpoint
&& has_uuid(cf
->original_layout
, data
))
1382 mountpoint
= get_mountpoint(cf
, "PARTUUID", data
);
1386 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_TYPE
, &data
) && data
) {
1387 char *code
= NULL
, *type
= NULL
;
1389 fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_TYPEID
, &code
);
1390 xasprintf(&type
, "%s (%s)", data
, code
);
1392 extra_insert_pair(l
, _("Partition type:"), type
);
1398 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_ATTR
, &data
) && data
) {
1399 extra_insert_pair(l
, _("Attributes:"), data
);
1403 /* for numeric data, only show non-zero rows */
1404 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_BSIZE
, &data
) && data
) {
1406 extra_insert_pair(l
, "BSIZE:", data
);
1410 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_CPG
, &data
) && data
) {
1412 extra_insert_pair(l
, "CPG:", data
);
1416 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSIZE
, &data
) && data
) {
1418 extra_insert_pair(l
, "FSIZE:", data
);
1422 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSUUID
, &data
) && data
) {
1423 extra_insert_pair(l
, _("Filesystem UUID:"), data
);
1425 mountpoint
= get_mountpoint(cf
, "UUID", data
);
1429 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSLABEL
, &data
) && data
) {
1430 extra_insert_pair(l
, _("Filesystem LABEL:"), data
);
1432 mountpoint
= get_mountpoint(cf
, "LABEL", data
);
1435 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSTYPE
, &data
) && data
) {
1436 extra_insert_pair(l
, _("Filesystem:"), data
);
1441 extra_insert_pair(l
, _("Mountpoint:"), mountpoint
);
1446 static int ui_draw_extra(struct cfdisk
*cf
)
1450 struct cfdisk_line
*ln
= &cf
->lines
[cf
->lines_idx
];
1451 char *tbstr
= NULL
, *end
;
1452 int win_ex_start_line
, win_height
, tblen
;
1455 if (!cf
->show_extra
)
1458 DBG(UI
, ul_debug("draw extra"));
1463 wclear(cf
->act_win
);
1467 if (scols_table_is_empty(ln
->extra
)) {
1468 extra_prepare_data(cf
);
1469 if (scols_table_is_empty(ln
->extra
))
1473 ndatalines
= fdisk_table_get_nents(cf
->table
) + 1;
1475 /* nents + header + one free line */
1476 win_ex_start_line
= TABLE_START_LINE
+ ndatalines
;
1477 win_height
= MENU_START_LINE
- win_ex_start_line
;
1478 tblen
= scols_table_get_nlines(ln
->extra
);
1480 /* we can't get a single line of data under the partlist*/
1484 /* number of data lines + 2 for top/bottom lines */
1485 win_height
= win_height
< tblen
+ 2 ? win_height
: tblen
+ 2;
1487 if ((size_t) win_ex_start_line
+ win_height
+ 1 < MENU_START_LINE
)
1488 win_ex_start_line
= MENU_START_LINE
- win_height
;
1490 win_ex
= subwin(stdscr
, win_height
, ui_cols
- 2, win_ex_start_line
, 1);
1492 scols_table_reduce_termwidth(ln
->extra
, 4);
1493 scols_print_table_to_string(ln
->extra
, &tbstr
);
1496 while ((end
= strchr(end
, '\n')))
1502 while (--win_height
> 1) {
1503 mvwaddstr(win_ex
, wline
++, 1 /* window column*/, tbstr
);
1504 tbstr
+= strlen(tbstr
) + 1;
1511 DBG(UI
, ul_debug("draw window: %p", win_ex
));
1515 cf
->act_win
= ln
->w
= win_ex
;
1519 static void ui_menu_goto(struct cfdisk
*cf
, int where
)
1521 struct cfdisk_menuitem
*d
;
1524 /* stop and begin/end for vertical menus */
1525 if (cf
->menu
->vertical
) {
1528 else if (where
> (int) cf
->menu
->nitems
- 1)
1529 where
= cf
->menu
->nitems
- 1;
1531 /* continue from begin/end */
1533 where
= cf
->menu
->nitems
- 1;
1534 else if ((size_t) where
> cf
->menu
->nitems
- 1)
1537 if ((size_t) where
== cf
->menu
->idx
)
1542 old
= cf
->menu
->idx
;
1543 cf
->menu
->idx
= where
;
1545 if (!menuitem_on_page(cf
, old
)) {
1550 d
= menu_get_menuitem(cf
, old
);
1551 ui_draw_menuitem(cf
, d
, old
);
1553 d
= menu_get_menuitem(cf
, where
);
1554 ui_draw_menuitem(cf
, d
, where
);
1558 static int ui_menu_move(struct cfdisk
*cf
, int key
)
1560 struct cfdisk_menu
*m
;
1565 if (key
== (int) ERR
)
1566 return 0; /* ignore errors */
1570 DBG(MENU
, ul_debug("menu move key >%c<.", key
));
1576 case '\016': /* ^N */
1577 case 'j': /* Vi-like alternative */
1578 ui_menu_goto(cf
, m
->idx
+ 1);
1581 case '\020': /* ^P */
1582 case 'k': /* Vi-like alternative */
1583 ui_menu_goto(cf
, (int) m
->idx
- 1);
1587 ui_menu_goto(cf
, (int) m
->idx
- m
->page_sz
);
1592 ui_menu_goto(cf
, 0);
1596 ui_menu_goto(cf
, m
->idx
+ m
->page_sz
);
1601 ui_menu_goto(cf
, m
->nitems
);
1608 ui_menu_goto(cf
, m
->idx
+ 1);
1614 ui_menu_goto(cf
, (int) m
->idx
- 1);
1619 if (key
== '\014') { /* ^L refresh */
1624 DBG(MENU
, ul_debug(" no menu move key"));
1628 /* but don't call me from ui_run(), this is for pop-up menus only */
1629 static void ui_menu_resize(struct cfdisk
*cf
)
1631 DBG(MENU
, ul_debug("menu resize/refresh"));
1634 menu_refresh_size(cf
);
1639 static int partition_on_page(struct cfdisk
*cf
, size_t i
)
1641 if (cf
->page_sz
== 0 ||
1642 cf
->lines_idx
/ cf
->page_sz
== i
/ cf
->page_sz
)
1647 static void ui_draw_partition(struct cfdisk
*cf
, size_t i
)
1649 int ln
= TABLE_START_LINE
+ 1 + i
; /* skip table header */
1650 int cl
= ARROW_CURSOR_WIDTH
; /* we need extra space for cursor */
1651 int cur
= cf
->lines_idx
== i
;
1655 if (!partition_on_page(cf
, i
))
1657 ln
= TABLE_START_LINE
+ (i
% cf
->page_sz
) + 1;
1658 curpg
= cf
->lines_idx
/ cf
->page_sz
;
1662 "draw partition %zu [page_sz=%zu, "
1663 "line=%d, idx=%zu]",
1664 i
, cf
->page_sz
, ln
, cf
->lines_idx
));
1668 mvaddstr(ln
, 0, ARROW_CURSOR_STRING
);
1669 mvaddstr(ln
, cl
, cf
->lines
[i
+ 1].data
);
1674 if (colors_wanted() && is_freespace(cf
, i
)) {
1675 attron(COLOR_PAIR(CFDISK_CL_FREESPACE
));
1678 mvaddstr(ln
, 0, ARROW_CURSOR_DUMMY
);
1679 mvaddstr(ln
, cl
, cf
->lines
[i
+ 1].data
);
1681 attroff(COLOR_PAIR(CFDISK_CL_FREESPACE
));
1684 if ((size_t) ln
== MENU_START_LINE
- 1 &&
1685 cf
->page_sz
&& curpg
< cf
->nlines
/ cf
->page_sz
) {
1688 mvaddch(ln
, ui_cols
- 1, ACS_DARROW
);
1689 mvaddch(ln
, 0, ACS_DARROW
);
1696 static int ui_draw_table(struct cfdisk
*cf
)
1698 int cl
= ARROW_CURSOR_WIDTH
;
1699 size_t i
, nparts
= fdisk_table_get_nents(cf
->table
);
1700 size_t curpg
= cf
->page_sz
? cf
->lines_idx
/ cf
->page_sz
: 0;
1702 DBG(UI
, ul_debug("draw table"));
1704 for (i
= TABLE_START_LINE
; i
<= TABLE_START_LINE
+ cf
->page_sz
; i
++) {
1709 if (nparts
== 0 || (size_t) cf
->lines_idx
> nparts
- 1)
1710 cf
->lines_idx
= nparts
? nparts
- 1 : 0;
1714 mvaddstr(TABLE_START_LINE
, cl
, cf
->lines
[0].data
);
1717 /* print partitions */
1718 for (i
= 0; i
< nparts
; i
++)
1719 ui_draw_partition(cf
, i
);
1722 mvaddch(TABLE_START_LINE
, ui_cols
- 1, ACS_UARROW
);
1723 mvaddch(TABLE_START_LINE
, 0, ACS_UARROW
);
1725 if (cf
->page_sz
&& curpg
< cf
->nlines
/ cf
->page_sz
) {
1726 mvaddch(MENU_START_LINE
- 1, ui_cols
- 1, ACS_DARROW
);
1727 mvaddch(MENU_START_LINE
- 1, 0, ACS_DARROW
);
1732 static int ui_table_goto(struct cfdisk
*cf
, int where
)
1735 size_t nparts
= fdisk_table_get_nents(cf
->table
);
1737 DBG(UI
, ul_debug("goto table %d", where
));
1741 else if ((size_t) where
> nparts
- 1)
1744 if ((size_t) where
== cf
->lines_idx
)
1747 old
= cf
->lines_idx
;
1748 cf
->lines_idx
= where
;
1750 if (!partition_on_page(cf
, old
) ||!partition_on_page(cf
, where
))
1753 ui_draw_partition(cf
, old
); /* cleanup old */
1754 ui_draw_partition(cf
, where
); /* draw new */
1764 static int ui_refresh(struct cfdisk
*cf
)
1766 struct fdisk_label
*lb
;
1768 uint64_t bytes
= fdisk_get_nsectors(cf
->cxt
) * fdisk_get_sector_size(cf
->cxt
);
1774 strsz
= size_to_human_string(SIZE_DECIMAL_2DIGITS
1776 | SIZE_SUFFIX_3LETTER
, bytes
);
1778 lb
= fdisk_get_label(cf
->cxt
, NULL
);
1785 ui_center(0, _("Disk: %s"), fdisk_get_devname(cf
->cxt
));
1787 ui_center(1, _("Size: %s, %"PRIu64
" bytes, %ju sectors"),
1788 strsz
, bytes
, (uintmax_t) fdisk_get_nsectors(cf
->cxt
));
1789 if (fdisk_get_disklabel_id(cf
->cxt
, &id
) == 0 && id
)
1790 ui_center(2, _("Label: %s, identifier: %s"),
1791 fdisk_label_get_name(lb
), id
);
1793 ui_center(2, _("Label: %s"), fdisk_label_get_name(lb
));
1803 static ssize_t
ui_get_string(const char *prompt
,
1804 const char *hint
, char *buf
, size_t len
)
1806 int ln
= MENU_START_LINE
, cl
= 1;
1808 struct mbs_editor
*edit
;
1810 DBG(UI
, ul_debug("ui get string"));
1822 mvaddstr(ln
, cl
, prompt
);
1823 cl
+= mbs_safe_width(prompt
);
1826 edit
= mbs_new_edit(buf
, len
, ui_cols
- cl
);
1830 mbs_edit_goto(edit
, MBS_EDIT_END
);
1833 ui_hint("%s", hint
);
1840 wint_t c
; /* we have fallback in widechar.h */
1844 mvaddstr(ln
, cl
, edit
->buf
);
1845 move(ln
, cl
+ edit
->cursor_cells
);
1848 #if !defined(HAVE_SLCURSES_H) && !defined(HAVE_SLANG_SLCURSES_H) && \
1849 defined(HAVE_LIBNCURSESW) && defined(HAVE_WIDECHAR)
1850 if (get_wch(&c
) == ERR
) {
1852 if ((c
= getch()) == (wint_t) ERR
) {
1860 if (!isatty(STDIN_FILENO
))
1866 DBG(UI
, ul_debug("ui get string: key=%lc", c
));
1868 if (c
== '\r' || c
== '\n' || c
== KEY_ENTER
)
1875 rc
= -CFDISK_ERR_ESC
;
1878 rc
= mbs_edit_goto(edit
, MBS_EDIT_LEFT
);
1881 rc
= mbs_edit_goto(edit
, MBS_EDIT_RIGHT
);
1884 rc
= mbs_edit_goto(edit
, MBS_EDIT_END
);
1887 rc
= mbs_edit_goto(edit
, MBS_EDIT_HOME
);
1893 rc
= mbs_edit_delete(edit
);
1898 rc
= mbs_edit_backspace(edit
);
1901 rc
= mbs_edit_insert(edit
, c
);
1911 rc
= strlen(edit
->buf
); /* success */
1917 mbs_free_edit(edit
);
1922 static int ui_get_size(struct cfdisk
*cf
, /* context */
1923 const char *prompt
, /* UI dialog string */
1924 uint64_t *res
, /* result in bytes */
1925 uint64_t low
, /* minimal size */
1926 uint64_t up
, /* maximal size */
1927 int *expsize
) /* explicitly specified size */
1932 char *dflt
= size_to_human_string(0, *res
);
1934 DBG(UI
, ul_debug("get_size (default=%"PRIu64
")", *res
));
1938 snprintf(buf
, sizeof(buf
), "%s", dflt
);
1941 int pwr
= 0, insec
= 0;
1943 rc
= ui_get_string(prompt
,
1944 _("May be followed by M for MiB, G for GiB, "
1945 "T for TiB, or S for sectors."),
1950 ui_warnx(_("Please, specify size."));
1951 continue; /* nothing specified */
1952 } if (rc
== -CFDISK_ERR_ESC
)
1953 break; /* cancel dialog */
1955 if (strcmp(buf
, dflt
) == 0)
1956 user
= *res
, rc
= 0; /* no change, use default */
1958 size_t len
= strlen(buf
);
1959 if (buf
[len
- 1] == 'S' || buf
[len
- 1] == 's') {
1961 buf
[len
- 1] = '\0';
1963 rc
= parse_size(buf
, (uintmax_t *)&user
, &pwr
); /* parse */
1967 DBG(UI
, ul_debug("get_size user=%"PRIu64
", power=%d, in-sectors=%s",
1968 user
, pwr
, insec
? "yes" : "no"));
1970 user
*= fdisk_get_sector_size(cf
->cxt
);
1972 ui_warnx(_("Minimum size is %"PRIu64
" bytes."), low
);
1975 if (user
> up
&& pwr
&& user
< up
+ (1ULL << pwr
* 10))
1976 /* ignore when the user specified size overflow
1977 * with in range specified by suffix (e.g. MiB) */
1981 ui_warnx(_("Maximum size is %"PRIu64
" bytes."), up
);
1984 if (rc
== 0 && insec
&& expsize
)
1988 ui_warnx(_("Failed to parse size."));
1995 DBG(UI
, ul_debug("get_size (result=%"PRIu64
", rc=%zd)", *res
, rc
));
1999 static struct fdisk_parttype
*ui_get_parttype(struct cfdisk
*cf
,
2000 struct fdisk_parttype
*cur
)
2002 struct cfdisk_menuitem
*d
, *cm
;
2003 size_t i
= 0, nitems
, idx
= 0;
2004 struct fdisk_parttype
*t
= NULL
;
2005 struct fdisk_label
*lb
;
2008 DBG(UI
, ul_debug("asking for parttype."));
2010 lb
= fdisk_get_label(cf
->cxt
, NULL
);
2012 /* create cfdisk menu according to label types, note that the
2013 * last cm[] item has to be empty -- so nitems + 1 */
2014 nitems
= fdisk_label_get_nparttypes(lb
);
2018 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
2022 codetypes
= fdisk_label_has_code_parttypes(lb
);
2024 for (i
= 0; i
< nitems
; i
++) {
2025 const struct fdisk_parttype
*x
= fdisk_label_get_parttype(lb
, i
);
2028 cm
[i
].userdata
= (void *) x
;
2030 xasprintf(&name
, "%2x %s",
2031 fdisk_parttype_get_code(x
),
2032 _(fdisk_parttype_get_name(x
)));
2034 name
= (char *) _(fdisk_parttype_get_name(x
));
2035 cm
[i
].desc
= fdisk_parttype_get_string(x
);
2042 /* make the new menu active */
2044 cf
->menu
->vertical
= 1;
2045 cf
->menu
->idx
= idx
;
2046 menu_set_title(cf
->menu
, _("Select partition type"));
2057 if (ui_menu_move(cf
, key
) == 0)
2064 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2066 t
= (struct fdisk_parttype
*) d
->userdata
;
2080 for (i
= 0; i
< nitems
; i
++)
2081 free((char *) cm
[i
].name
);
2084 DBG(UI
, ul_debug("get parrtype done [type=%s] ", t
?
2085 fdisk_parttype_get_name(t
) : ""));
2089 static int ui_script_read(struct cfdisk
*cf
)
2091 struct fdisk_script
*sc
= NULL
;
2092 char buf
[PATH_MAX
] = { 0 };
2096 rc
= ui_get_string( _("Enter script file name: "),
2097 _("The script file will be applied to in-memory partition table."),
2104 sc
= fdisk_new_script_from_file(cf
->cxt
, buf
);
2106 ui_warn(_("Cannot open %s"), buf
);
2108 ui_warnx(_("Failed to parse script file %s"), buf
);
2109 else if (fdisk_apply_script(cf
->cxt
, sc
) != 0)
2110 ui_warnx(_("Failed to apply script %s"), buf
);
2115 fdisk_unref_script(sc
);
2119 static int ui_script_write(struct cfdisk
*cf
)
2121 struct fdisk_script
*sc
= NULL
;
2122 char buf
[PATH_MAX
] = { 0 };
2126 rc
= ui_get_string( _("Enter script file name: "),
2127 _("The current in-memory partition table will be dumped to the file."),
2133 sc
= fdisk_new_script(cf
->cxt
);
2135 ui_warn(_("Failed to allocate script handler"));
2139 rc
= fdisk_script_read_context(sc
, NULL
);
2141 ui_warnx(_("Failed to read disk layout into script."));
2145 DBG(UI
, ul_debug("writing dump into: '%s'", buf
));
2146 f
= fopen(buf
, "w");
2148 ui_warn(_("Cannot open %s"), buf
);
2153 rc
= fdisk_script_write_file(sc
, f
);
2155 ui_info(_("Disk layout successfully dumped."));
2158 ui_warn(_("Failed to write script %s"), buf
);
2161 fdisk_unref_script(sc
);
2165 /* prints menu with libfdisk labels and waits for users response */
2166 static int ui_create_label(struct cfdisk
*cf
)
2168 struct cfdisk_menuitem
*d
, *cm
;
2169 int rc
= 1, refresh_menu
= 1;
2170 size_t i
= 0, nitems
;
2171 struct fdisk_label
*lb
= NULL
;
2175 DBG(UI
, ul_debug("asking for new disklabe."));
2177 /* create cfdisk menu according to libfdisk labels, note that the
2178 * last cm[] item has to be empty -- so nitems + 1 */
2179 nitems
= fdisk_get_nlabels(cf
->cxt
);
2180 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
2182 while (fdisk_next_label(cf
->cxt
, &lb
) == 0) {
2183 if (fdisk_label_is_disabled(lb
) ||
2184 fdisk_label_get_type(lb
) == FDISK_DISKLABEL_BSD
)
2186 cm
[i
++].name
= fdisk_label_get_name(lb
);
2191 /* make the new menu active */
2193 cf
->menu
->vertical
= 1;
2194 menu_set_title(cf
->menu
, _("Select label type"));
2196 if (!cf
->zero_start
)
2197 ui_info(_("Device does not contain a recognized partition table."));
2205 ui_hint(_("Select a type to create a new label, press 'L' to load script file, 'Q' quits."));
2216 if (ui_menu_move(cf
, key
) == 0)
2222 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2224 rc
= fdisk_create_disklabel(cf
->cxt
, d
->name
);
2232 rc
= ui_script_read(cf
);
2245 DBG(UI
, ul_debug("create label done [rc=%d] ", rc
));
2250 static int ui_help(void)
2253 static const char *help
[] = {
2254 N_("This is cfdisk, a curses-based disk partitioning program."),
2255 N_("It lets you create, delete, and modify partitions on a block device."),
2257 N_("Command Meaning"),
2258 N_("------- -------"),
2259 N_(" b Toggle bootable flag of the current partition"),
2260 N_(" d Delete the current partition"),
2261 N_(" h Print this screen"),
2262 N_(" n Create new partition from free space"),
2263 N_(" q Quit program without writing partition table"),
2264 N_(" r Reduce or enlarge the current partition"),
2265 N_(" s Fix partitions order (only when in disarray)"),
2266 N_(" t Change the partition type"),
2267 N_(" u Dump disk layout to sfdisk compatible script file"),
2268 N_(" W Write partition table to disk (you must enter uppercase W);"),
2269 N_(" since this might destroy data on the disk, you must either"),
2270 N_(" confirm or deny the write by entering 'yes' or 'no'"),
2271 N_(" x Display/hide extra information about a partition"),
2272 N_("Up Arrow Move cursor to the previous partition"),
2273 N_("Down Arrow Move cursor to the next partition"),
2274 N_("Left Arrow Move cursor to the previous menu item"),
2275 N_("Right Arrow Move cursor to the next menu item"),
2277 N_("Note: All of the commands can be entered with either upper or lower"),
2278 N_("case letters (except for Write)."),
2280 N_("Use lsblk(8) or partx(8) to see more details about the device."),
2283 "Copyright (C) 2014-2017 Karel Zak <kzak@redhat.com>"
2287 for (i
= 0; i
< ARRAY_SIZE(help
); i
++)
2288 mvaddstr(i
, 1, _(help
[i
]));
2290 ui_info(_("Press a key to continue."));
2299 /* TODO: use @sz, now 128bytes */
2300 static int main_menu_ignore_keys(struct cfdisk
*cf
, char *ignore
,
2301 size_t sz
__attribute__((__unused__
)))
2303 struct fdisk_partition
*pa
= get_current_partition(cf
);
2308 if (fdisk_partition_is_freespace(pa
)) {
2309 ignore
[i
++] = 'd'; /* delete */
2310 ignore
[i
++] = 't'; /* set type */
2311 ignore
[i
++] = 'b'; /* set bootable */
2312 ignore
[i
++] = 'r'; /* resize */
2313 cf
->menu
->prefkey
= 'n';
2315 cf
->menu
->prefkey
= 'q';
2317 if (!fdisk_is_label(cf
->cxt
, DOS
) &&
2318 !fdisk_is_label(cf
->cxt
, SGI
))
2322 if (!cf
->wrong_order
)
2325 if (fdisk_is_readonly(cf
->cxt
))
2332 /* returns: error: < 0, success: 0, quit: 1 */
2333 static int main_menu_action(struct cfdisk
*cf
, int key
)
2336 int ref
= 0, rc
, org_order
= cf
->wrong_order
;
2337 const char *info
= NULL
, *warn
= NULL
;
2338 struct fdisk_partition
*pa
;
2345 struct cfdisk_menuitem
*d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2350 } else if (key
!= 'w' && key
!= 'W')
2351 key
= tolower(key
); /* case insensitive except 'W'rite */
2353 DBG(MENU
, ul_debug("main menu action: key=%c", key
));
2355 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, key
)) {
2356 DBG(MENU
, ul_debug(" ignore '%c'", key
));
2360 pa
= get_current_partition(cf
);
2363 n
= fdisk_partition_get_partno(pa
);
2365 DBG(MENU
, ul_debug("menu action on %p", pa
));
2370 case 'b': /* Bootable flag */
2372 int fl
= fdisk_is_label(cf
->cxt
, DOS
) ? DOS_FLAG_ACTIVE
:
2373 fdisk_is_label(cf
->cxt
, SGI
) ? SGI_FLAG_BOOT
: 0;
2375 if (fl
&& fdisk_toggle_partition_flag(cf
->cxt
, n
, fl
))
2376 warn
= _("Could not toggle the flag.");
2384 case 'd': /* Delete */
2385 if (fdisk_delete_partition(cf
->cxt
, n
) != 0)
2386 warn
= _("Could not delete partition %zu.");
2388 info
= _("Partition %zu has been deleted.");
2391 case 'h': /* Help */
2398 uint64_t start
, size
, dflt_size
, secs
, max_size
;
2399 struct fdisk_partition
*npa
; /* the new partition */
2400 int expsize
= 0; /* size specified explicitly in sectors */
2402 if (!fdisk_partition_is_freespace(pa
) || !fdisk_partition_has_start(pa
))
2405 /* free space range */
2406 start
= fdisk_partition_get_start(pa
);
2407 size
= max_size
= dflt_size
= fdisk_partition_get_size(pa
) * fdisk_get_sector_size(cf
->cxt
);
2409 if (ui_get_size(cf
, _("Partition size: "), &size
,
2410 fdisk_get_sector_size(cf
->cxt
),
2411 max_size
, &expsize
) == -CFDISK_ERR_ESC
)
2414 secs
= size
/ fdisk_get_sector_size(cf
->cxt
);
2416 npa
= fdisk_new_partition();
2420 if (dflt_size
== size
) /* default is to fillin all free space */
2421 fdisk_partition_end_follow_default(npa
, 1);
2423 fdisk_partition_set_size(npa
, secs
);
2426 fdisk_partition_size_explicit(pa
, 1);
2428 fdisk_partition_set_start(npa
, start
);
2429 fdisk_partition_partno_follow_default(npa
, 1);
2430 /* add to disk label -- libfdisk will ask for missing details */
2431 rc
= fdisk_add_partition(cf
->cxt
, npa
, NULL
);
2432 fdisk_unref_partition(npa
);
2437 case 'q': /* Quit */
2439 case 't': /* Type */
2441 struct fdisk_parttype
*t
;
2443 if (fdisk_partition_is_freespace(pa
))
2445 t
= (struct fdisk_parttype
*) fdisk_partition_get_type(pa
);
2446 t
= ui_get_parttype(cf
, t
);
2449 if (t
&& fdisk_set_partition_type(cf
->cxt
, n
, t
) == 0)
2450 info
= _("Changed type of partition %zu.");
2452 info
= _("The type of partition %zu is unchanged.");
2455 case 'r': /* resize */
2457 struct fdisk_partition
*npa
, *next
;
2458 uint64_t size
, max_size
, secs
;
2460 if (fdisk_partition_is_freespace(pa
) || !fdisk_partition_has_start(pa
))
2463 size
= fdisk_partition_get_size(pa
);
2465 /* is the next freespace? */
2466 next
= fdisk_table_get_partition(cf
->table
, cf
->lines_idx
+ 1);
2467 if (next
&& fdisk_partition_is_freespace(next
))
2468 size
+= fdisk_partition_get_size(next
);
2470 size
*= fdisk_get_sector_size(cf
->cxt
);
2473 if (ui_get_size(cf
, _("New size: "), &size
,
2474 fdisk_get_sector_size(cf
->cxt
),
2475 max_size
, NULL
) == -CFDISK_ERR_ESC
)
2477 secs
= size
/ fdisk_get_sector_size(cf
->cxt
);
2478 npa
= fdisk_new_partition();
2482 fdisk_partition_set_size(npa
, secs
);
2484 rc
= fdisk_set_partition(cf
->cxt
, n
, npa
);
2485 fdisk_unref_partition(npa
);
2488 info
= _("Partition %zu resized.");
2492 case 's': /* Sort */
2493 if (cf
->wrong_order
) {
2494 fdisk_reorder_partitions(cf
->cxt
);
2498 case 'u': /* dUmp */
2499 ui_script_write(cf
);
2501 case 'W': /* Write */
2503 char buf
[64] = { 0 };
2505 if (fdisk_is_readonly(cf
->cxt
)) {
2506 warn
= _("Device is open in read-only mode.");
2511 _("Are you sure you want to write the partition "
2513 _("Type \"yes\" or \"no\", or press ESC to leave this dialog."),
2517 if (rc
<= 0 || (strcasecmp(buf
, "yes") != 0 &&
2518 strcasecmp(buf
, _("yes")) != 0)) {
2519 info
= _("Did not write partition table to disk.");
2522 rc
= fdisk_write_disklabel(cf
->cxt
);
2524 warn
= _("Failed to write disklabel.");
2526 if (cf
->device_is_used
)
2527 fdisk_reread_changes(cf
->cxt
, cf
->original_layout
);
2529 fdisk_reread_partition_table(cf
->cxt
);
2530 info
= _("The partition table has been altered.");
2549 ui_warnx(warn
, n
+ 1);
2551 ui_info(info
, n
+ 1);
2552 else if (key
== 'n' && cf
->wrong_order
&& org_order
== 0)
2553 ui_info(_("Note that partition table entries are not in disk order now."));
2558 static void ui_resize_refresh(struct cfdisk
*cf
)
2560 DBG(UI
, ul_debug("ui resize/refresh"));
2562 menu_refresh_size(cf
);
2568 static void toggle_show_extra(struct cfdisk
*cf
)
2570 if (cf
->show_extra
&& cf
->act_win
) {
2571 wclear(cf
->act_win
);
2574 cf
->show_extra
= cf
->show_extra
? 0 : 1;
2578 DBG(MENU
, ul_debug("extra: %s", cf
->show_extra
? "ENABLED" : "DISABLED" ));
2581 static int ui_run(struct cfdisk
*cf
)
2587 DBG(UI
, ul_debug("start cols=%zu, lines=%zu", ui_cols
, ui_lines
));
2589 if (fdisk_get_collision(cf
->cxt
)) {
2590 ui_warnx(_("Device already contains a %s signature; it will be removed by a write command."),
2591 fdisk_get_collision(cf
->cxt
));
2592 fdisk_enable_wipe(cf
->cxt
, 1);
2593 ui_hint(_("Press a key to continue."));
2597 if (!fdisk_has_label(cf
->cxt
) || cf
->zero_start
) {
2598 rc
= ui_create_label(cf
);
2601 ui_err(EXIT_FAILURE
,
2602 _("failed to create a new disklabel"));
2609 rc
= lines_refresh(cf
);
2611 ui_errx(EXIT_FAILURE
, _("failed to read partitions"));
2613 menu_push(cf
, main_menuitems
);
2614 cf
->menu
->ignore_cb
= main_menu_ignore_keys
;
2616 rc
= ui_refresh(cf
);
2623 if (fdisk_is_readonly(cf
->cxt
))
2624 ui_warnx(_("Device is open in read-only mode. Changes will remain in memory only."));
2625 else if (cf
->device_is_used
)
2626 ui_warnx(_("Device is currently in use, repartitioning is probably a bad idea."));
2627 else if (cf
->wrong_order
)
2628 ui_info(_("Note that partition table entries are not in disk order now."));
2638 /* Note that ncurses getch() returns ERR when interrupted
2639 * by signal, but SLang does not interrupt at all. */
2640 ui_resize_refresh(cf
);
2643 if (key
== '\014') { /* ^L refresh */
2644 ui_resize_refresh(cf
);
2647 if (ui_menu_move(cf
, key
) == 0)
2650 DBG(UI
, ul_debug("main action key >%1$c< [\\0%1$o].", key
));
2654 case '\016': /* ^N */
2655 case 'j': /* Vi-like alternative */
2656 ui_table_goto(cf
, cf
->lines_idx
+ 1);
2659 case '\020': /* ^P */
2660 case 'k': /* Vi-like alternative */
2661 ui_table_goto(cf
, (int) cf
->lines_idx
- 1);
2665 ui_table_goto(cf
, (int) cf
->lines_idx
- cf
->page_sz
);
2670 ui_table_goto(cf
, 0);
2674 ui_table_goto(cf
, cf
->lines_idx
+ cf
->page_sz
);
2679 ui_table_goto(cf
, (int) cf
->nlines
- 1);
2684 rc
= main_menu_action(cf
, 0);
2687 case 'x': /* Extra */
2688 toggle_show_extra(cf
);
2691 rc
= main_menu_action(cf
, key
);
2703 DBG(UI
, ul_debug("end"));
2707 static void __attribute__((__noreturn__
)) usage(void)
2710 fputs(USAGE_HEADER
, out
);
2712 _(" %1$s [options] <disk>\n"), program_invocation_short_name
);
2714 fputs(USAGE_SEPARATOR
, out
);
2715 fputs(_("Display or manipulate a disk partition table.\n"), out
);
2717 fputs(USAGE_OPTIONS
, out
);
2719 _(" -L, --color[=<when>] colorize output (%s, %s or %s)\n"), "auto", "always", "never");
2721 " %s\n", USAGE_COLORS_DEFAULT
);
2722 fputs(_(" -z, --zero start with zeroed partition table\n"), out
);
2724 _(" --lock[=<mode>] use exclusive device lock (%s, %s or %s)\n"), "yes", "no", "nonblock");
2725 fputs(_(" -r, --read-only forced open cfdisk in read-only mode\n"), out
);
2727 fputs(USAGE_SEPARATOR
, out
);
2728 printf(USAGE_HELP_OPTIONS(26));
2730 printf(USAGE_MAN_TAIL("cfdisk(8)"));
2734 int main(int argc
, char *argv
[])
2736 const char *diskpath
= NULL
, *lockmode
= NULL
;
2737 int rc
, c
, colormode
= UL_COLORMODE_UNDEF
;
2739 struct cfdisk _cf
= { .lines_idx
= 0 },
2742 OPT_LOCK
= CHAR_MAX
+ 1
2744 static const struct option longopts
[] = {
2745 { "color", optional_argument
, NULL
, 'L' },
2746 { "lock", optional_argument
, NULL
, OPT_LOCK
},
2747 { "help", no_argument
, NULL
, 'h' },
2748 { "version", no_argument
, NULL
, 'V' },
2749 { "zero", no_argument
, NULL
, 'z' },
2750 { "read-only", no_argument
, NULL
, 'r' },
2751 { NULL
, 0, NULL
, 0 },
2754 setlocale(LC_ALL
, "");
2755 bindtextdomain(PACKAGE
, LOCALEDIR
);
2756 textdomain(PACKAGE
);
2757 close_stdout_atexit();
2759 while((c
= getopt_long(argc
, argv
, "L::hVzr", longopts
, NULL
)) != -1) {
2765 colormode
= UL_COLORMODE_AUTO
;
2767 colormode
= colormode_or_err(optarg
,
2768 _("unsupported color mode"));
2774 print_version(EXIT_SUCCESS
);
2787 errtryhelp(EXIT_FAILURE
);
2791 colors_init(colormode
, "cfdisk");
2793 fdisk_init_debug(0);
2794 scols_init_debug(0);
2795 cfdisk_init_debug();
2796 cf
->cxt
= fdisk_new_context();
2798 err(EXIT_FAILURE
, _("failed to allocate libfdisk context"));
2800 fdisk_set_ask(cf
->cxt
, ask_callback
, (void *) cf
);
2802 if (optind
== argc
) {
2805 for (i
= 0; i
< ARRAY_SIZE(default_disks
); i
++) {
2806 if (access(default_disks
[i
], F_OK
) == 0) {
2807 diskpath
= default_disks
[i
];
2812 diskpath
= default_disks
[0]; /* default, used for "cannot open" */
2814 diskpath
= argv
[optind
];
2816 rc
= fdisk_assign_device(cf
->cxt
, diskpath
, read_only
);
2817 if (rc
== -EACCES
&& read_only
== 0)
2818 rc
= fdisk_assign_device(cf
->cxt
, diskpath
, 1);
2820 err(EXIT_FAILURE
, _("cannot open %s"), diskpath
);
2822 if (!fdisk_is_readonly(cf
->cxt
)) {
2823 if (blkdev_lock(fdisk_get_devfd(cf
->cxt
), diskpath
, lockmode
) != 0)
2824 return EXIT_FAILURE
;
2826 cf
->device_is_used
= fdisk_device_is_used(cf
->cxt
);
2827 fdisk_get_partitions(cf
->cxt
, &cf
->original_layout
);
2830 /* Don't use err(), warn() from this point */
2835 cfdisk_free_lines(cf
);
2839 fdisk_unref_table(cf
->table
);
2840 #ifdef HAVE_LIBMOUNT
2841 mnt_unref_table(cf
->fstab
);
2842 mnt_unref_table(cf
->mtab
);
2843 mnt_unref_cache(cf
->mntcache
);
2845 rc
= fdisk_deassign_device(cf
->cxt
, cf
->nwrites
== 0);
2846 fdisk_unref_context(cf
->cxt
);
2847 DBG(MISC
, ul_debug("bye! [rc=%d]", rc
));
2848 return rc
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;