/*
 * private/ui.c - Screen library independent user interface routines.
 */
/*
 * This file is part of Open Sound System
 *
 * Copyright (C) 4Front Technologies 1996-2007.
 *
 * This software is released under CDDL 1.0 source license for operating systems
 * that have their full source code available under the BSD or CDDL licenses.
 *
 * See the COPYING file included in the main directory of this source
 * distribution. Please contact sales@opensound.com for further info.
 */

/*
 * NOTE! This is not the development version of this file. Please download the
 * sources of the latest Open Sound System version from 
 * http://developer.opensound.com/sources if you plan to make any changes
 * to the software.
 */

#undef KERNEL
#undef _KERNEL

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#ifndef __FreeBSD__
#include <malloc.h>
#endif
#include <ctype.h>
#include "ui.h"

int ui_module = UI_TTY;

ui_selection *
ui_sel_create (char *title, int maxchoices)
{
  ui_selection *sel;
  ui_choice *ch;
  int l;

  if ((sel = (ui_selection *) malloc (sizeof (ui_selection))) == NULL)
    {
      ui_message ("malloc (selection) failed", 1);
      exit (-1);
    }

  if ((ch = (ui_choice *) malloc (maxchoices * sizeof (ui_choice))) == NULL)
    {
      ui_message ("malloc (choice) failed", 1);
      exit (-1);
    }

  l = strlen (title);
  if (l > 127)
    l = 127;

  strncpy (sel->title, title, l);
  sel->title[l] = 0;

  sel->priv = NULL;
  sel->nhdrs = 0;
  *sel->hdrdesc = 0;

  sel->choices = ch;
  sel->maxchoices = maxchoices;
  sel->nchoices = 0;

  sel->active = 0;
  sel->nbuttons = 0;

  return sel;
}

void
ui_sel_setactive (ui_selection * sel, int num)
{
  if (num == -1)
    sel->active = sel->nchoices - 1;
  else
    sel->active = num;
}

int
ui_sel_getactive (ui_selection * sel)
{
  return sel->active;
}

void
ui_sel_delete (ui_selection * sel)
{
  ui_sel_close_window (sel);
  free (sel->choices);
  free (sel);
}

void
ui_sel_delhdrs (ui_selection * sel)
{
  sel->nhdrs = 0;
  *sel->hdrdesc = 0;
}

void
ui_sel_addhdr (ui_selection * sel, char *hdr)
{
  if (sel->nhdrs >= UI_MAXHDR)
    {
      ui_message ("Internal error: Too many header lines", 1);
      ui_close ();
      exit (-1);
    }

  sel->hdrs[sel->nhdrs++] = hdr;
}

void
ui_sel_hdrdesc (ui_selection * sel, char *s)
{
  strcpy (sel->hdrdesc, s);
}

void
ui_sel_addchoice (ui_selection * sel, char *line, int id)
{
  ui_choice *ch;

  if (sel->nchoices >= sel->maxchoices)
    {
      ui_message ("Internal error: Too many choice lines", 1);
      ui_close ();
      abort ();
      exit (-1);
    }

  ch = &sel->choices[sel->nchoices];

  strncpy (ch->txt, line, 128);
  ch->txt[127] = 0;
  ch->id = id;

  sel->nchoices++;
}

void
ui_sel_addbutton (ui_selection * sel, char *label, int id)
{
  sel->tbuttons[sel->nbuttons] = label;
  sel->buttonidents[sel->nbuttons++] = id;
}

int
ui_sel_getid (ui_selection * sel)
{
  return sel->choices[sel->active].id;
}
