/* view.c - Graphical menu interface MVC view. */
/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2008  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <grub/types.h>
#include <grub/file.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/normal.h>
#include <grub/video.h>
#include <grub/gui_string_util.h>
#include <grub/gfxterm.h>
#include <grub/bitmap.h>
#include <grub/bitmap_scale.h>
#include <grub/term.h>
#include <grub/gfxwidgets.h>
#include <grub/time.h>
#include <grub/menu.h>
#include <grub/menu_viewer.h>
#include <grub/gfxmenu_view.h>
#include <grub/gui.h>
#include <grub/icon_manager.h>

/* The component ID identifying GUI components to be updated as the timeout
   status changes.  */
#define TIMEOUT_COMPONENT_ID "__timeout__"

static void init_terminal (grub_gfxmenu_view_t view);
static void destroy_terminal (void);
static grub_err_t set_graphics_mode (void);
static grub_err_t set_text_mode (void);

/* Create a new view object, loading the theme specified by THEME_PATH and
   associating MODEL with the view.  */
grub_gfxmenu_view_t
grub_gfxmenu_view_new (const char *theme_path, grub_gfxmenu_model_t model)
{
  grub_gfxmenu_view_t view;

  view = grub_malloc (sizeof (*view));
  if (! view)
    return 0;

  set_graphics_mode ();
  grub_video_set_active_render_target (GRUB_VIDEO_RENDER_TARGET_DISPLAY);
  grub_video_get_viewport ((unsigned *) &view->screen.x,
                           (unsigned *) &view->screen.y,
                           (unsigned *) &view->screen.width,
                           (unsigned *) &view->screen.height);

  /* Clear the screen; there may be garbage left over in video memory, and
     loading the menu style (particularly the background) can take a while. */
  grub_video_fill_rect (grub_video_map_rgb (0, 0, 0),
                        view->screen.x, view->screen.y,
                        view->screen.width, view->screen.height);
  grub_video_swap_buffers ();

  grub_font_t default_font;
  grub_gui_color_t default_fg_color;
  grub_gui_color_t default_bg_color;

  default_font = grub_font_get ("Helvetica 12");
  default_fg_color = grub_gui_color_rgb (0, 0, 0);
  default_bg_color = grub_gui_color_rgb (255, 255, 255);

  view->model = model;
  view->canvas = 0;

  view->title_font = default_font;
  view->message_font = default_font;
  view->terminal_font_name = grub_strdup ("Fixed 10");
  view->title_color = default_fg_color;
  view->message_color = default_bg_color;
  view->message_bg_color = default_fg_color;
  view->desktop_image = 0;
  view->desktop_color = default_bg_color;
  view->terminal_box = grub_gfxmenu_create_box (0, 0);
  view->title_text = grub_strdup ("GRUB Boot Menu");
  view->progress_message_text = 0;
  view->theme_path = 0;

  if (! grub_gfxmenu_view_load_theme (view, theme_path))
    {
      grub_gfxmenu_view_destroy (view);
      return 0;
    }

  init_terminal (view);

  return view;
}

/* Destroy the view object.  All used memory is freed.  */
void
grub_gfxmenu_view_destroy (grub_gfxmenu_view_t view)
{
  grub_video_bitmap_destroy (view->desktop_image);
  if (view->terminal_box)
    view->terminal_box->destroy (view->terminal_box);
  grub_free (view->terminal_font_name);
  grub_free (view->title_text);
  grub_free (view->progress_message_text);
  grub_free (view->theme_path);
  if (view->canvas)
    view->canvas->ops->component.destroy (view->canvas);
  grub_free (view);

  set_text_mode ();
  destroy_terminal ();
}

/* Sets MESSAGE as the progress message for the view.
   MESSAGE can be 0, in which case no message is displayed.  */
static void
set_progress_message (grub_gfxmenu_view_t view, const char *message)
{
  grub_free (view->progress_message_text);
  if (message)
    view->progress_message_text = grub_strdup (message);
  else
    view->progress_message_text = 0;
}

