

/* Pocket Smalltalk
   Copyright (c) 1998,1999 by Andrew Brault
   http://www.pocketsmalltalk.com
   See LICENSE.TXT for license information */

/* Primitives for PalmOS */

#include "main.h"



Object p_set_list_choices(Object choices, Object controlID,
                          Object freeVisibleItems);



/* ListBox>>#primSetListChoices:controlID:freeVisibleItems: */
Object p_set_list_choices(Object choices, Object controlID,
                          Object freeVisibleItems)
{
  CharPtr ptr, * ptr_table;
  ListType * list;
  Object element;
  int16 len, n, count, size;
  FormPtr form_ptr;
  
  if((choices != nil) && (CLASS_OF(choices) != Array))
    { FAIL(1); }
  if(!IS_SMALLINT(controlID))
    { FAIL(1); }

  form_ptr = FrmGetActiveForm();
  list = (ListType *)
    FrmGetObjectPtr(form_ptr, 
		    FrmGetObjectIndex(form_ptr, 
				      FROM_SMALLINT(controlID)));
  if(choices == nil)  
    goto free_it;

  count = OBJECT_SIZE(choices);
  len = 0;
  for(n = 0; n < count; n++) {
    element = OBJECT_ACCESS(choices, n);
    if(CLASS_OF(element) != String)
      { FAIL(1); }
    len += OBJECT_BYTE_SIZE(element) + 1;
  }
  if(count > 0) {
    ptr_table = MemPtrNew(sizeof(CharPtr) * count);
    if(!ptr_table) { FAIL(2); }
    ptr = MemPtrNew(len);
    if(!ptr) { 
      MemPtrFree(ptr_table);
      FAIL(2); 
    }
  }
  else {
    ptr_table = NIL;
    ptr = NIL;
  }
  len = 0;
  for(n = 0; n < count; n++) {
    element = OBJECT_ACCESS(choices, n);
    size = OBJECT_BYTE_SIZE(element);
    MEMCOPY(ptr + len, OBJECT_BYTES(element), size);
    ptr_table[n] = ptr + len;
    len += size;
    ptr[len++] = '\0';
  }
free_it:;
  if(freeVisibleItems == true_obj) {
    if(list->itemsText) {
      MemPtrFree(list->itemsText[0]);
      MemPtrFree(list->itemsText);
    }
  }
  if(choices != nil) {
    LstSetListChoices(list, ptr_table, count);
    if(freeVisibleItems == true_obj)
      LstDrawList(list);
  }
  return receiver;
}





