#include <Common.h>
#include <System/sysAll.h>
#include <UI/UIAll.h>
#include "Misc.h"


void SetFieldText(Word fieldID, CharPtr text)
{
  VoidHand handle;
  VoidPtr ptr;
  FieldPtr field;
  FormPtr form;
    
  handle = MemHandleNew(StrLen(text) + 1);
  if (handle) {
    ptr = MemHandleLock(handle);
    StrCopy(ptr, text);
    MemHandleUnlock(handle);

    form = FrmGetActiveForm();
    field = FrmGetObjectPtr(form, FrmGetObjectIndex(form, fieldID));
    FldFreeMemory(field);
    FldSetTextHandle(field, (Handle)handle);
    FldDrawField(field);
  }
}


VoidPtr GetObjectPtr(Int objectID)
{
  FormPtr form = FrmGetActiveForm();

  return (FrmGetObjectPtr(form, FrmGetObjectIndex(form, objectID)));
}


void UpdateScrollBar(Int fieldID, Int scrollbarID)
{
  Word  CurrPos;
  Word  TextHeight;
  Word  FieldHeight;
  Short MaxVal;
  FieldPtr     field     = GetObjectPtr(fieldID);
  ScrollBarPtr scrollbar = GetObjectPtr(scrollbarID);

  FldGetScrollValues(field, &CurrPos, &TextHeight, &FieldHeight);

  if (TextHeight > FieldHeight) {
    MaxVal = TextHeight - FieldHeight + 1; /* last term is OVERLAP */
  } else if (CurrPos > 0) {
    MaxVal = CurrPos;
  } else {
    MaxVal = 0;
  }
  SclSetScrollBar(scrollbar, CurrPos, 0, MaxVal, FieldHeight - 1);
}


void ScrollLines(Int n, Int fieldID)
{
  FieldPtr field = GetObjectPtr(fieldID);

  if (n > 0) {
    FldScrollField(field,  n, down);
  } else if (n < 0) {
    FldScrollField(field, -n, up);
  }
}


void AssignPopupListPtr(PopupListPtrType* popuplistptr,
			       Word popupID, Word listID)
{
  popuplistptr->control = GetObjectPtr(popupID);
  popuplistptr->list    = GetObjectPtr(listID);
}


void SetPopupListSelection(PopupListPtrType* popuplistptr, Word selection)
{
  LstSetSelection(popuplistptr->list, selection);
  CtlSetLabel(popuplistptr->control,
	      LstGetSelectionText(popuplistptr->list, selection));
}


Word GetPopupListSelection(PopupListPtrType* popuplistptr)
{
  return LstGetSelection(popuplistptr->list);
}


void SkipLeadingSpace(CharPtr* p)
{
  while((**p == ' ') || (**p == '\t')) (*p)++;
}


void ChopTrailingSpace(CharPtr p)
{
  Int s = StrLen(p);
  CharPtr p0 = p;

  if (s == 0) return;
  p += s - 1;
  while ((p >= p0) && ((*p == ' ') || (*p == '\t'))) *(p--) = '\0';
}