static void
draw_background (grub_gfxmenu_view_t view)
{
  if (view->desktop_image)
    {
      struct grub_video_bitmap *img = view->desktop_image;
      grub_video_blit_bitmap (img, GRUB_VIDEO_BLIT_REPLACE,
                              view->screen.x, view->screen.y, 0, 0,
                              grub_video_bitmap_get_width (img),
                              grub_video_bitmap_get_height (img));
    }
  else
    {
      grub_video_fill_rect (grub_gui_map_color (view->desktop_color),
                            view->screen.x, view->screen.y,
                            view->screen.width, view->screen.height);
    }
}

static void
draw_title (grub_gfxmenu_view_t view)
{
  if (! view->title_text)
    return;

  /* Center the title. */
  int title_width = grub_font_get_string_width (view->title_font,
                                                view->title_text);
  int x = (view->screen.width - title_width) / 2;
  int y = 40 + grub_font_get_ascent (view->title_font);
  grub_video_draw_string (view->title_text,
                          view->title_font,
                          grub_gui_map_color (view->title_color),
                          x, y);
}

struct progress_value_data
{
  const char *visible;
  const char *start;
  const char *end;
  const char *value;
  const char *text;
};

static void
update_timeout_visit (grub_gui_component_t component,
                      void *userdata)
{
  struct progress_value_data *pv;
  pv = (struct progress_value_data *) userdata;
  component->ops->set_property (component, "visible", pv->visible);
  component->ops->set_property (component, "start", pv->start);
  component->ops->set_property (component, "end", pv->end);
  component->ops->set_property (component, "value", pv->value);
  component->ops->set_property (component, "text", pv->text);
}

static void
update_timeout (grub_gfxmenu_view_t view)
{
  char startbuf[20];
  char valuebuf[20];
  char msgbuf[120];

  int timeout = grub_gfxmenu_model_get_timeout_ms (view->model);
  int remaining = grub_gfxmenu_model_get_timeout_remaining_ms (view->model);
  struct progress_value_data pv;

  pv.visible = timeout > 0 ? "true" : "false";
  grub_sprintf (startbuf, "%d", -timeout);
  pv.start = startbuf;
  pv.end = "0";
  grub_sprintf (valuebuf, "%d", remaining > 0 ? -remaining : 0);
  pv.value = valuebuf;

  int seconds_remaining_rounded_up = (remaining + 999) / 1000;
  grub_sprintf (msgbuf,
                "The highlighted entry will be booted automatically in %d s.",
                seconds_remaining_rounded_up);
  pv.text = msgbuf;

  grub_gui_find_by_id ((grub_gui_component_t) view->canvas,
                       TIMEOUT_COMPONENT_ID, update_timeout_visit, &pv);
}

static void
update_menu_visit (grub_gui_component_t component,
                   void *userdata)
{
  grub_gfxmenu_view_t view;
  view = userdata;
  if (component->ops->is_instance (component, "list"))
    {
      grub_gui_list_t list = (grub_gui_list_t) component;
      list->ops->set_view_info (list, view->theme_path, view->model);
    }
}

/* Update any boot menu components with the current menu model and
   theme path.  */
static void
update_menu_components (grub_gfxmenu_view_t view)
{
  grub_gui_iterate_recursively ((grub_gui_component_t) view->canvas,
                                update_menu_visit, view);
}

