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 static const int color_pairs
[][2] = {
128 /* color foreground, background */
129 [CFDISK_CL_WARNING
] = { COLOR_RED
, -1 },
130 [CFDISK_CL_FREESPACE
] = { COLOR_GREEN
, -1 },
131 [CFDISK_CL_INFO
] = { COLOR_BLUE
, -1 }
136 static struct cfdisk_menuitem
*menu_get_menuitem(struct cfdisk
*cf
, size_t idx
);
137 static struct cfdisk_menuitem
*menu_get_menuitem_by_key(struct cfdisk
*cf
, int key
, size_t *idx
);
138 static struct cfdisk_menu
*menu_push(struct cfdisk
*cf
, struct cfdisk_menuitem
*item
);
139 static struct cfdisk_menu
*menu_pop(struct cfdisk
*cf
);
140 static void menu_refresh_size(struct cfdisk
*cf
);
142 static int ui_end(void);
143 static int ui_refresh(struct cfdisk
*cf
);
145 static void ui_warnx(const char *fmt
, ...)
146 __attribute__((__format__ (__printf__
, 1, 2)));
147 static void ui_warn(const char *fmt
, ...)
148 __attribute__((__format__ (__printf__
, 1, 2)));
149 static void ui_info(const char *fmt
, ...)
150 __attribute__((__format__ (__printf__
, 1, 2)));
152 static void ui_draw_menu(struct cfdisk
*cf
);
153 static int ui_menu_move(struct cfdisk
*cf
, int key
);
154 static void ui_menu_resize(struct cfdisk
*cf
);
156 static int ui_get_size(struct cfdisk
*cf
, const char *prompt
, uint64_t *res
,
157 uint64_t low
, uint64_t up
, int *expsize
);
159 static int ui_enabled
;
160 static volatile sig_atomic_t sig_resize
;
161 static volatile sig_atomic_t sig_die
;
163 /* ncurses LINES and COLS may be actual variables or *macros*, but we need
164 * something portable and writable */
165 static size_t ui_lines
;
166 static size_t ui_cols
;
169 struct cfdisk_menuitem
{
170 int key
; /* keyboard shortcut */
171 const char *name
; /* item name */
172 const char *desc
; /* item description (hint) */
178 char *title
; /* optional menu title */
179 struct cfdisk_menuitem
*items
; /* array with menu items */
180 char *ignore
;/* string with keys to ignore */
181 size_t width
; /* maximal width of the menu item */
182 size_t nitems
; /* number of the active menu items */
183 size_t page_sz
;/* when menu longer than screen */
184 size_t idx
; /* the current menu item */
185 int prefkey
;/* preferred menu item */
186 struct cfdisk_menu
*prev
;
188 /* @ignore keys generator */
189 int (*ignore_cb
) (struct cfdisk
*, char *, size_t);
191 unsigned int vertical
: 1; /* enable vertical mode */
195 static struct cfdisk_menuitem main_menuitems
[] = {
196 { 'b', N_("Bootable"), N_("Toggle bootable flag of the current partition") },
197 { 'd', N_("Delete"), N_("Delete the current partition") },
198 { 'r', N_("Resize"), N_("Reduce or enlarge the current partition") },
199 { 'n', N_("New"), N_("Create new partition from free space") },
200 { 'q', N_("Quit"), N_("Quit program without writing changes") },
201 { 't', N_("Type"), N_("Change the partition type") },
202 { 'h', N_("Help"), N_("Print help screen") },
203 { 's', N_("Sort"), N_("Fix partitions order") },
204 { 'W', N_("Write"), N_("Write partition table to disk (this might destroy data)") },
205 { 'u', N_("Dump"), N_("Dump partition table to sfdisk compatible script file") },
209 /* extra partinfo in name:value pairs */
210 struct cfdisk_extra
{
214 struct list_head exs
;
217 /* line and extra partinfo list_head */
219 char *data
; /* line data */
220 struct libscols_table
*extra
; /* extra info ('X') */
221 WINDOW
*w
; /* window with extra info */
224 /* top level control struct */
226 struct fdisk_context
*cxt
; /* libfdisk context */
227 struct fdisk_table
*table
; /* partition table */
228 struct fdisk_table
*original_layout
; /* original on-disk PT */
230 struct cfdisk_menu
*menu
; /* the current menu */
232 int *fields
; /* output columns IDs */
233 size_t nfields
; /* number of columns IDs */
235 char *linesbuf
; /* table as string */
236 size_t linesbufsz
; /* size of the tb_buf */
238 struct cfdisk_line
*lines
; /* list of lines */
240 size_t nlines
; /* number of lines */
241 size_t lines_idx
; /* current line <0..N>, exclude header */
244 unsigned int nwrites
; /* fdisk_write_disklabel() counter */
246 WINDOW
*act_win
; /* the window currently on the screen */
249 struct libmnt_table
*mtab
;
250 struct libmnt_table
*fstab
;
251 struct libmnt_cache
*mntcache
;
253 unsigned int wrong_order
:1, /* PT not in right order */
254 zero_start
:1, /* ignore existing partition table */
255 device_is_used
: 1, /* don't use re-read ioctl */
256 show_extra
:1; /* show extra partinfo */
261 * let's use include/debug.h stuff for cfdisk too
263 static UL_DEBUG_DEFINE_MASK(cfdisk
);
264 UL_DEBUG_DEFINE_MASKNAMES(cfdisk
) = UL_DEBUG_EMPTY_MASKNAMES
;
266 #define CFDISK_DEBUG_INIT (1 << 1)
267 #define CFDISK_DEBUG_UI (1 << 2)
268 #define CFDISK_DEBUG_MENU (1 << 3)
269 #define CFDISK_DEBUG_MISC (1 << 4)
270 #define CFDISK_DEBUG_TABLE (1 << 5)
271 #define CFDISK_DEBUG_ALL 0xFFFF
273 #define DBG(m, x) __UL_DBG(cfdisk, CFDISK_DEBUG_, m, x)
275 static void cfdisk_init_debug(void)
277 __UL_INIT_DEBUG_FROM_ENV(cfdisk
, CFDISK_DEBUG_
, 0, CFDISK_DEBUG
);
280 /* Initialize output columns -- we follow libfdisk fields (usually specific
283 static int cols_init(struct cfdisk
*cf
)
291 return fdisk_label_get_fields_ids(NULL
, cf
->cxt
, &cf
->fields
, &cf
->nfields
);
294 static void die_on_signal(void)
296 DBG(MISC
, ul_debug("die on signal."));
301 static void resize(void)
305 if (ioctl(fileno(stdout
), TIOCGWINSZ
, &ws
) != -1
306 && ws
.ws_row
&& ws
.ws_col
) {
307 ui_lines
= ws
.ws_row
;
310 resizeterm(ws
.ws_row
, ws
.ws_col
);
312 clearok(stdscr
, TRUE
);
316 DBG(UI
, ul_debug("ui: resize refresh ui_cols=%zu, ui_lines=%zu",
321 /* Reads partition in tree-like order from scols
323 static int partition_from_scols(struct fdisk_table
*tb
,
324 struct libscols_line
*ln
)
326 struct fdisk_partition
*pa
= scols_line_get_userdata(ln
);
328 fdisk_table_add_partition(tb
, pa
);
329 fdisk_unref_partition(pa
);
331 if (scols_line_has_children(ln
)) {
332 struct libscols_line
*chln
;
333 struct libscols_iter
*itr
= scols_new_iter(SCOLS_ITER_FORWARD
);
337 while (scols_line_next_child(ln
, itr
, &chln
) == 0)
338 partition_from_scols(tb
, chln
);
339 scols_free_iter(itr
);
344 static char *table_to_string(struct cfdisk
*cf
, struct fdisk_table
*tb
)
346 struct fdisk_partition
*pa
;
347 struct fdisk_label
*lb
;
348 struct fdisk_iter
*itr
;
349 struct libscols_table
*table
= NULL
;
350 struct libscols_iter
*s_itr
= NULL
;
354 struct libscols_line
*ln
, *ln_cont
= NULL
;
356 DBG(TABLE
, ul_debug("convert to string"));
363 lb
= fdisk_get_label(cf
->cxt
, NULL
);
366 itr
= fdisk_new_iter(FDISK_ITER_FORWARD
);
370 /* get container (e.g. extended partition) */
371 while (fdisk_table_next_partition(tb
, itr
, &pa
) == 0) {
372 if (fdisk_partition_is_nested(pa
)) {
373 DBG(TABLE
, ul_debug("nested detected, using tree"));
374 tree
= SCOLS_FL_TREE
;
379 table
= scols_new_table();
382 scols_table_enable_maxout(table
, 1);
383 scols_table_enable_nowrap(table
, 1);
385 #if !defined(HAVE_LIBNCURSESW) || !defined(HAVE_WIDECHAR)
386 scols_table_enable_ascii(table
, 1);
390 for (i
= 0; i
< cf
->nfields
; i
++) {
392 const struct fdisk_field
*field
=
393 fdisk_label_get_field(lb
, cf
->fields
[i
]);
397 if (fdisk_field_is_number(field
))
398 fl
|= SCOLS_FL_RIGHT
;
399 if (fdisk_field_get_id(field
) == FDISK_FIELD_TYPE
)
400 fl
|= SCOLS_FL_TRUNC
;
401 if (tree
&& fdisk_field_get_id(field
) == FDISK_FIELD_DEVICE
)
404 if (!scols_table_new_column(table
,
405 _(fdisk_field_get_name(field
)),
406 fdisk_field_get_width(field
), fl
))
411 fdisk_reset_iter(itr
, FDISK_ITER_FORWARD
);
413 while (fdisk_table_next_partition(tb
, itr
, &pa
) == 0) {
414 struct libscols_line
*parent
= fdisk_partition_is_nested(pa
) ? ln_cont
: NULL
;
416 ln
= scols_table_new_line(table
, parent
);
419 for (i
= 0; i
< cf
->nfields
; i
++) {
422 if (fdisk_partition_to_string(pa
, cf
->cxt
,
423 cf
->fields
[i
], &cdata
))
425 scols_line_refer_data(ln
, i
, cdata
);
427 if (tree
&& fdisk_partition_is_container(pa
))
430 scols_line_set_userdata(ln
, (void *) pa
);
431 fdisk_ref_partition(pa
);
434 if (scols_table_is_empty(table
))
437 scols_table_reduce_termwidth(table
, ARROW_CURSOR_WIDTH
);
438 scols_print_table_to_string(table
, &res
);
440 /* scols_* code might reorder lines, let's reorder @tb according to the
441 * final output (it's no problem because partitions are addressed by
442 * parno stored within struct fdisk_partition) */
445 fdisk_reset_table(tb
);
447 s_itr
= scols_new_iter(SCOLS_ITER_FORWARD
);
451 /* add all in the right order (don't forget the output is tree) */
452 while (scols_table_next_line(table
, s_itr
, &ln
) == 0) {
453 if (scols_line_get_parent(ln
))
455 if (partition_from_scols(tb
, ln
))
459 scols_unref_table(table
);
460 scols_free_iter(s_itr
);
461 fdisk_free_iter(itr
);
466 static void cfdisk_free_lines(struct cfdisk
*cf
)
469 while(i
< cf
->nlines
) {
470 scols_unref_table(cf
->lines
[i
].extra
);
472 DBG(UI
, ul_debug("delete window: %p",
476 delwin(cf
->lines
[i
].w
);
477 cf
->lines
[i
].w
= NULL
;
485 * Read data about partitions from libfdisk and prepare output lines.
487 static int lines_refresh(struct cfdisk
*cf
)
495 DBG(TABLE
, ul_debug("refreshing buffer"));
498 cfdisk_free_lines(cf
);
504 fdisk_unref_table(cf
->table
);
507 /* read partitions and free spaces into cf->table */
508 rc
= fdisk_get_partitions(cf
->cxt
, &cf
->table
);
510 rc
= fdisk_get_freespaces(cf
->cxt
, &cf
->table
);
514 cf
->linesbuf
= table_to_string(cf
, cf
->table
);
518 cf
->linesbufsz
= strlen(cf
->linesbuf
);
519 cf
->nlines
= fdisk_table_get_nents(cf
->table
) + 1; /* 1 for header line */
521 cf
->wrong_order
= fdisk_table_wrong_order(cf
->table
) ? 1 : 0;
523 if (MENU_START_LINE
- TABLE_START_LINE
< cf
->nlines
)
524 cf
->page_sz
= MENU_START_LINE
- TABLE_START_LINE
- 1;
526 cf
->lines
= xcalloc(cf
->nlines
, sizeof(struct cfdisk_line
));
528 for (p
= cf
->linesbuf
, i
= 0; p
&& i
< cf
->nlines
; i
++) {
529 cf
->lines
[i
].data
= p
;
535 cf
->lines
[i
].extra
= scols_new_table();
536 scols_table_enable_noheadings(cf
->lines
[i
].extra
, 1);
537 scols_table_new_column(cf
->lines
[i
].extra
, NULL
, 0, SCOLS_FL_RIGHT
);
538 scols_table_new_column(cf
->lines
[i
].extra
, NULL
, 0, SCOLS_FL_TRUNC
);
544 static struct fdisk_partition
*get_current_partition(struct cfdisk
*cf
)
549 return fdisk_table_get_partition(cf
->table
, cf
->lines_idx
);
552 static int is_freespace(struct cfdisk
*cf
, size_t i
)
554 struct fdisk_partition
*pa
;
559 pa
= fdisk_table_get_partition(cf
->table
, i
);
560 return fdisk_partition_is_freespace(pa
);
563 /* converts libfdisk FDISK_ASKTYPE_MENU to cfdisk menu and returns user's
564 * response back to libfdisk
566 static int ask_menu(struct fdisk_ask
*ask
, struct cfdisk
*cf
)
568 struct cfdisk_menuitem
*d
, *cm
;
570 size_t i
= 0, nitems
;
571 const char *name
, *desc
;
576 /* create cfdisk menu according to libfdisk ask-menu, note that the
577 * last cm[] item has to be empty -- so nitems + 1 */
578 nitems
= fdisk_ask_menu_get_nitems(ask
);
579 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
581 for (i
= 0; i
< nitems
; i
++) {
582 if (fdisk_ask_menu_get_item(ask
, i
, &key
, &name
, &desc
))
589 /* make the new menu active */
602 if (ui_menu_move(cf
, key
) == 0)
609 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
611 fdisk_ask_menu_set_result(ask
, d
->key
);
628 static int ask_callback(struct fdisk_context
*cxt
__attribute__((__unused__
)),
629 struct fdisk_ask
*ask
,
630 void *data
__attribute__((__unused__
)))
636 switch(fdisk_ask_get_type(ask
)) {
637 case FDISK_ASKTYPE_INFO
:
638 ui_info("%s", fdisk_ask_print_get_mesg(ask
));
640 case FDISK_ASKTYPE_WARNX
:
641 ui_warnx("%s", fdisk_ask_print_get_mesg(ask
));
643 case FDISK_ASKTYPE_WARN
:
644 ui_warn("%s", fdisk_ask_print_get_mesg(ask
));
646 case FDISK_ASKTYPE_MENU
:
647 ask_menu(ask
, (struct cfdisk
*) data
);
650 ui_warnx(_("internal error: unsupported dialog type %d"),
651 fdisk_ask_get_type(ask
));
657 static int ui_end(void)
662 #if defined(HAVE_SLCURSES_H) || defined(HAVE_SLANG_SLCURSES_H)
663 SLsmg_gotorc(ui_lines
- 1, 0);
666 mvcur(0, ui_cols
- 1, ui_lines
-1, 0);
676 static void __attribute__((__format__ (__printf__
, 3, 0)))
677 ui_vprint_center(size_t line
, int attrs
, const char *fmt
, va_list ap
)
685 xvasprintf(&buf
, fmt
, ap
);
687 width
= mbs_safe_width(buf
);
688 if (width
> (size_t) ui_cols
) {
689 char *p
= strrchr(buf
+ ui_cols
, ' ');
693 if (line
+ 1 >= ui_lines
)
696 mvaddstr(line
, 0, buf
);
697 mvaddstr(line
+ 1, 0, p
+1);
701 mvaddstr(line
, (ui_cols
- width
) / 2, buf
);
707 static void __attribute__((__format__ (__printf__
, 2, 3)))
708 ui_center(size_t line
, const char *fmt
, ...)
712 ui_vprint_center(line
, 0, fmt
, ap
);
716 static void __attribute__((__format__ (__printf__
, 1, 2)))
717 ui_warnx(const char *fmt
, ...)
722 ui_vprint_center(WARN_LINE
,
723 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING
) : 0,
726 vfprintf(stderr
, fmt
, ap
);
732 static void __attribute__((__format__ (__printf__
, 1, 2)))
733 ui_warn(const char *fmt
, ...)
738 xasprintf(&fmt_m
, "%s: %m", fmt
);
742 ui_vprint_center(WARN_LINE
,
743 colors_wanted() ? COLOR_PAIR(CFDISK_CL_WARNING
) : 0,
746 vfprintf(stderr
, fmt_m
, ap
);
753 static void ui_clean_warn(void)
759 static int __attribute__((__noreturn__
))
760 __attribute__((__format__ (__printf__
, 2, 3)))
761 ui_err(int rc
, const char *fmt
, ...)
767 fprintf(stderr
, "%s: ", program_invocation_short_name
);
768 vfprintf(stderr
, fmt
, ap
);
769 fprintf(stderr
, ": %s\n", strerror(errno
));
775 static int __attribute__((__noreturn__
))
776 __attribute__((__format__ (__printf__
, 2, 3)))
777 ui_errx(int rc
, const char *fmt
, ...)
783 fprintf(stderr
, "%s: ", program_invocation_short_name
);
784 vfprintf(stderr
, fmt
, ap
);
791 static void __attribute__((__format__ (__printf__
, 1, 2)))
792 ui_info(const char *fmt
, ...)
797 ui_vprint_center(INFO_LINE
,
798 colors_wanted() ? COLOR_PAIR(CFDISK_CL_INFO
) : 0,
801 vfprintf(stdout
, fmt
, ap
);
807 static void ui_clean_info(void)
813 static void __attribute__((__format__ (__printf__
, 1, 2)))
814 ui_hint(const char *fmt
, ...)
819 ui_vprint_center(HINT_LINE
, A_BOLD
, fmt
, ap
);
821 vfprintf(stdout
, fmt
, ap
);
827 static void ui_clean_hint(void)
834 static void sig_handler_die(int dummy
__attribute__((__unused__
)))
839 static void sig_handler_resize(int dummy
__attribute__((__unused__
)))
844 static void menu_refresh_size(struct cfdisk
*cf
)
846 if (cf
->menu
&& cf
->menu
->nitems
)
847 cf
->menu
->page_sz
= (cf
->menu
->nitems
/ (ui_lines
- 4)) ? ui_lines
- 4 : 0;
850 static void menu_update_ignore(struct cfdisk
*cf
)
852 char ignore
[128] = { 0 };
854 struct cfdisk_menu
*m
;
855 struct cfdisk_menuitem
*d
, *org
= NULL
;
860 assert(cf
->menu
->ignore_cb
);
863 DBG(MENU
, ul_debug("update menu ignored keys"));
865 i
= m
->ignore_cb(cf
, ignore
, sizeof(ignore
));
868 /* return if no change */
869 if ((!m
->ignore
&& !*ignore
)
870 || (m
->ignore
&& *ignore
&& strcmp(m
->ignore
, ignore
) == 0)) {
875 org
= menu_get_menuitem(cf
, m
->idx
);
878 m
->ignore
= xstrdup(ignore
);
881 for (d
= m
->items
; d
->name
; d
++) {
882 if (m
->ignore
&& strchr(m
->ignore
, d
->key
))
887 DBG(MENU
, ul_debug("update menu preferred keys"));
889 /* refresh menu index to be at the same menuitem or go to the first */
890 if (org
&& menu_get_menuitem_by_key(cf
, org
->key
, &idx
))
892 else if (m
->prefkey
&& menu_get_menuitem_by_key(cf
, m
->prefkey
, &idx
))
897 menu_refresh_size(cf
);
900 static struct cfdisk_menu
*menu_push(
902 struct cfdisk_menuitem
*items
)
904 struct cfdisk_menu
*m
= xcalloc(1, sizeof(*m
));
905 struct cfdisk_menuitem
*d
;
909 DBG(MENU
, ul_debug("new menu"));
914 for (d
= m
->items
; d
->name
; d
++) {
915 const char *name
= _(d
->name
);
916 size_t len
= mbs_safe_width(name
);
924 menu_refresh_size(cf
);
928 static struct cfdisk_menu
*menu_pop(struct cfdisk
*cf
)
930 struct cfdisk_menu
*m
= NULL
;
934 DBG(MENU
, ul_debug("pop menu"));
938 free(cf
->menu
->ignore
);
939 free(cf
->menu
->title
);
946 static void menu_set_title(struct cfdisk_menu
*m
, const char *title
)
951 size_t len
= mbs_safe_width(title
);
952 if (len
+ MENU_TITLE_PADDING
> m
->width
)
953 m
->width
= len
+ MENU_TITLE_PADDING
;
954 str
= xstrdup(title
);
960 static int ui_init(struct cfdisk
*cf
__attribute__((__unused__
)))
964 DBG(UI
, ul_debug("init"));
966 /* setup SIGCHLD handler */
967 sigemptyset(&sa
.sa_mask
);
969 sa
.sa_handler
= sig_handler_die
;
970 sigaction(SIGINT
, &sa
, NULL
);
971 sigaction(SIGTERM
, &sa
, NULL
);
973 sa
.sa_handler
= sig_handler_resize
;
974 sigaction(SIGWINCH
, &sa
, NULL
);
979 #ifdef HAVE_USE_DEFAULT_COLORS
980 if (colors_wanted() && has_colors()) {
984 use_default_colors();
985 for (i
= 1; i
< ARRAY_SIZE(color_pairs
); i
++) /* yeah, start from 1! */
986 init_pair(i
, color_pairs
[i
][0], color_pairs
[i
][1]);
996 keypad(stdscr
, TRUE
);
1002 #define MENU_H_ITEMWIDTH(m) ( MENU_H_PRESTR_SZ \
1006 + MENU_H_POSTSTR_SZ)
1008 #define MENU_V_ITEMWIDTH(m) (MENU_V_SPADDING + (m)->width + MENU_V_SPADDING)
1011 static size_t menuitem_get_line(struct cfdisk
*cf
, size_t idx
)
1013 struct cfdisk_menu
*m
= cf
->menu
;
1016 if (!m
->page_sz
) /* small menu */
1017 return (ui_lines
- (cf
->menu
->nitems
+ 1)) / 2 + idx
;
1018 return (idx
% m
->page_sz
) + 1;
1022 size_t len
= MENU_H_ITEMWIDTH(m
) + MENU_H_BETWEEN
; /** item width */
1023 size_t items
= ui_cols
/ len
; /* items per line */
1027 return MENU_START_LINE
+ ((idx
/ items
));
1031 static int menuitem_get_column(struct cfdisk
*cf
, size_t idx
)
1033 if (cf
->menu
->vertical
) {
1034 size_t nc
= MENU_V_ITEMWIDTH(cf
->menu
);
1035 if ((size_t) ui_cols
<= nc
)
1037 return (ui_cols
- nc
) / 2;
1041 size_t len
= MENU_H_ITEMWIDTH(cf
->menu
) + MENU_H_BETWEEN
; /* item width */
1042 size_t items
= ui_cols
/ len
; /* items per line */
1043 size_t extra
= items
< cf
->menu
->nitems
? /* extra space on line */
1044 ui_cols
% len
: /* - multi-line menu */
1045 ui_cols
- (cf
->menu
->nitems
* len
); /* - one line menu */
1048 return 0; /* hmm... no space */
1050 extra
+= MENU_H_BETWEEN
; /* add padding after last item to extra */
1053 return (idx
* len
) + (extra
/ 2);
1054 return ((idx
% items
) * len
) + (extra
/ 2);
1058 static int menuitem_on_page(struct cfdisk
*cf
, size_t idx
)
1060 struct cfdisk_menu
*m
= cf
->menu
;
1062 if (m
->page_sz
== 0 ||
1063 m
->idx
/ m
->page_sz
== idx
/ m
->page_sz
)
1068 static struct cfdisk_menuitem
*menu_get_menuitem(struct cfdisk
*cf
, size_t idx
)
1070 struct cfdisk_menuitem
*d
;
1073 for (i
= 0, d
= cf
->menu
->items
; d
->name
; d
++) {
1074 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, d
->key
))
1083 static struct cfdisk_menuitem
*menu_get_menuitem_by_key(struct cfdisk
*cf
,
1084 int key
, size_t *idx
)
1086 struct cfdisk_menuitem
*d
;
1088 for (*idx
= 0, d
= cf
->menu
->items
; d
->name
; d
++) {
1089 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, d
->key
))
1099 static void ui_draw_menuitem(struct cfdisk
*cf
,
1100 struct cfdisk_menuitem
*d
,
1106 const size_t buf_sz
= 80 * MB_CUR_MAX
;
1107 int ln
, cl
, vert
= cf
->menu
->vertical
;
1109 if (!menuitem_on_page(cf
, idx
))
1110 return; /* no visible item */
1111 ln
= menuitem_get_line(cf
, idx
);
1112 cl
= menuitem_get_column(cf
, idx
);
1114 ptr
= buf
= xmalloc(buf_sz
);
1117 width
= cf
->menu
->width
+ MENU_V_SPADDING
;
1118 memset(ptr
, ' ', MENU_V_SPADDING
);
1119 ptr
+= MENU_V_SPADDING
;
1121 width
= MENU_H_SPADDING
+ cf
->menu
->width
+ MENU_H_SPADDING
;
1124 mbsalign(name
, ptr
, buf_sz
, &width
,
1125 vert
? MBS_ALIGN_LEFT
: MBS_ALIGN_CENTER
,
1128 DBG(MENU
, ul_debug("menuitem: cl=%d, ln=%d, item='%s'",
1132 mvaddch(ln
, cl
- 1, ACS_VLINE
);
1133 mvaddch(ln
, cl
+ MENU_V_ITEMWIDTH(cf
->menu
), ACS_VLINE
);
1136 if (cf
->menu
->idx
== idx
)
1140 mvprintw(ln
, cl
, "%s", buf
);
1142 mvprintw(ln
, cl
, "%s%s%s", MENU_H_PRESTR
, buf
, MENU_H_POSTSTR
);
1145 if (cf
->menu
->idx
== idx
) {
1148 ui_hint("%s", _(d
->desc
));
1152 static void ui_clean_menu(struct cfdisk
*cf
)
1156 struct cfdisk_menu
*m
= cf
->menu
;
1157 size_t ln
= menuitem_get_line(cf
, 0);
1160 lastline
= ln
+ (m
->page_sz
? m
->page_sz
: m
->nitems
);
1162 lastline
= menuitem_get_line(cf
, m
->nitems
);
1164 for (i
= ln
; i
<= lastline
; i
++) {
1167 DBG(MENU
, ul_debug("clean_menu: line %zu", i
));
1176 static void ui_draw_menu(struct cfdisk
*cf
)
1178 struct cfdisk_menuitem
*d
;
1179 struct cfdisk_menu
*m
;
1181 size_t ln
= menuitem_get_line(cf
, 0);
1187 DBG(MENU
, ul_debug("draw start"));
1193 nlines
= m
->page_sz
? m
->page_sz
: m
->nitems
;
1195 nlines
= menuitem_get_line(cf
, m
->nitems
);
1198 menu_update_ignore(cf
);
1200 while ((d
= menu_get_menuitem(cf
, i
)))
1201 ui_draw_menuitem(cf
, d
, i
++);
1204 size_t cl
= menuitem_get_column(cf
, 0);
1205 size_t curpg
= m
->page_sz
? m
->idx
/ m
->page_sz
: 0;
1207 /* corners and horizontal lines */
1208 mvaddch(ln
- 1, cl
- 1, ACS_ULCORNER
);
1209 mvaddch(ln
+ nlines
, cl
- 1, ACS_LLCORNER
);
1211 for (i
= 0; i
< MENU_V_ITEMWIDTH(m
); i
++) {
1212 mvaddch(ln
- 1, cl
+ i
, ACS_HLINE
);
1213 mvaddch(ln
+ nlines
, cl
+ i
, ACS_HLINE
);
1216 mvaddch(ln
- 1, cl
+ i
, ACS_URCORNER
);
1217 mvaddch(ln
+ nlines
, cl
+ i
, ACS_LRCORNER
);
1219 /* draw also lines around empty lines on last page */
1221 m
->nitems
/ m
->page_sz
== m
->idx
/ m
->page_sz
) {
1222 for (i
= m
->nitems
% m
->page_sz
+ 1; i
<= m
->page_sz
; i
++) {
1223 mvaddch(i
, cl
- 1, ACS_VLINE
);
1224 mvaddch(i
, cl
+ MENU_V_ITEMWIDTH(m
), ACS_VLINE
);
1229 mvprintw(ln
- 1, cl
, " %s ", m
->title
);
1233 mvaddch(ln
- 1, cl
+ MENU_V_ITEMWIDTH(m
) - 2, ACS_UARROW
);
1234 if (m
->page_sz
&& curpg
< m
->nitems
/ m
->page_sz
)
1235 mvaddch(ln
+ nlines
, cl
+ MENU_V_ITEMWIDTH(m
) - 2, ACS_DARROW
);
1238 DBG(MENU
, ul_debug("draw end."));
1241 inline static int extra_insert_pair(struct cfdisk_line
*l
, const char *name
, const char *data
)
1243 struct libscols_line
*lsl
;
1249 if (!data
|| !*data
)
1252 lsl
= scols_table_new_line(l
->extra
, NULL
);
1256 rc
= scols_line_set_data(lsl
, 0, name
);
1258 rc
= scols_line_set_data(lsl
, 1, data
);
1263 #ifndef HAVE_LIBMOUNT
1264 static char *get_mountpoint( struct cfdisk
*cf
__attribute__((unused
)),
1265 const char *tagname
__attribute__((unused
)),
1266 const char *tagdata
__attribute__((unused
)))
1271 static char *get_mountpoint(struct cfdisk
*cf
, const char *tagname
, const char *tagdata
)
1273 struct libmnt_fs
*fs
= NULL
;
1274 char *target
= NULL
;
1280 DBG(UI
, ul_debug("asking for mountpoint [%s=%s]", tagname
, tagdata
));
1283 cf
->mntcache
= mnt_new_cache();
1285 /* 1st try between mounted filesystems */
1287 cf
->mtab
= mnt_new_table();
1289 mnt_table_set_cache(cf
->mtab
, cf
->mntcache
);
1290 mnt_table_parse_mtab(cf
->mtab
, NULL
);
1295 fs
= mnt_table_find_tag(cf
->mtab
, tagname
, tagdata
, MNT_ITER_FORWARD
);
1300 cf
->fstab
= mnt_new_table();
1302 mnt_table_set_cache(cf
->fstab
, cf
->mntcache
);
1303 if (mnt_table_parse_fstab(cf
->fstab
, NULL
) != 0) {
1304 mnt_unref_table(cf
->fstab
);
1310 fs
= mnt_table_find_tag(cf
->fstab
, tagname
, tagdata
, MNT_ITER_FORWARD
);
1316 xasprintf(&target
, _("%s (mounted)"), mnt_fs_get_target(fs
));
1318 target
= xstrdup(mnt_fs_get_target(fs
));
1323 #endif /* HAVE_LIBMOUNT */
1325 static inline int iszero(const char *str
)
1329 for (p
= str
; p
&& *p
== '0'; p
++);
1331 return !p
|| *p
== '\0';
1334 static void extra_prepare_data(struct cfdisk
*cf
)
1336 struct fdisk_partition
*pa
= get_current_partition(cf
);
1337 struct cfdisk_line
*l
= &cf
->lines
[cf
->lines_idx
];
1339 char *mountpoint
= NULL
;
1341 DBG(UI
, ul_debug("preparing extra data"));
1343 /* string data should not equal an empty string */
1344 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_NAME
, &data
) && data
) {
1345 extra_insert_pair(l
, _("Partition name:"), data
);
1347 mountpoint
= get_mountpoint(cf
, "PARTLABEL", data
);
1351 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_UUID
, &data
) && data
) {
1352 extra_insert_pair(l
, _("Partition UUID:"), data
);
1354 mountpoint
= get_mountpoint(cf
, "PARTUUID", data
);
1358 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_TYPE
, &data
) && data
) {
1359 char *code
= NULL
, *type
= NULL
;
1361 fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_TYPEID
, &code
);
1362 xasprintf(&type
, "%s (%s)", data
, code
);
1364 extra_insert_pair(l
, _("Partition type:"), type
);
1370 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_ATTR
, &data
) && data
) {
1371 extra_insert_pair(l
, _("Attributes:"), data
);
1375 /* for numeric data, only show non-zero rows */
1376 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_BSIZE
, &data
) && data
) {
1378 extra_insert_pair(l
, "BSIZE:", data
);
1382 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_CPG
, &data
) && data
) {
1384 extra_insert_pair(l
, "CPG:", data
);
1388 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSIZE
, &data
) && data
) {
1390 extra_insert_pair(l
, "FSIZE:", data
);
1394 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSUUID
, &data
) && data
) {
1395 extra_insert_pair(l
, _("Filesystem UUID:"), data
);
1397 mountpoint
= get_mountpoint(cf
, "UUID", data
);
1401 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSLABEL
, &data
) && data
) {
1402 extra_insert_pair(l
, _("Filesystem LABEL:"), data
);
1404 mountpoint
= get_mountpoint(cf
, "LABEL", data
);
1407 if (!fdisk_partition_to_string(pa
, cf
->cxt
, FDISK_FIELD_FSTYPE
, &data
) && data
) {
1408 extra_insert_pair(l
, _("Filesystem:"), data
);
1413 extra_insert_pair(l
, _("Mountpoint:"), mountpoint
);
1418 static int ui_draw_extra(struct cfdisk
*cf
)
1422 struct cfdisk_line
*ln
= &cf
->lines
[cf
->lines_idx
];
1423 char *tbstr
= NULL
, *end
;
1424 int win_ex_start_line
, win_height
, tblen
;
1427 if (!cf
->show_extra
)
1430 DBG(UI
, ul_debug("draw extra"));
1435 wclear(cf
->act_win
);
1439 if (scols_table_is_empty(ln
->extra
)) {
1440 extra_prepare_data(cf
);
1441 if (scols_table_is_empty(ln
->extra
))
1445 ndatalines
= fdisk_table_get_nents(cf
->table
) + 1;
1447 /* nents + header + one free line */
1448 win_ex_start_line
= TABLE_START_LINE
+ ndatalines
;
1449 win_height
= MENU_START_LINE
- win_ex_start_line
;
1450 tblen
= scols_table_get_nlines(ln
->extra
);
1452 /* we can't get a single line of data under the partlist*/
1456 /* number of data lines + 2 for top/bottom lines */
1457 win_height
= win_height
< tblen
+ 2 ? win_height
: tblen
+ 2;
1459 if ((size_t) win_ex_start_line
+ win_height
+ 1 < MENU_START_LINE
)
1460 win_ex_start_line
= MENU_START_LINE
- win_height
;
1462 win_ex
= subwin(stdscr
, win_height
, ui_cols
- 2, win_ex_start_line
, 1);
1464 scols_table_reduce_termwidth(ln
->extra
, 4);
1465 scols_print_table_to_string(ln
->extra
, &tbstr
);
1468 while ((end
= strchr(end
, '\n')))
1474 while (--win_height
> 1) {
1475 mvwaddstr(win_ex
, wline
++, 1 /* window column*/, tbstr
);
1476 tbstr
+= strlen(tbstr
) + 1;
1483 DBG(UI
, ul_debug("draw window: %p", win_ex
));
1487 cf
->act_win
= ln
->w
= win_ex
;
1491 static void ui_menu_goto(struct cfdisk
*cf
, int where
)
1493 struct cfdisk_menuitem
*d
;
1496 /* stop and begin/end for vertical menus */
1497 if (cf
->menu
->vertical
) {
1500 else if (where
> (int) cf
->menu
->nitems
- 1)
1501 where
= cf
->menu
->nitems
- 1;
1503 /* continue from begin/end */
1505 where
= cf
->menu
->nitems
- 1;
1506 else if ((size_t) where
> cf
->menu
->nitems
- 1)
1509 if ((size_t) where
== cf
->menu
->idx
)
1514 old
= cf
->menu
->idx
;
1515 cf
->menu
->idx
= where
;
1517 if (!menuitem_on_page(cf
, old
)) {
1522 d
= menu_get_menuitem(cf
, old
);
1523 ui_draw_menuitem(cf
, d
, old
);
1525 d
= menu_get_menuitem(cf
, where
);
1526 ui_draw_menuitem(cf
, d
, where
);
1530 static int ui_menu_move(struct cfdisk
*cf
, int key
)
1532 struct cfdisk_menu
*m
;
1537 if (key
== (int) ERR
)
1538 return 0; /* ignore errors */
1542 DBG(MENU
, ul_debug("menu move key >%c<.", key
));
1548 case '\016': /* ^N */
1549 case 'j': /* Vi-like alternative */
1550 ui_menu_goto(cf
, m
->idx
+ 1);
1553 case '\020': /* ^P */
1554 case 'k': /* Vi-like alternative */
1555 ui_menu_goto(cf
, (int) m
->idx
- 1);
1559 ui_menu_goto(cf
, (int) m
->idx
- m
->page_sz
);
1564 ui_menu_goto(cf
, 0);
1568 ui_menu_goto(cf
, m
->idx
+ m
->page_sz
);
1573 ui_menu_goto(cf
, m
->nitems
);
1580 ui_menu_goto(cf
, m
->idx
+ 1);
1586 ui_menu_goto(cf
, (int) m
->idx
- 1);
1591 if (key
== '\014') { /* ^L refresh */
1596 DBG(MENU
, ul_debug(" no menu move key"));
1600 /* but don't call me from ui_run(), this is for pop-up menus only */
1601 static void ui_menu_resize(struct cfdisk
*cf
)
1603 DBG(MENU
, ul_debug("menu resize/refresh"));
1606 menu_refresh_size(cf
);
1611 static int partition_on_page(struct cfdisk
*cf
, size_t i
)
1613 if (cf
->page_sz
== 0 ||
1614 cf
->lines_idx
/ cf
->page_sz
== i
/ cf
->page_sz
)
1619 static void ui_draw_partition(struct cfdisk
*cf
, size_t i
)
1621 int ln
= TABLE_START_LINE
+ 1 + i
; /* skip table header */
1622 int cl
= ARROW_CURSOR_WIDTH
; /* we need extra space for cursor */
1623 int cur
= cf
->lines_idx
== i
;
1627 if (!partition_on_page(cf
, i
))
1629 ln
= TABLE_START_LINE
+ (i
% cf
->page_sz
) + 1;
1630 curpg
= cf
->lines_idx
/ cf
->page_sz
;
1634 "draw partition %zu [page_sz=%zu, "
1635 "line=%d, idx=%zu]",
1636 i
, cf
->page_sz
, ln
, cf
->lines_idx
));
1640 mvaddstr(ln
, 0, ARROW_CURSOR_STRING
);
1641 mvaddstr(ln
, cl
, cf
->lines
[i
+ 1].data
);
1646 if (colors_wanted() && is_freespace(cf
, i
)) {
1647 attron(COLOR_PAIR(CFDISK_CL_FREESPACE
));
1650 mvaddstr(ln
, 0, ARROW_CURSOR_DUMMY
);
1651 mvaddstr(ln
, cl
, cf
->lines
[i
+ 1].data
);
1653 attroff(COLOR_PAIR(CFDISK_CL_FREESPACE
));
1656 if ((size_t) ln
== MENU_START_LINE
- 1 &&
1657 cf
->page_sz
&& curpg
< cf
->nlines
/ cf
->page_sz
) {
1660 mvaddch(ln
, ui_cols
- 1, ACS_DARROW
);
1661 mvaddch(ln
, 0, ACS_DARROW
);
1668 static int ui_draw_table(struct cfdisk
*cf
)
1670 int cl
= ARROW_CURSOR_WIDTH
;
1671 size_t i
, nparts
= fdisk_table_get_nents(cf
->table
);
1672 size_t curpg
= cf
->page_sz
? cf
->lines_idx
/ cf
->page_sz
: 0;
1674 DBG(UI
, ul_debug("draw table"));
1676 for (i
= TABLE_START_LINE
; i
<= TABLE_START_LINE
+ cf
->page_sz
; i
++) {
1681 if (nparts
== 0 || (size_t) cf
->lines_idx
> nparts
- 1)
1682 cf
->lines_idx
= nparts
? nparts
- 1 : 0;
1686 mvaddstr(TABLE_START_LINE
, cl
, cf
->lines
[0].data
);
1689 /* print partitions */
1690 for (i
= 0; i
< nparts
; i
++)
1691 ui_draw_partition(cf
, i
);
1694 mvaddch(TABLE_START_LINE
, ui_cols
- 1, ACS_UARROW
);
1695 mvaddch(TABLE_START_LINE
, 0, ACS_UARROW
);
1697 if (cf
->page_sz
&& curpg
< cf
->nlines
/ cf
->page_sz
) {
1698 mvaddch(MENU_START_LINE
- 1, ui_cols
- 1, ACS_DARROW
);
1699 mvaddch(MENU_START_LINE
- 1, 0, ACS_DARROW
);
1704 static int ui_table_goto(struct cfdisk
*cf
, int where
)
1707 size_t nparts
= fdisk_table_get_nents(cf
->table
);
1709 DBG(UI
, ul_debug("goto table %d", where
));
1713 else if ((size_t) where
> nparts
- 1)
1716 if ((size_t) where
== cf
->lines_idx
)
1719 old
= cf
->lines_idx
;
1720 cf
->lines_idx
= where
;
1722 if (!partition_on_page(cf
, old
) ||!partition_on_page(cf
, where
))
1725 ui_draw_partition(cf
, old
); /* cleanup old */
1726 ui_draw_partition(cf
, where
); /* draw new */
1736 static int ui_refresh(struct cfdisk
*cf
)
1738 struct fdisk_label
*lb
;
1740 uint64_t bytes
= fdisk_get_nsectors(cf
->cxt
) * fdisk_get_sector_size(cf
->cxt
);
1746 strsz
= size_to_human_string(SIZE_DECIMAL_2DIGITS
1748 | SIZE_SUFFIX_3LETTER
, bytes
);
1750 lb
= fdisk_get_label(cf
->cxt
, NULL
);
1757 ui_center(0, _("Disk: %s"), fdisk_get_devname(cf
->cxt
));
1759 ui_center(1, _("Size: %s, %"PRIu64
" bytes, %ju sectors"),
1760 strsz
, bytes
, (uintmax_t) fdisk_get_nsectors(cf
->cxt
));
1761 if (fdisk_get_disklabel_id(cf
->cxt
, &id
) == 0 && id
)
1762 ui_center(2, _("Label: %s, identifier: %s"),
1763 fdisk_label_get_name(lb
), id
);
1765 ui_center(2, _("Label: %s"), fdisk_label_get_name(lb
));
1775 static ssize_t
ui_get_string(const char *prompt
,
1776 const char *hint
, char *buf
, size_t len
)
1778 int ln
= MENU_START_LINE
, cl
= 1;
1780 struct mbs_editor
*edit
;
1782 DBG(UI
, ul_debug("ui get string"));
1794 mvaddstr(ln
, cl
, prompt
);
1795 cl
+= mbs_safe_width(prompt
);
1798 edit
= mbs_new_edit(buf
, len
, ui_cols
- cl
);
1802 mbs_edit_goto(edit
, MBS_EDIT_END
);
1805 ui_hint("%s", hint
);
1812 wint_t c
; /* we have fallback in widechar.h */
1816 mvaddstr(ln
, cl
, edit
->buf
);
1817 move(ln
, cl
+ edit
->cursor_cells
);
1820 #if !defined(HAVE_SLCURSES_H) && !defined(HAVE_SLANG_SLCURSES_H) && \
1821 defined(HAVE_LIBNCURSESW) && defined(HAVE_WIDECHAR)
1822 if (get_wch(&c
) == ERR
) {
1824 if ((c
= getch()) == (wint_t) ERR
) {
1832 if (!isatty(STDIN_FILENO
))
1838 DBG(UI
, ul_debug("ui get string: key=%lc", c
));
1840 if (c
== '\r' || c
== '\n' || c
== KEY_ENTER
)
1847 rc
= -CFDISK_ERR_ESC
;
1850 rc
= mbs_edit_goto(edit
, MBS_EDIT_LEFT
);
1853 rc
= mbs_edit_goto(edit
, MBS_EDIT_RIGHT
);
1856 rc
= mbs_edit_goto(edit
, MBS_EDIT_END
);
1859 rc
= mbs_edit_goto(edit
, MBS_EDIT_HOME
);
1865 rc
= mbs_edit_delete(edit
);
1870 rc
= mbs_edit_backspace(edit
);
1873 rc
= mbs_edit_insert(edit
, c
);
1883 rc
= strlen(edit
->buf
); /* success */
1889 mbs_free_edit(edit
);
1894 static int ui_get_size(struct cfdisk
*cf
, /* context */
1895 const char *prompt
, /* UI dialog string */
1896 uint64_t *res
, /* result in bytes */
1897 uint64_t low
, /* minimal size */
1898 uint64_t up
, /* maximal size */
1899 int *expsize
) /* explicitly specified size */
1904 char *dflt
= size_to_human_string(0, *res
);
1906 DBG(UI
, ul_debug("get_size (default=%"PRIu64
")", *res
));
1910 snprintf(buf
, sizeof(buf
), "%s", dflt
);
1913 int pwr
= 0, insec
= 0;
1915 rc
= ui_get_string(prompt
,
1916 _("May be followed by M for MiB, G for GiB, "
1917 "T for TiB, or S for sectors."),
1922 ui_warnx(_("Please, specify size."));
1923 continue; /* nothing specified */
1924 } if (rc
== -CFDISK_ERR_ESC
)
1925 break; /* cancel dialog */
1927 if (strcmp(buf
, dflt
) == 0)
1928 user
= *res
, rc
= 0; /* no change, use default */
1930 size_t len
= strlen(buf
);
1931 if (buf
[len
- 1] == 'S' || buf
[len
- 1] == 's') {
1933 buf
[len
- 1] = '\0';
1935 rc
= parse_size(buf
, (uintmax_t *)&user
, &pwr
); /* parse */
1939 DBG(UI
, ul_debug("get_size user=%"PRIu64
", power=%d, in-sectors=%s",
1940 user
, pwr
, insec
? "yes" : "no"));
1942 user
*= fdisk_get_sector_size(cf
->cxt
);
1944 ui_warnx(_("Minimum size is %"PRIu64
" bytes."), low
);
1947 if (user
> up
&& pwr
&& user
< up
+ (1ULL << pwr
* 10))
1948 /* ignore when the user specified size overflow
1949 * with in range specified by suffix (e.g. MiB) */
1953 ui_warnx(_("Maximum size is %"PRIu64
" bytes."), up
);
1956 if (rc
== 0 && insec
&& expsize
)
1960 ui_warnx(_("Failed to parse size."));
1967 DBG(UI
, ul_debug("get_size (result=%"PRIu64
", rc=%zd)", *res
, rc
));
1971 static struct fdisk_parttype
*ui_get_parttype(struct cfdisk
*cf
,
1972 struct fdisk_parttype
*cur
)
1974 struct cfdisk_menuitem
*d
, *cm
;
1975 size_t i
= 0, nitems
, idx
= 0;
1976 struct fdisk_parttype
*t
= NULL
;
1977 struct fdisk_label
*lb
;
1980 DBG(UI
, ul_debug("asking for parttype."));
1982 lb
= fdisk_get_label(cf
->cxt
, NULL
);
1984 /* create cfdisk menu according to label types, note that the
1985 * last cm[] item has to be empty -- so nitems + 1 */
1986 nitems
= fdisk_label_get_nparttypes(lb
);
1990 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
1994 codetypes
= fdisk_label_has_code_parttypes(lb
);
1996 for (i
= 0; i
< nitems
; i
++) {
1997 const struct fdisk_parttype
*x
= fdisk_label_get_parttype(lb
, i
);
2000 cm
[i
].userdata
= (void *) x
;
2002 xasprintf(&name
, "%2x %s",
2003 fdisk_parttype_get_code(x
),
2004 _(fdisk_parttype_get_name(x
)));
2006 name
= (char *) _(fdisk_parttype_get_name(x
));
2007 cm
[i
].desc
= fdisk_parttype_get_string(x
);
2014 /* make the new menu active */
2016 cf
->menu
->vertical
= 1;
2017 cf
->menu
->idx
= idx
;
2018 menu_set_title(cf
->menu
, _("Select partition type"));
2029 if (ui_menu_move(cf
, key
) == 0)
2036 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2038 t
= (struct fdisk_parttype
*) d
->userdata
;
2052 for (i
= 0; i
< nitems
; i
++)
2053 free((char *) cm
[i
].name
);
2056 DBG(UI
, ul_debug("get parrtype done [type=%s] ", t
?
2057 fdisk_parttype_get_name(t
) : NULL
));
2061 static int ui_script_read(struct cfdisk
*cf
)
2063 struct fdisk_script
*sc
= NULL
;
2064 char buf
[PATH_MAX
] = { 0 };
2068 rc
= ui_get_string( _("Enter script file name: "),
2069 _("The script file will be applied to in-memory partition table."),
2076 sc
= fdisk_new_script_from_file(cf
->cxt
, buf
);
2078 ui_warn(_("Cannot open %s"), buf
);
2080 ui_warnx(_("Failed to parse script file %s"), buf
);
2081 else if (fdisk_apply_script(cf
->cxt
, sc
) != 0)
2082 ui_warnx(_("Failed to apply script %s"), buf
);
2087 fdisk_unref_script(sc
);
2091 static int ui_script_write(struct cfdisk
*cf
)
2093 struct fdisk_script
*sc
= NULL
;
2094 char buf
[PATH_MAX
] = { 0 };
2098 rc
= ui_get_string( _("Enter script file name: "),
2099 _("The current in-memory partition table will be dumped to the file."),
2105 sc
= fdisk_new_script(cf
->cxt
);
2107 ui_warn(_("Failed to allocate script handler"));
2111 rc
= fdisk_script_read_context(sc
, NULL
);
2113 ui_warnx(_("Failed to read disk layout into script."));
2117 DBG(UI
, ul_debug("writing dump into: '%s'", buf
));
2118 f
= fopen(buf
, "w");
2120 ui_warn(_("Cannot open %s"), buf
);
2125 rc
= fdisk_script_write_file(sc
, f
);
2127 ui_info(_("Disk layout successfully dumped."));
2130 ui_warn(_("Failed to write script %s"), buf
);
2133 fdisk_unref_script(sc
);
2137 /* prints menu with libfdisk labels and waits for users response */
2138 static int ui_create_label(struct cfdisk
*cf
)
2140 struct cfdisk_menuitem
*d
, *cm
;
2141 int rc
= 1, refresh_menu
= 1;
2142 size_t i
= 0, nitems
;
2143 struct fdisk_label
*lb
= NULL
;
2147 DBG(UI
, ul_debug("asking for new disklabe."));
2149 /* create cfdisk menu according to libfdisk labels, note that the
2150 * last cm[] item has to be empty -- so nitems + 1 */
2151 nitems
= fdisk_get_nlabels(cf
->cxt
);
2152 cm
= xcalloc(nitems
+ 1, sizeof(struct cfdisk_menuitem
));
2154 while (fdisk_next_label(cf
->cxt
, &lb
) == 0) {
2155 if (fdisk_label_is_disabled(lb
) ||
2156 fdisk_label_get_type(lb
) == FDISK_DISKLABEL_BSD
)
2158 cm
[i
++].name
= fdisk_label_get_name(lb
);
2163 /* make the new menu active */
2165 cf
->menu
->vertical
= 1;
2166 menu_set_title(cf
->menu
, _("Select label type"));
2168 if (!cf
->zero_start
)
2169 ui_info(_("Device does not contain a recognized partition table."));
2177 ui_hint(_("Select a type to create a new label, press 'L' to load script file, 'Q' quits."));
2188 if (ui_menu_move(cf
, key
) == 0)
2194 d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2196 rc
= fdisk_create_disklabel(cf
->cxt
, d
->name
);
2204 rc
= ui_script_read(cf
);
2217 DBG(UI
, ul_debug("create label done [rc=%d] ", rc
));
2222 static int ui_help(void)
2225 static const char *help
[] = {
2226 N_("This is cfdisk, a curses-based disk partitioning program."),
2227 N_("It lets you create, delete, and modify partitions on a block device."),
2229 N_("Command Meaning"),
2230 N_("------- -------"),
2231 N_(" b Toggle bootable flag of the current partition"),
2232 N_(" d Delete the current partition"),
2233 N_(" h Print this screen"),
2234 N_(" n Create new partition from free space"),
2235 N_(" q Quit program without writing partition table"),
2236 N_(" r Reduce or enlarge the current partition"),
2237 N_(" s Fix partitions order (only when in disarray)"),
2238 N_(" t Change the partition type"),
2239 N_(" u Dump disk layout to sfdisk compatible script file"),
2240 N_(" W Write partition table to disk (you must enter uppercase W);"),
2241 N_(" since this might destroy data on the disk, you must either"),
2242 N_(" confirm or deny the write by entering 'yes' or 'no'"),
2243 N_(" x Display/hide extra information about a partition"),
2244 N_("Up Arrow Move cursor to the previous partition"),
2245 N_("Down Arrow Move cursor to the next partition"),
2246 N_("Left Arrow Move cursor to the previous menu item"),
2247 N_("Right Arrow Move cursor to the next menu item"),
2249 N_("Note: All of the commands can be entered with either upper or lower"),
2250 N_("case letters (except for Write)."),
2252 N_("Use lsblk(8) or partx(8) to see more details about the device."),
2255 "Copyright (C) 2014-2017 Karel Zak <kzak@redhat.com>"
2259 for (i
= 0; i
< ARRAY_SIZE(help
); i
++)
2260 mvaddstr(i
, 1, _(help
[i
]));
2262 ui_info(_("Press a key to continue."));
2271 /* TODO: use @sz, now 128bytes */
2272 static int main_menu_ignore_keys(struct cfdisk
*cf
, char *ignore
,
2273 size_t sz
__attribute__((__unused__
)))
2275 struct fdisk_partition
*pa
= get_current_partition(cf
);
2280 if (fdisk_partition_is_freespace(pa
)) {
2281 ignore
[i
++] = 'd'; /* delete */
2282 ignore
[i
++] = 't'; /* set type */
2283 ignore
[i
++] = 'b'; /* set bootable */
2284 ignore
[i
++] = 'r'; /* resize */
2285 cf
->menu
->prefkey
= 'n';
2287 cf
->menu
->prefkey
= 'q';
2289 if (!fdisk_is_label(cf
->cxt
, DOS
) &&
2290 !fdisk_is_label(cf
->cxt
, SGI
))
2294 if (!cf
->wrong_order
)
2297 if (fdisk_is_readonly(cf
->cxt
))
2304 /* returns: error: < 0, success: 0, quit: 1 */
2305 static int main_menu_action(struct cfdisk
*cf
, int key
)
2308 int ref
= 0, rc
, org_order
= cf
->wrong_order
;
2309 const char *info
= NULL
, *warn
= NULL
;
2310 struct fdisk_partition
*pa
;
2317 struct cfdisk_menuitem
*d
= menu_get_menuitem(cf
, cf
->menu
->idx
);
2322 } else if (key
!= 'w' && key
!= 'W')
2323 key
= tolower(key
); /* case insensitive except 'W'rite */
2325 DBG(MENU
, ul_debug("main menu action: key=%c", key
));
2327 if (cf
->menu
->ignore
&& strchr(cf
->menu
->ignore
, key
)) {
2328 DBG(MENU
, ul_debug(" ignore '%c'", key
));
2332 pa
= get_current_partition(cf
);
2335 n
= fdisk_partition_get_partno(pa
);
2337 DBG(MENU
, ul_debug("menu action on %p", pa
));
2342 case 'b': /* Bootable flag */
2344 int fl
= fdisk_is_label(cf
->cxt
, DOS
) ? DOS_FLAG_ACTIVE
:
2345 fdisk_is_label(cf
->cxt
, SGI
) ? SGI_FLAG_BOOT
: 0;
2347 if (fl
&& fdisk_toggle_partition_flag(cf
->cxt
, n
, fl
))
2348 warn
= _("Could not toggle the flag.");
2356 case 'd': /* Delete */
2357 if (fdisk_delete_partition(cf
->cxt
, n
) != 0)
2358 warn
= _("Could not delete partition %zu.");
2360 info
= _("Partition %zu has been deleted.");
2363 case 'h': /* Help */
2370 uint64_t start
, size
, dflt_size
, secs
, max_size
;
2371 struct fdisk_partition
*npa
; /* the new partition */
2372 int expsize
= 0; /* size specified explicitly in sectors */
2374 if (!fdisk_partition_is_freespace(pa
) || !fdisk_partition_has_start(pa
))
2377 /* free space range */
2378 start
= fdisk_partition_get_start(pa
);
2379 size
= max_size
= dflt_size
= fdisk_partition_get_size(pa
) * fdisk_get_sector_size(cf
->cxt
);
2381 if (ui_get_size(cf
, _("Partition size: "), &size
,
2382 fdisk_get_sector_size(cf
->cxt
),
2383 max_size
, &expsize
) == -CFDISK_ERR_ESC
)
2386 secs
= size
/ fdisk_get_sector_size(cf
->cxt
);
2388 npa
= fdisk_new_partition();
2392 if (dflt_size
== size
) /* default is to fillin all free space */
2393 fdisk_partition_end_follow_default(npa
, 1);
2395 fdisk_partition_set_size(npa
, secs
);
2398 fdisk_partition_size_explicit(pa
, 1);
2400 fdisk_partition_set_start(npa
, start
);
2401 fdisk_partition_partno_follow_default(npa
, 1);
2402 /* add to disk label -- libfdisk will ask for missing details */
2403 rc
= fdisk_add_partition(cf
->cxt
, npa
, NULL
);
2404 fdisk_unref_partition(npa
);
2409 case 'q': /* Quit */
2411 case 't': /* Type */
2413 struct fdisk_parttype
*t
;
2415 if (fdisk_partition_is_freespace(pa
))
2417 t
= (struct fdisk_parttype
*) fdisk_partition_get_type(pa
);
2418 t
= ui_get_parttype(cf
, t
);
2421 if (t
&& fdisk_set_partition_type(cf
->cxt
, n
, t
) == 0)
2422 info
= _("Changed type of partition %zu.");
2424 info
= _("The type of partition %zu is unchanged.");
2427 case 'r': /* resize */
2429 struct fdisk_partition
*npa
, *next
;
2430 uint64_t size
, max_size
, secs
;
2432 if (fdisk_partition_is_freespace(pa
) || !fdisk_partition_has_start(pa
))
2435 size
= fdisk_partition_get_size(pa
);
2437 /* is the next freespace? */
2438 next
= fdisk_table_get_partition(cf
->table
, cf
->lines_idx
+ 1);
2439 if (next
&& fdisk_partition_is_freespace(next
))
2440 size
+= fdisk_partition_get_size(next
);
2442 size
*= fdisk_get_sector_size(cf
->cxt
);
2445 if (ui_get_size(cf
, _("New size: "), &size
,
2446 fdisk_get_sector_size(cf
->cxt
),
2447 max_size
, NULL
) == -CFDISK_ERR_ESC
)
2449 secs
= size
/ fdisk_get_sector_size(cf
->cxt
);
2450 npa
= fdisk_new_partition();
2454 fdisk_partition_set_size(npa
, secs
);
2456 rc
= fdisk_set_partition(cf
->cxt
, n
, npa
);
2457 fdisk_unref_partition(npa
);
2460 info
= _("Partition %zu resized.");
2464 case 's': /* Sort */
2465 if (cf
->wrong_order
) {
2466 fdisk_reorder_partitions(cf
->cxt
);
2470 case 'u': /* dUmp */
2471 ui_script_write(cf
);
2473 case 'W': /* Write */
2475 char buf
[64] = { 0 };
2477 if (fdisk_is_readonly(cf
->cxt
)) {
2478 warn
= _("Device is open in read-only mode.");
2483 _("Are you sure you want to write the partition "
2485 _("Type \"yes\" or \"no\", or press ESC to leave this dialog."),
2489 if (rc
<= 0 || (strcasecmp(buf
, "yes") != 0 &&
2490 strcasecmp(buf
, _("yes")) != 0)) {
2491 info
= _("Did not write partition table to disk.");
2494 rc
= fdisk_write_disklabel(cf
->cxt
);
2496 warn
= _("Failed to write disklabel.");
2498 if (cf
->device_is_used
)
2499 fdisk_reread_changes(cf
->cxt
, cf
->original_layout
);
2501 fdisk_reread_partition_table(cf
->cxt
);
2502 info
= _("The partition table has been altered.");
2521 ui_warnx(warn
, n
+ 1);
2523 ui_info(info
, n
+ 1);
2524 else if (key
== 'n' && cf
->wrong_order
&& org_order
== 0)
2525 ui_info(_("Note that partition table entries are not in disk order now."));
2530 static void ui_resize_refresh(struct cfdisk
*cf
)
2532 DBG(UI
, ul_debug("ui resize/refresh"));
2534 menu_refresh_size(cf
);
2540 static void toggle_show_extra(struct cfdisk
*cf
)
2542 if (cf
->show_extra
&& cf
->act_win
) {
2543 wclear(cf
->act_win
);
2546 cf
->show_extra
= cf
->show_extra
? 0 : 1;
2550 DBG(MENU
, ul_debug("extra: %s", cf
->show_extra
? "ENABLED" : "DISABLED" ));
2553 static int ui_run(struct cfdisk
*cf
)
2559 DBG(UI
, ul_debug("start cols=%zu, lines=%zu", ui_cols
, ui_lines
));
2561 if (fdisk_get_collision(cf
->cxt
)) {
2562 ui_warnx(_("Device already contains a %s signature; it will be removed by a write command."),
2563 fdisk_get_collision(cf
->cxt
));
2564 fdisk_enable_wipe(cf
->cxt
, 1);
2565 ui_hint(_("Press a key to continue."));
2569 if (!fdisk_has_label(cf
->cxt
) || cf
->zero_start
) {
2570 rc
= ui_create_label(cf
);
2573 ui_err(EXIT_FAILURE
,
2574 _("failed to create a new disklabel"));
2581 rc
= lines_refresh(cf
);
2583 ui_errx(EXIT_FAILURE
, _("failed to read partitions"));
2585 menu_push(cf
, main_menuitems
);
2586 cf
->menu
->ignore_cb
= main_menu_ignore_keys
;
2588 rc
= ui_refresh(cf
);
2595 if (fdisk_is_readonly(cf
->cxt
))
2596 ui_warnx(_("Device is open in read-only mode. Changes will remain in memory only."));
2597 else if (cf
->device_is_used
)
2598 ui_warnx(_("Device is currently in use, repartitioning is probably a bad idea."));
2599 else if (cf
->wrong_order
)
2600 ui_info(_("Note that partition table entries are not in disk order now."));
2610 /* Note that ncurses getch() returns ERR when interrupted
2611 * by signal, but SLang does not interrupt at all. */
2612 ui_resize_refresh(cf
);
2615 if (key
== '\014') { /* ^L refresh */
2616 ui_resize_refresh(cf
);
2619 if (ui_menu_move(cf
, key
) == 0)
2622 DBG(UI
, ul_debug("main action key >%1$c< [\\0%1$o].", key
));
2626 case '\016': /* ^N */
2627 case 'j': /* Vi-like alternative */
2628 ui_table_goto(cf
, cf
->lines_idx
+ 1);
2631 case '\020': /* ^P */
2632 case 'k': /* Vi-like alternative */
2633 ui_table_goto(cf
, (int) cf
->lines_idx
- 1);
2637 ui_table_goto(cf
, (int) cf
->lines_idx
- cf
->page_sz
);
2642 ui_table_goto(cf
, 0);
2646 ui_table_goto(cf
, cf
->lines_idx
+ cf
->page_sz
);
2651 ui_table_goto(cf
, (int) cf
->nlines
- 1);
2656 rc
= main_menu_action(cf
, 0);
2659 case 'x': /* Extra */
2660 toggle_show_extra(cf
);
2663 rc
= main_menu_action(cf
, key
);
2675 DBG(UI
, ul_debug("end"));
2679 static void __attribute__((__noreturn__
)) usage(void)
2682 fputs(USAGE_HEADER
, out
);
2684 _(" %1$s [options] <disk>\n"), program_invocation_short_name
);
2686 fputs(USAGE_SEPARATOR
, out
);
2687 fputs(_("Display or manipulate a disk partition table.\n"), out
);
2689 fputs(USAGE_OPTIONS
, out
);
2691 _(" -L, --color[=<when>] colorize output (%s, %s or %s)\n"), "auto", "always", "never");
2693 " %s\n", USAGE_COLORS_DEFAULT
);
2694 fputs(_(" -z, --zero start with zeroed partition table\n"), out
);
2696 _(" --lock[=<mode>] use exclusive device lock (%s, %s or %s)\n"), "yes", "no", "nonblock");
2697 fputs(_(" -r, --read-only forced open cfdisk in read-only mode\n"), out
);
2699 fputs(USAGE_SEPARATOR
, out
);
2700 printf(USAGE_HELP_OPTIONS(26));
2702 printf(USAGE_MAN_TAIL("cfdisk(8)"));
2706 int main(int argc
, char *argv
[])
2708 const char *diskpath
= NULL
, *lockmode
= NULL
;
2709 int rc
, c
, colormode
= UL_COLORMODE_UNDEF
;
2711 struct cfdisk _cf
= { .lines_idx
= 0 },
2714 OPT_LOCK
= CHAR_MAX
+ 1
2716 static const struct option longopts
[] = {
2717 { "color", optional_argument
, NULL
, 'L' },
2718 { "lock", optional_argument
, NULL
, OPT_LOCK
},
2719 { "help", no_argument
, NULL
, 'h' },
2720 { "version", no_argument
, NULL
, 'V' },
2721 { "zero", no_argument
, NULL
, 'z' },
2722 { "read-only", no_argument
, NULL
, 'r' },
2723 { NULL
, 0, NULL
, 0 },
2726 setlocale(LC_ALL
, "");
2727 bindtextdomain(PACKAGE
, LOCALEDIR
);
2728 textdomain(PACKAGE
);
2729 close_stdout_atexit();
2731 while((c
= getopt_long(argc
, argv
, "L::hVzr", longopts
, NULL
)) != -1) {
2737 colormode
= UL_COLORMODE_AUTO
;
2739 colormode
= colormode_or_err(optarg
,
2740 _("unsupported color mode"));
2746 print_version(EXIT_SUCCESS
);
2759 errtryhelp(EXIT_FAILURE
);
2763 colors_init(colormode
, "cfdisk");
2765 fdisk_init_debug(0);
2766 scols_init_debug(0);
2767 cfdisk_init_debug();
2768 cf
->cxt
= fdisk_new_context();
2770 err(EXIT_FAILURE
, _("failed to allocate libfdisk context"));
2772 fdisk_set_ask(cf
->cxt
, ask_callback
, (void *) cf
);
2774 if (optind
== argc
) {
2777 for (i
= 0; i
< ARRAY_SIZE(default_disks
); i
++) {
2778 if (access(default_disks
[i
], F_OK
) == 0) {
2779 diskpath
= default_disks
[i
];
2784 diskpath
= default_disks
[0]; /* default, used for "cannot open" */
2786 diskpath
= argv
[optind
];
2788 rc
= fdisk_assign_device(cf
->cxt
, diskpath
, read_only
);
2789 if (rc
== -EACCES
&& read_only
== 0)
2790 rc
= fdisk_assign_device(cf
->cxt
, diskpath
, 1);
2792 err(EXIT_FAILURE
, _("cannot open %s"), diskpath
);
2794 if (!fdisk_is_readonly(cf
->cxt
)) {
2795 if (blkdev_lock(fdisk_get_devfd(cf
->cxt
), diskpath
, lockmode
) != 0)
2796 return EXIT_FAILURE
;
2798 cf
->device_is_used
= fdisk_device_is_used(cf
->cxt
);
2799 fdisk_get_partitions(cf
->cxt
, &cf
->original_layout
);
2802 /* Don't use err(), warn() from this point */
2807 cfdisk_free_lines(cf
);
2811 fdisk_unref_table(cf
->table
);
2812 #ifdef HAVE_LIBMOUNT
2813 mnt_unref_table(cf
->fstab
);
2814 mnt_unref_table(cf
->mtab
);
2815 mnt_unref_cache(cf
->mntcache
);
2817 rc
= fdisk_deassign_device(cf
->cxt
, cf
->nwrites
== 0);
2818 fdisk_unref_context(cf
->cxt
);
2819 DBG(MISC
, ul_debug("bye! [rc=%d]", rc
));
2820 return rc
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;