]> git.ozlabs.org Git - petitboot/blob - ui/ncurses/nc-cui.c
ui/ncurses: Fix adding unnecessary leading slashes to paths
[petitboot] / ui / ncurses / nc-cui.c
1 /*
2  *  Copyright (C) 2009 Sony Computer Entertainment Inc.
3  *  Copyright 2009 Sony Corp.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; version 2 of the License.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #if defined(HAVE_CONFIG_H)
20 #include "config.h"
21 #endif
22
23 #include <assert.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/reboot.h>
29
30 #include "log/log.h"
31 #include "pb-protocol/pb-protocol.h"
32 #include "talloc/talloc.h"
33 #include "waiter/waiter.h"
34 #include "process/process.h"
35 #include "i18n/i18n.h"
36 #include "ui/common/discover-client.h"
37 #include "ui/common/ui-system.h"
38 #include "nc-cui.h"
39 #include "nc-boot-editor.h"
40 #include "nc-config.h"
41 #include "nc-add-url.h"
42 #include "nc-sysinfo.h"
43 #include "nc-lang.h"
44 #include "nc-helpscreen.h"
45 #include "nc-statuslog.h"
46 #include "nc-subset.h"
47
48 extern const struct help_text main_menu_help_text;
49
50 static bool cui_detached = false;
51
52 static struct pmenu *main_menu_init(struct cui *cui);
53
54 static bool lockdown_active(void)
55 {
56         bool lockdown = false;
57         if (access(LOCKDOWN_FILE, F_OK) != -1)
58                 lockdown = true;
59         return lockdown;
60 }
61
62 static void cui_start(void)
63 {
64         initscr();                      /* Initialize ncurses. */
65         cbreak();                       /* Disable line buffering. */
66         noecho();                       /* Disable getch() echo. */
67         keypad(stdscr, TRUE);           /* Enable num keypad keys. */
68         nonl();                         /* Disable new-line translation. */
69         intrflush(stdscr, FALSE);       /* Disable interrupt flush. */
70         curs_set(0);                    /* Make cursor invisible */
71         nodelay(stdscr, TRUE);          /* Enable non-blocking getch() */
72
73         /* We may be operating with an incorrect $TERM type; in this case
74          * the keymappings will be slightly broken. We want at least
75          * backspace to work though, so we'll define both DEL and ^H to
76          * map to backspace */
77         define_key("\x7f", KEY_BACKSPACE);
78         define_key("\x08", KEY_BACKSPACE);
79
80         /* we need backtab too, for form navigation. vt220 doesn't include
81          * this (kcbt), but we don't want to require a full linux/xterm termcap
82          */
83         define_key("\x1b[Z", KEY_BTAB);
84
85         /* We'll define a few other keys too since they're commonly
86          * used for navigation but the escape character will cause
87          * Petitboot to exit if they're left undefined */
88         define_key("\x1b\x5b\x35\x7e", KEY_PPAGE);
89         define_key("\x1b\x5b\x36\x7e", KEY_NPAGE);
90         define_key("\x1b\x5b\x31\x7e", KEY_HOME);
91         define_key("\x1b\x5b\x34\x7e", KEY_END);
92         define_key("\x1b\x4f\x48", KEY_HOME);
93         define_key("\x1b\x4f\x46", KEY_END);
94         define_key("OH", KEY_HOME);
95         define_key("OF", KEY_END);
96         define_key("\x1b\x5b\x41", KEY_UP);
97         define_key("\x1b\x5b\x42", KEY_DOWN);
98         define_key("\x1b\x5b\x33\x7e", KEY_DC);
99
100         while (getch() != ERR)          /* flush stdin */
101                 (void)0;
102 }
103
104 static void cui_atexit(void)
105 {
106         if (cui_detached)
107                 return;
108
109         clear();
110         refresh();
111         endwin();
112
113         bool lockdown = lockdown_active();
114
115         while (lockdown) {
116                 sync();
117                 reboot(RB_AUTOBOOT);
118         }
119 }
120
121 /**
122  * cui_abort - Signal the main cui program loop to exit.
123  *
124  * Sets cui.abort, which causes the cui_run() routine to return.
125  */
126
127 void cui_abort(struct cui *cui)
128 {
129         pb_log("%s: exiting\n", __func__);
130         cui->abort = 1;
131 }
132
133 /**
134  * cui_resize - Signal the main cui program loop to resize
135  *
136  * Called at SIGWINCH.
137  */
138
139 void cui_resize(struct cui *cui)
140 {
141         pb_debug("%s: resizing\n", __func__);
142         cui->resize = 1;
143 }
144
145 /**
146  * cui_on_exit - A generic main menu exit callback.
147  */
148
149 void cui_on_exit(struct pmenu *menu)
150 {
151         cui_abort(cui_from_pmenu(menu));
152 }
153
154 /**
155  * cui_run_cmd - A generic cb to run the supplied command.
156  */
157
158 int cui_run_cmd(struct pmenu_item *item)
159 {
160         int result;
161         struct cui *cui = cui_from_item(item);
162         const char **cmd_argv = item->data;
163
164         nc_scr_status_printf(cui->current, _("Running %s..."), cmd_argv[0]);
165
166         def_prog_mode();
167
168         result = process_run_simple_argv(item, cmd_argv);
169
170         reset_prog_mode();
171         redrawwin(cui->current->main_ncw);
172
173         if (result) {
174                 pb_log("%s: failed: '%s'\n", __func__, cmd_argv[0]);
175                 nc_scr_status_printf(cui->current, _("Failed: %s"),
176                                 cmd_argv[0]);
177         }
178
179         return result;
180 }
181
182 /**
183  * cui_boot - A generic cb to run kexec.
184  */
185
186 static int cui_boot(struct pmenu_item *item)
187 {
188         int result;
189         struct cui *cui = cui_from_item(item);
190         struct cui_opt_data *cod = cod_from_item(item);
191
192         assert(cui->current == &cui->main->scr);
193
194         pb_debug("%s: %s\n", __func__, cod->name);
195
196         nc_scr_status_printf(cui->current, _("Booting %s..."), cod->name);
197
198         result = discover_client_boot(cui->client, NULL, cod->opt, cod->bd);
199
200         if (result) {
201                 nc_scr_status_printf(cui->current,
202                                 _("Failed: boot %s"), cod->bd->image);
203         }
204
205         return 0;
206 }
207
208 static void cui_boot_editor_on_exit(struct cui *cui,
209                 struct pmenu_item *item,
210                 struct pb_boot_data *bd)
211 {
212         struct pmenu *menu = cui->main;
213         struct cui_opt_data *cod;
214         int idx, top, rows, cols;
215         static int user_idx = 0;
216
217         /* Was the edit cancelled? */
218         if (!bd) {
219                 cui_set_current(cui, &cui->main->scr);
220                 talloc_free(cui->boot_editor);
221                 cui->boot_editor = NULL;
222                 return;
223         }
224
225         /* Is this was a new item, we'll need to update the menu */
226         if (!item) {
227                 int insert_pt;
228
229                 cod = talloc_zero(NULL, struct cui_opt_data);
230                 cod->name = talloc_asprintf(cod, _("User item %u"), ++user_idx);
231
232                 item = pmenu_item_create(menu, cod->name);
233                 if (!item) {
234                         talloc_free(cod);
235                         goto out;
236                 }
237
238                 item->on_edit = cui_item_edit;
239                 item->on_execute = cui_boot;
240                 item->data = cod;
241
242                 talloc_steal(item, cod);
243
244                 /* Detach the items array. */
245                 set_menu_items(menu->ncm, NULL);
246
247                 /* Insert new item at insert_pt. */
248                 insert_pt = pmenu_grow(menu, 1);
249                 pmenu_item_insert(menu, item, insert_pt);
250
251                 /* Re-attach the items array. */
252                 set_menu_items(menu->ncm, menu->items);
253
254                 /* If our index is above the current top row, align
255                  * us to the new top. Otherwise, align us to the new
256                  * bottom */
257                 menu_format(cui->main->ncm, &rows, &cols);
258                 top = top_row(cui->main->ncm);
259                 idx = item_index(item->nci);
260
261                 if (top >= idx)
262                         top = idx;
263                 else
264                         top = idx < rows ? 0 : idx - rows + 1;
265
266                 set_top_row(cui->main->ncm, top);
267                 set_current_item(item->pmenu->ncm, item->nci);
268
269                 nc_scr_post(&menu->scr);
270         } else {
271                 cod = item->data;
272         }
273
274         cod->bd = talloc_steal(cod, bd);
275
276 out:
277         cui_set_current(cui, &cui->main->scr);
278         talloc_free(cui->boot_editor);
279         cui->boot_editor = NULL;
280 }
281
282 void cui_item_edit(struct pmenu_item *item)
283 {
284         struct cui *cui = cui_from_item(item);
285         cui->boot_editor = boot_editor_init(cui, item, cui->sysinfo,
286                                         cui_boot_editor_on_exit);
287         cui_set_current(cui, boot_editor_scr(cui->boot_editor));
288 }
289
290 void cui_item_new(struct pmenu *menu)
291 {
292         struct cui *cui = cui_from_pmenu(menu);
293         cui->boot_editor = boot_editor_init(cui, NULL, cui->sysinfo,
294                                         cui_boot_editor_on_exit);
295         cui_set_current(cui, boot_editor_scr(cui->boot_editor));
296 }
297
298 static void cui_sysinfo_exit(struct cui *cui)
299 {
300         cui_set_current(cui, &cui->main->scr);
301         talloc_free(cui->sysinfo_screen);
302         cui->sysinfo_screen = NULL;
303 }
304
305 void cui_show_sysinfo(struct cui *cui)
306 {
307         cui->sysinfo_screen = sysinfo_screen_init(cui, cui->sysinfo,
308                         cui_sysinfo_exit);
309         cui_set_current(cui, sysinfo_screen_scr(cui->sysinfo_screen));
310 }
311
312 static void cui_config_exit(struct cui *cui)
313 {
314         cui_set_current(cui, &cui->main->scr);
315         talloc_free(cui->config_screen);
316         cui->config_screen = NULL;
317 }
318
319 void cui_show_config(struct cui *cui)
320 {
321         cui->config_screen = config_screen_init(cui, cui->config,
322                         cui->sysinfo, cui_config_exit);
323         cui_set_current(cui, config_screen_scr(cui->config_screen));
324 }
325
326 static void cui_lang_exit(struct cui *cui)
327 {
328         cui_set_current(cui, &cui->main->scr);
329         talloc_free(cui->lang_screen);
330         cui->lang_screen = NULL;
331 }
332
333 void cui_show_lang(struct cui *cui)
334 {
335         cui->lang_screen = lang_screen_init(cui, cui->config, cui_lang_exit);
336         cui_set_current(cui, lang_screen_scr(cui->lang_screen));
337 }
338
339 static void cui_statuslog_exit(struct cui *cui)
340 {
341         cui_set_current(cui, &cui->main->scr);
342         talloc_free(cui->statuslog_screen);
343         cui->statuslog_screen = NULL;
344 }
345
346 void cui_show_statuslog(struct cui *cui)
347 {
348         cui->statuslog_screen = statuslog_screen_init(cui, cui_statuslog_exit);
349         cui_set_current(cui, statuslog_screen_scr(cui->statuslog_screen));
350 }
351
352 static void cui_add_url_exit(struct cui *cui)
353 {
354         cui_set_current(cui, &cui->main->scr);
355         talloc_free(cui->add_url_screen);
356         cui->add_url_screen = NULL;
357 }
358
359 void cui_show_add_url(struct cui *cui)
360 {
361         cui->add_url_screen = add_url_screen_init(cui, cui_add_url_exit);
362         cui_set_current(cui, add_url_screen_scr(cui->add_url_screen));
363 }
364
365 static void cui_help_exit(struct cui *cui)
366 {
367         cui_set_current(cui, help_screen_return_scr(cui->help_screen));
368         talloc_free(cui->help_screen);
369         cui->help_screen = NULL;
370 }
371
372 void cui_show_help(struct cui *cui, const char *title,
373                 const struct help_text *text)
374 {
375         if (!cui->current)
376                 return;
377
378         if (cui->help_screen)
379                 return;
380
381         cui->help_screen = help_screen_init(cui, cui->current,
382                         title, text, cui_help_exit);
383
384         if (cui->help_screen)
385                 cui_set_current(cui, help_screen_scr(cui->help_screen));
386 }
387
388 static void cui_subset_exit(struct cui *cui)
389 {
390         cui_set_current(cui, subset_screen_return_scr(cui->subset_screen));
391         talloc_free(cui->subset_screen);
392         cui->subset_screen = NULL;
393 }
394
395 void cui_show_subset(struct cui *cui, const char *title,
396                      void *arg)
397 {
398         if (!cui->current)
399                 return;
400
401         if (cui->subset_screen)
402                 return;
403
404         cui->subset_screen = subset_screen_init(cui, cui->current,
405                         title, arg, cui_subset_exit);
406
407         if (cui->subset_screen)
408                 cui_set_current(cui, subset_screen_scr(cui->subset_screen));
409 }
410
411 /**
412  * cui_set_current - Set the currently active screen and redraw it.
413  */
414
415 struct nc_scr *cui_set_current(struct cui *cui, struct nc_scr *scr)
416 {
417         struct nc_scr *old;
418
419         DBGS("%p -> %p\n", cui->current, scr);
420
421         assert(cui->current != scr);
422
423         old = cui->current;
424         nc_scr_unpost(old);
425
426         cui->current = scr;
427
428         nc_scr_post(cui->current);
429
430         return old;
431 }
432
433 static bool process_global_keys(struct cui *cui, int key)
434 {
435         switch (key) {
436         case 0xc:
437                 if (cui->current && cui->current->main_ncw)
438                         wrefresh(curscr);
439                 return true;
440         }
441         return false;
442 }
443
444 /**
445  * cui_process_key - Process input on stdin.
446  */
447
448 static int cui_process_key(void *arg)
449 {
450         struct cui *cui = cui_from_arg(arg);
451
452         assert(cui->current);
453
454         for (;;) {
455                 int c = getch();
456
457                 pb_debug("%s: got key %d\n", __func__, c);
458
459                 if (c == ERR)
460                         break;
461
462                 if (!cui->has_input) {
463                         cui->has_input = true;
464                         if (cui->client) {
465                                 pb_log("UI input received (key = %d), aborting "
466                                         "default boot\n", c);
467                                 discover_client_cancel_default(cui->client);
468                         } else {
469                                 pb_log("UI input received (key = %d), aborting "
470                                         "once server connects\n", c);
471                         }
472                 }
473
474                 if (process_global_keys(cui, c))
475                         continue;
476
477                 cui->current->process_key(cui->current, c);
478         }
479
480         return 0;
481 }
482
483 /**
484  * cui_process_js - Process joystick events.
485  */
486
487 static int cui_process_js(void *arg)
488 {
489         struct cui *cui = cui_from_arg(arg);
490         int c;
491
492         c = pjs_process_event(cui->pjs);
493
494         if (c) {
495                 ungetch(c);
496                 cui_process_key(arg);
497         }
498
499         return 0;
500 }
501
502 /**
503  * cui_handle_resize - Handle the term resize.
504  */
505
506 static void cui_handle_resize(struct cui *cui)
507 {
508         struct winsize ws;
509
510         if (ioctl(1, TIOCGWINSZ, &ws) == -1) {
511                 pb_log("%s: ioctl failed: %s\n", __func__, strerror(errno));
512                 return;
513         }
514
515         pb_debug("%s: {%u,%u}\n", __func__, ws.ws_row, ws.ws_col);
516
517         wclear(cui->current->main_ncw);
518         resize_term(ws.ws_row, ws.ws_col);
519         cui->current->resize(cui->current);
520
521         /* For some reason this makes ncurses redraw the screen */
522         getch();
523         redrawwin(cui->current->main_ncw);
524         wrefresh(cui->current->main_ncw);
525 }
526
527 /**
528  * cui_device_add - Client device_add callback.
529  *
530  * Creates menu_items for all the device boot_options and inserts those
531  * menu_items into the main menu.  Redraws the main menu if it is active.
532  */
533
534 static int cui_boot_option_add(struct device *dev, struct boot_option *opt,
535                 void *arg)
536 {
537         struct pmenu_item *i, *dev_hdr = NULL;
538         struct cui *cui = cui_from_arg(arg);
539         struct cui_opt_data *cod;
540         const char *tab = "  ";
541         unsigned int insert_pt;
542         int result, rows, cols;
543         ITEM *selected;
544         char *name;
545
546         pb_debug("%s: %p %s\n", __func__, opt, opt->id);
547
548         selected = current_item(cui->main->ncm);
549         menu_format(cui->main->ncm, &rows, &cols);
550
551         if (cui->current == &cui->main->scr)
552                 nc_scr_unpost(cui->current);
553
554         /* Check if the boot device is new */
555         dev_hdr = pmenu_find_device(cui->main, dev, opt);
556
557         /* All actual boot entries are 'tabbed' across */
558         name = talloc_asprintf(cui->main, "%s%s",
559                         tab, opt->name ? : "Unknown Name");
560
561         /* Save the item in opt->ui_info for cui_device_remove() */
562         opt->ui_info = i = pmenu_item_create(cui->main, name);
563         talloc_free(name);
564         if (!i)
565                 return -1;
566
567         i->on_edit = cui_item_edit;
568         i->on_execute = cui_boot;
569         i->data = cod = talloc(i, struct cui_opt_data);
570
571         cod->opt = opt;
572         cod->dev = dev;
573         cod->opt_hash = pb_opt_hash(dev, opt);
574         cod->name = opt->name;
575         cod->bd = talloc(i, struct pb_boot_data);
576
577         cod->bd->image = talloc_strdup(cod->bd, opt->boot_image_file);
578         cod->bd->initrd = talloc_strdup(cod->bd, opt->initrd_file);
579         cod->bd->dtb = talloc_strdup(cod->bd, opt->dtb_file);
580         cod->bd->args = talloc_strdup(cod->bd, opt->boot_args);
581         cod->bd->args_sig_file = talloc_strdup(cod->bd, opt->args_sig_file);
582
583         /* This disconnects items array from menu. */
584         result = set_menu_items(cui->main->ncm, NULL);
585
586         if (result)
587                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
588
589         /* Insert new items at insert_pt. */
590         if (dev_hdr) {
591                 insert_pt = pmenu_grow(cui->main, 2);
592                 pmenu_item_insert(cui->main, dev_hdr, insert_pt);
593                 pb_log("%s: adding new device hierarchy %s\n",
594                         __func__,opt->device_id);
595                 pmenu_item_insert(cui->main, i, insert_pt+1);
596         } else {
597                 insert_pt = pmenu_grow(cui->main, 1);
598                 pmenu_item_add(cui->main, i, insert_pt);
599         }
600
601         pb_log("%s: adding opt '%s'\n", __func__, cod->name);
602         pb_log("   image  '%s'\n", cod->bd->image);
603         pb_log("   initrd '%s'\n", cod->bd->initrd);
604         pb_log("   args   '%s'\n", cod->bd->args);
605         pb_log("   argsig '%s'\n", cod->bd->args_sig_file);
606
607         /* Re-attach the items array. */
608         result = set_menu_items(cui->main->ncm, cui->main->items);
609
610         if (result)
611                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
612
613         if (0) {
614                 pb_log("%s\n", __func__);
615                 pmenu_dump_items(cui->main->items,
616                         item_count(cui->main->ncm) + 1);
617         }
618
619         if (!item_visible(selected)) {
620                 int idx, top;
621
622                 top = top_row(cui->main->ncm);
623                 idx = item_index(selected);
624
625                 /* If our index is above the current top row, align
626                  * us to the new top. Otherwise, align us to the new
627                  * bottom */
628                 top = top < idx ? idx - rows + 1 : idx;
629
630                 set_top_row(cui->main->ncm, top);
631                 set_current_item(cui->main->ncm, selected);
632         }
633
634         if (cui->current == &cui->main->scr)
635                 nc_scr_post(cui->current);
636
637         return 0;
638 }
639
640 /**
641  * cui_device_remove - Client device remove callback.
642  *
643  * Removes all the menu_items for the device from the main menu and redraws the
644  * main menu if it is active.
645  */
646
647 static void cui_device_remove(struct device *dev, void *arg)
648 {
649         struct cui *cui = cui_from_arg(arg);
650         struct boot_option *opt;
651         unsigned int i;
652         int rows, cols, top, last;
653         int result;
654
655         pb_log("%s: %p %s\n", __func__, dev, dev->id);
656
657         if (cui->current == &cui->main->scr)
658                 nc_scr_unpost(cui->current);
659
660         /* This disconnects items array from menu. */
661
662         result = set_menu_items(cui->main->ncm, NULL);
663
664         if (result)
665                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
666
667         list_for_each_entry(&dev->boot_options, opt, list) {
668                 struct pmenu_item *item = pmenu_item_from_arg(opt->ui_info);
669
670                 assert(pb_protocol_device_cmp(dev, cod_from_item(item)->dev));
671                 pmenu_remove(cui->main, item);
672         }
673
674         /* Manually remove remaining device hierarchy item */
675         for (i=0; i < cui->main->item_count; i++) {
676                 struct pmenu_item *item = item_userptr(cui->main->items[i]);
677                 if (!item || !item->data )
678                         continue;
679
680                 struct cui_opt_data *data = item->data;
681                 if (data && data->dev && data->dev == dev)
682                         pmenu_remove(cui->main,item);
683         }
684
685         /* Re-attach the items array. */
686
687         result = set_menu_items(cui->main->ncm, cui->main->items);
688
689         /* Move cursor to 'Exit' menu entry */
690         menu_format(cui->main->ncm, &rows, &cols);
691         last = cui->main->item_count - 1;
692         set_current_item(cui->main->ncm, cui->main->items[last]);
693         if (!item_visible(cui->main->items[last])) {
694                 top = last < rows ? 0 : last - rows + 1;
695                 set_top_row(cui->main->ncm, top);
696         }
697
698         if (result)
699                 pb_log("%s: set_menu_items failed: %d\n", __func__, result);
700
701         if (0) {
702                 pb_log("%s\n", __func__);
703                 pmenu_dump_items(cui->main->items,
704                         item_count(cui->main->ncm) + 1);
705         }
706
707         if (cui->current == &cui->main->scr)
708                 nc_scr_post(cui->current);
709 }
710
711 static void cui_update_status(struct status *status, void *arg)
712 {
713         struct cui *cui = cui_from_arg(arg);
714
715         statuslog_append_steal(cui, cui->statuslog, status);
716
717         /* Ignore status messages from the backlog */
718         if (!status->backlog)
719                 nc_scr_status_printf(cui->current, "%s", status->message);
720 }
721
722 static void cui_update_mm_title(struct cui *cui)
723 {
724         struct nc_frame *frame = &cui->main->scr.frame;
725
726         talloc_free(frame->rtitle);
727
728         frame->rtitle = talloc_strdup(cui->main, cui->sysinfo->type);
729         if (cui->sysinfo->identifier)
730                 frame->rtitle = talloc_asprintf_append(frame->rtitle,
731                                 " %s", cui->sysinfo->identifier);
732
733         if (cui->current == &cui->main->scr)
734                 nc_scr_post(cui->current);
735 }
736
737 static void cui_update_sysinfo(struct system_info *sysinfo, void *arg)
738 {
739         struct cui *cui = cui_from_arg(arg);
740         cui->sysinfo = talloc_steal(cui, sysinfo);
741
742         /* if we're currently displaying the system info screen, inform it
743          * of the updated information. */
744         if (cui->sysinfo_screen)
745                 sysinfo_screen_update(cui->sysinfo_screen, sysinfo);
746
747         if (cui->subset_screen)
748                 subset_screen_update(cui->subset_screen);
749
750         /* ... and do the same with the config screen... */
751         if (cui->config_screen)
752                 config_screen_update(cui->config_screen, cui->config, sysinfo);
753
754         /* ... and the boot editor. */
755         if (cui->boot_editor)
756                 boot_editor_update(cui->boot_editor, sysinfo);
757
758         cui_update_mm_title(cui);
759 }
760
761 static void cui_update_language(struct cui *cui, char *lang)
762 {
763         bool repost_menu;
764         char *cur_lang;
765
766         cur_lang = setlocale(LC_ALL, NULL);
767         if (cur_lang && !strcmp(cur_lang, lang))
768                 return;
769
770         setlocale(LC_ALL, lang);
771
772         /* we'll need to update the menu: drop all items and repopulate */
773         repost_menu = cui->current == &cui->main->scr;
774         if (repost_menu)
775                 nc_scr_unpost(cui->current);
776
777         talloc_free(cui->main);
778         cui->main = main_menu_init(cui);
779
780         if (repost_menu) {
781                 cui->current = &cui->main->scr;
782                 nc_scr_post(cui->current);
783         }
784
785         discover_client_enumerate(cui->client);
786 }
787
788 static void cui_update_config(struct config *config, void *arg)
789 {
790         struct cui *cui = cui_from_arg(arg);
791         cui->config = talloc_steal(cui, config);
792
793         if (config->lang)
794                 cui_update_language(cui, config->lang);
795
796         if (cui->subset_screen)
797                 subset_screen_update(cui->subset_screen);
798
799         if (cui->config_screen)
800                 config_screen_update(cui->config_screen, config, cui->sysinfo);
801
802         if (config->safe_mode)
803                 nc_scr_status_printf(cui->current,
804                                 _("SAFE MODE: select '%s' to continue"),
805                                 _("Rescan devices"));
806 }
807
808 int cui_send_config(struct cui *cui, struct config *config)
809 {
810         return discover_client_send_config(cui->client, config);
811 }
812
813 int cui_send_url(struct cui *cui, char * url)
814 {
815         return discover_client_send_url(cui->client, url);
816 }
817
818 void cui_send_reinit(struct cui *cui)
819 {
820         discover_client_send_reinit(cui->client);
821 }
822
823 static int menu_sysinfo_execute(struct pmenu_item *item)
824 {
825         cui_show_sysinfo(cui_from_item(item));
826         return 0;
827 }
828
829 static int menu_config_execute(struct pmenu_item *item)
830 {
831         cui_show_config(cui_from_item(item));
832         return 0;
833 }
834
835 static int menu_lang_execute(struct pmenu_item *item)
836 {
837         cui_show_lang(cui_from_item(item));
838         return 0;
839 }
840
841 static int menu_statuslog_execute(struct pmenu_item *item)
842 {
843         cui_show_statuslog(cui_from_item(item));
844         return 0;
845 }
846
847 static int menu_reinit_execute(struct pmenu_item *item)
848 {
849         if (cui_from_item(item)->client)
850                 cui_send_reinit(cui_from_item(item));
851         return 0;
852 }
853
854 static int menu_add_url_execute(struct pmenu_item *item)
855 {
856         if (cui_from_item(item)->client)
857                 cui_show_add_url(cui_from_item(item));
858         return 0;
859 }
860
861 /**
862  * pb_mm_init - Setup the main menu instance.
863  */
864 static struct pmenu *main_menu_init(struct cui *cui)
865 {
866         struct pmenu_item *i;
867         struct pmenu *m;
868         int result;
869         bool lockdown = lockdown_active();
870
871         m = pmenu_init(cui, 8, cui_on_exit);
872         if (!m) {
873                 pb_log("%s: failed\n", __func__);
874                 return NULL;
875         }
876
877         m->on_new = cui_item_new;
878
879         m->scr.frame.ltitle = talloc_asprintf(m,
880                 "Petitboot (" PACKAGE_VERSION ")");
881         m->scr.frame.rtitle = NULL;
882         m->scr.frame.help = talloc_strdup(m,
883                 _("Enter=accept, e=edit, n=new, x=exit, l=language, g=log, h=help"));
884         m->scr.frame.status = talloc_strdup(m, _("Welcome to Petitboot"));
885
886         /* add a separator */
887         i = pmenu_item_create(m, " ");
888         item_opts_off(i->nci, O_SELECTABLE);
889         pmenu_item_insert(m, i, 0);
890
891         /* add system items */
892         i = pmenu_item_create(m, _("System information"));
893         i->on_execute = menu_sysinfo_execute;
894         pmenu_item_insert(m, i, 1);
895
896         i = pmenu_item_create(m, _("System configuration"));
897         i->on_execute = menu_config_execute;
898         pmenu_item_insert(m, i, 2);
899
900         i = pmenu_item_create(m, _("System status log"));
901         i->on_execute = menu_statuslog_execute;
902         pmenu_item_insert(m, i, 3);
903
904         /* this label isn't translated, so we don't want a gettext() here */
905         i = pmenu_item_create(m, "Language");
906         i->on_execute = menu_lang_execute;
907         pmenu_item_insert(m, i, 4);
908
909         i = pmenu_item_create(m, _("Rescan devices"));
910         i->on_execute = menu_reinit_execute;
911         pmenu_item_insert(m, i, 5);
912
913         i = pmenu_item_create(m, _("Retrieve config from URL"));
914         i->on_execute = menu_add_url_execute;
915         pmenu_item_insert(m, i, 6);
916
917         if (lockdown)
918                 i = pmenu_item_create(m, _("Reboot"));
919         else
920                 i = pmenu_item_create(m, _("Exit to shell"));
921         i->on_execute = pmenu_exit_cb;
922         pmenu_item_insert(m, i, 7);
923
924         result = pmenu_setup(m);
925
926         if (result) {
927                 pb_log("%s:%d: pmenu_setup failed: %s\n", __func__, __LINE__,
928                         strerror(errno));
929                 goto fail_setup;
930         }
931
932         m->help_title = _("main menu");
933         m->help_text = &main_menu_help_text;
934
935         menu_opts_off(m->ncm, O_SHOWDESC);
936         set_menu_mark(m->ncm, " *");
937         set_current_item(m->ncm, i->nci);
938
939         return m;
940
941 fail_setup:
942         talloc_free(m);
943         return NULL;
944 }
945
946 static struct discover_client_ops cui_client_ops = {
947         .device_add = NULL,
948         .boot_option_add = cui_boot_option_add,
949         .device_remove = cui_device_remove,
950         .update_status = cui_update_status,
951         .update_sysinfo = cui_update_sysinfo,
952         .update_config = cui_update_config,
953 };
954
955 /* cui_server_wait_on_exit - On exit spin until the server is available.
956  *
957  * If the program exits before connecting to the server autoboot won't be
958  * cancelled even though there has been keyboard activity. This function is
959  * called by a child process which will spin until the server is connected and
960  * told to cancel autoboot.
961  *
962  * Processes exiting from this function will not carry out the cui_atexit()
963  * steps.
964  */
965 static void cui_server_wait_on_exit(struct cui *cui)
966 {
967         cui_detached = true;
968
969         while (!cui->client) {
970                 cui->client = discover_client_init(cui->waitset,
971                                 &cui_client_ops, cui);
972                 if (!cui->client)
973                         sleep(1);
974         }
975
976         talloc_steal(cui, cui->client);
977         discover_client_cancel_default(cui->client);
978 }
979
980 /* cui_server_wait - Connect to the discover server.
981  * @arg: Pointer to the cui instance.
982  *
983  * A timeout callback that attempts to connect to the discover server; on
984  * failure it registers itself with a one second timeout to try again.
985  * On success the cui->client struct will be set.
986  *
987  * Since this updates the status line when called it must not be called
988  * before the UI is ready.
989  */
990 static int cui_server_wait(void *arg)
991 {
992         struct cui *cui = cui_from_arg(arg);
993
994         if (cui->client) {
995                 pb_debug("We already have a server!\n");
996                 return 0;
997         }
998
999         /* We haven't yet connected to the server */
1000         pb_log("Trying to connect...\n");
1001         cui->client = discover_client_init(cui->waitset,
1002                         &cui_client_ops, cui);
1003
1004         if (!cui->client) {
1005                 waiter_register_timeout(cui->waitset, 1000, cui_server_wait,
1006                                         cui);
1007                 nc_scr_status_printf(cui->current,
1008                                      "Info: Waiting for device discovery");
1009         } else {
1010                 nc_scr_status_free(cui->current);
1011                 talloc_steal(cui, cui->client);
1012
1013                 if (cui->has_input) {
1014                         pb_log("Aborting default boot on pb-discover connect\n");
1015                         discover_client_cancel_default(cui->client);
1016                 }
1017         }
1018
1019         return 0;
1020 }
1021
1022 /**
1023  * cui_init - Setup the cui instance.
1024  * @platform_info: A value for the struct cui platform_info member.
1025  *
1026  * Returns a pointer to a struct cui on success, or NULL on error.
1027  *
1028  * Allocates the cui instance, sets up the client and stdin waiters, and
1029  * sets up the ncurses menu screen.
1030  */
1031
1032 struct cui *cui_init(void* platform_info,
1033         int (*js_map)(const struct js_event *e), int start_daemon, int timeout)
1034 {
1035         struct cui *cui;
1036         unsigned int i;
1037
1038         cui = talloc_zero(NULL, struct cui);
1039         if (!cui) {
1040                 pb_log("%s: alloc cui failed.\n", __func__);
1041                 fprintf(stderr, _("%s: alloc cui failed.\n"), __func__);
1042                 goto fail_alloc;
1043         }
1044
1045         cui->c_sig = pb_cui_sig;
1046         cui->platform_info = platform_info;
1047         cui->waitset = waitset_create(cui);
1048         cui->statuslog = statuslog_init(cui);
1049
1050         process_init(cui, cui->waitset, false);
1051
1052         /* Loop here for scripts that just started the server. */
1053
1054 retry_start:
1055         for (i = start_daemon ? 2 : 15; i && timeout; i--) {
1056                 cui->client = discover_client_init(cui->waitset,
1057                                 &cui_client_ops, cui);
1058                 if (cui->client || !i)
1059                         break;
1060                 pb_log("%s: waiting for server %d\n", __func__, i);
1061                 sleep(1);
1062         }
1063
1064         if (!cui->client && start_daemon) {
1065                 int result;
1066
1067                 start_daemon = 0;
1068
1069                 result = pb_start_daemon(cui);
1070
1071                 if (!result)
1072                         goto retry_start;
1073
1074                 pb_log("%s: discover_client_init failed.\n", __func__);
1075                 fprintf(stderr, _("%s: error: discover_client_init failed.\n"),
1076                         __func__);
1077                 fprintf(stderr, _("could not start pb-discover, the petitboot "
1078                         "daemon.\n"));
1079                 goto fail_client_init;
1080         }
1081
1082         if (!cui->client && !timeout) {
1083                 /* Have the first timeout fire immediately so we can check
1084                  * for the server as soon as the UI is ready */
1085                 waiter_register_timeout(cui->waitset, 0,
1086                                         cui_server_wait, cui);
1087         } else if (!cui->client) {
1088                 pb_log("%s: discover_client_init failed.\n", __func__);
1089                 fprintf(stderr, _("%s: error: discover_client_init failed.\n"),
1090                         __func__);
1091                 fprintf(stderr, _("check that pb-discover, "
1092                         "the petitboot daemon is running.\n"));
1093                 goto fail_client_init;
1094         }
1095
1096         atexit(cui_atexit);
1097         talloc_steal(cui, cui->client);
1098         cui_start();
1099
1100         cui->main = main_menu_init(cui);
1101         if (!cui->main)
1102                 goto fail_client_init;
1103
1104         waiter_register_io(cui->waitset, STDIN_FILENO, WAIT_IN,
1105                         cui_process_key, cui);
1106
1107         if (js_map) {
1108
1109                 cui->pjs = pjs_init(cui, js_map);
1110
1111                 if (cui->pjs)
1112                         waiter_register_io(cui->waitset, pjs_get_fd(cui->pjs),
1113                                         WAIT_IN, cui_process_js, cui);
1114         }
1115
1116         return cui;
1117
1118 fail_client_init:
1119         talloc_free(cui);
1120 fail_alloc:
1121         return NULL;
1122 }
1123
1124 /**
1125  * cui_run - The main cui program loop.
1126  * @cui: The cui instance.
1127  * @main: The menu to use as the main menu.
1128  *
1129  * Runs the cui engine.  Does not return until indicated to do so by some
1130  * user action, or an error occurs.  Frees the cui object on return.
1131  * Returns 0 on success (return to shell), -1 on error (should restart).
1132  */
1133
1134 int cui_run(struct cui *cui)
1135 {
1136         pid_t pid;
1137
1138         assert(main);
1139
1140         cui->current = &cui->main->scr;
1141         cui->default_item = 0;
1142
1143         nc_scr_post(cui->current);
1144
1145         while (1) {
1146                 int result = waiter_poll(cui->waitset);
1147
1148                 if (result < 0) {
1149                         pb_log("%s: poll: %s\n", __func__, strerror(errno));
1150                         break;
1151                 }
1152
1153                 if (cui->abort)
1154                         break;
1155
1156                 while (cui->resize) {
1157                         cui->resize = 0;
1158                         cui_handle_resize(cui);
1159                 }
1160         }
1161
1162         cui_atexit();
1163
1164         if (!cui->client) {
1165                 /* Fork a child to tell the server to cancel autoboot */
1166                 pid = fork();
1167                 if (!pid) {
1168                         cui_server_wait_on_exit(cui);
1169                         exit(EXIT_SUCCESS);
1170                 }
1171                 if (pid < 0)
1172                         pb_log("Failed to fork child on exit: %m\n");
1173         }
1174
1175         return cui->abort ? 0 : -1;
1176 }