static void
draw_message (grub_gfxmenu_view_t view)
{
  char *text = view->progress_message_text;
  if (! text)
    return;

  grub_font_t font = view->message_font;
  grub_video_color_t color = grub_gui_map_color (view->message_color);

  /* Set the timeout bar's frame.  */
  grub_video_rect_t f;
  f.width = view->screen.width * 4 / 5;
  f.height = 50;
  f.x = view->screen.x + (view->screen.width - f.width) / 2;
  f.y = view->screen.y + view->screen.height - 90 - 20 - f.height;

  /* Border.  */
  grub_video_fill_rect (color,
                        f.x-1, f.y-1, f.width+2, f.height+2);
  /* Fill.  */
  grub_video_fill_rect (grub_gui_map_color (view->message_bg_color),
                        f.x, f.y, f.width, f.height);

  /* Center the text. */
  int text_width = grub_font_get_string_width (font, text);
  int x = f.x + (f.width - text_width) / 2;
  int y = (f.y + (f.height - grub_font_get_descent (font)) / 2
           + grub_font_get_ascent (font) / 2);
  grub_video_draw_string (text, font, color, x, y);
}


void
grub_gfxmenu_view_draw (grub_gfxmenu_view_t view)
{
  grub_video_set_active_render_target (GRUB_VIDEO_RENDER_TARGET_DISPLAY);
  update_timeout (view);
  update_menu_components (view);

  draw_background (view);
  if (view->canvas)
    view->canvas->ops->component.paint (view->canvas);
  draw_title (view);
  draw_message (view);
}

static grub_err_t
set_graphics_mode (void)
{
  const char *doublebuf_str = grub_env_get ("doublebuffering");
  int doublebuf_flags =
    (doublebuf_str && doublebuf_str[0] == 'n')
    ? 0
    : GRUB_VIDEO_MODE_TYPE_DOUBLE_BUFFERED;

  const char *modestr = grub_env_get ("gfxmode");
  if (grub_video_setup_preferred_mode (modestr, doublebuf_flags, 640, 480)
      != GRUB_ERR_NONE)
    return grub_errno;

  return GRUB_ERR_NONE;
}

static grub_err_t
set_text_mode (void)
{
  return grub_video_restore ();
}

static int term_target_width;
static int term_target_height;
static struct grub_video_render_target *term_target;
static int term_initialized;
static grub_term_t term_original;
static grub_gfxmenu_view_t term_view;

static void
repaint_terminal (int x __attribute ((unused)),
                  int y __attribute ((unused)),
                  int width __attribute ((unused)),
                  int height __attribute ((unused)))
{
  if (! term_view)
    return;

  grub_video_set_active_render_target (GRUB_VIDEO_RENDER_TARGET_DISPLAY);
  grub_gfxmenu_view_draw (term_view);
  grub_video_set_active_render_target (GRUB_VIDEO_RENDER_TARGET_DISPLAY);

  int termx = term_view->screen.x
    + term_view->screen.width * (10 - 7) / 10 / 2;
  int termy = term_view->screen.y
    + term_view->screen.height * (10 - 7) / 10 / 2;

  grub_gfxmenu_box_t term_box = term_view->terminal_box;
  if (term_box)
    {
      term_box->set_content_size (term_box,
                                  term_target_width, term_target_height);

      term_box->draw (term_box,
                      termx - term_box->get_left_pad (term_box),
                      termy - term_box->get_top_pad (term_box));
    }

  grub_video_blit_render_target (term_target, GRUB_VIDEO_BLIT_REPLACE,
                                 termx, termy,
                                 0, 0, term_target_width, term_target_height);
  grub_video_swap_buffers ();
}

static void
init_terminal (grub_gfxmenu_view_t view)
{
  term_original = grub_term_get_current ();

  term_target_width = view->screen.width * 7 / 10;
  term_target_height = view->screen.height * 7 / 10;

  grub_video_create_render_target (&term_target,
                                   term_target_width,
                                   term_target_height,
                                   GRUB_VIDEO_MODE_TYPE_RGB
                                   | GRUB_VIDEO_MODE_TYPE_ALPHA);
  if (grub_errno != GRUB_ERR_NONE)
    return;

  /* Note: currently there is no API for changing the gfxterm font
     on the fly, so whatever font the initially loaded theme specifies
     will be permanent.  */
  grub_gfxterm_init_window (term_target, 0, 0,
                            term_target_width, term_target_height,
                            view->terminal_font_name, 3);
  if (grub_errno != GRUB_ERR_NONE)
    return;
  term_initialized = 1;

  /* XXX: store static pointer to the 'view' object so the repaint callback can access it.  */
  term_view = view;
  grub_gfxterm_set_repaint_callback (repaint_terminal);
  grub_term_set_current (grub_gfxterm_get_term ());
}

static void destroy_terminal (void)
{
  term_view = 0;
  if (term_initialized)
    grub_gfxterm_destroy_window ();
  grub_gfxterm_set_repaint_callback (0);
  if (term_target)
    grub_video_delete_render_target (term_target);
  if (term_original)
    grub_term_set_current (term_original);
}


static void
notify_booting (void *userdata, grub_menu_entry_t entry)
{
  grub_gfxmenu_view_t view = (grub_gfxmenu_view_t) userdata;

  char *s = grub_malloc (100 + grub_strlen (entry->title));
  if (!s)
    return;

  grub_sprintf (s, "Booting '%s'", entry->title);
  set_progress_message (view, s);
  grub_free (s);
  grub_gfxmenu_view_draw (view);
  grub_video_swap_buffers ();
}

static void
notify_fallback (void *userdata, grub_menu_entry_t entry)
{
  grub_gfxmenu_view_t view = (grub_gfxmenu_view_t) userdata;

  char *s = grub_malloc (100 + grub_strlen (entry->title));
  if (!s)
    return;

  grub_sprintf (s, "Falling back to '%s'", entry->title);
  set_progress_message (view, s);
  grub_free (s);
  grub_gfxmenu_view_draw (view);
  grub_video_swap_buffers ();
}

static void
notify_execution_failure (void *userdata __attribute__ ((unused)))
{
}


static struct grub_menu_execute_callback execute_callback =
{
  .notify_booting = notify_booting,
  .notify_fallback = notify_fallback,
  .notify_failure = notify_execution_failure
};

int
grub_gfxmenu_view_execute_with_fallback (grub_gfxmenu_view_t view,
                                         grub_menu_entry_t entry)
{
  grub_menu_execute_with_fallback (grub_gfxmenu_model_get_menu (view->model),
                                   entry, &execute_callback, (void *) view);

  if (set_graphics_mode () != GRUB_ERR_NONE)
    return 0;  /* Failure.  */

  /* If we returned, there was a failure.  */
  set_progress_message (view,
                        "Unable to automatically boot.  "
                        "Press SPACE to continue.");
  grub_gfxmenu_view_draw (view);
  grub_video_swap_buffers ();
  while (GRUB_TERM_ASCII_CHAR(grub_getkey ()) != ' ')
    {
      /* Wait for SPACE to be pressed.  */
    }

  set_progress_message (view, 0);   /* Clear the message.  */

  return 1;   /* Ok.  */
}

int
grub_gfxmenu_view_execute_entry (grub_gfxmenu_view_t view,
                                 grub_menu_entry_t entry)
{
  /* Currently we switch back to text mode by restoring
     the original terminal before executing the menu entry.
     It is hard to make it work when executing a menu entry
     that switches video modes -- it using gfxterm in a
     window, the repaint callback seems to crash GRUB. */
  /* TODO: Determine if this works when 'gfxterm' was set as
     the current terminal before invoking the gfxmenu. */
  destroy_terminal ();

  grub_menu_execute_entry (entry);
  if (grub_errno != GRUB_ERR_NONE)
    grub_wait_after_message ();

  if (set_graphics_mode () != GRUB_ERR_NONE)
    return 0;  /* Failure.  */

  init_terminal (view);
  return 1;   /* Ok.  */
}

void
grub_gfxmenu_view_run_terminal (grub_gfxmenu_view_t view __attribute__((unused)))
{
  grub_cmdline_run (1);
}
