/*
    ####             #    #     # #
    #   #            #    #       #          The FreeWare C library for 
    #   #  ##   ###  #  # #     # ###             RISC OS machines
    #   # #  # #     # #  #     # #  #   ___________________________________
    #   # ####  ###  ##   #     # #  #                                      
    #   # #        # # #  #     # #  #    Please refer to the accompanying
    ####   ### ####  #  # ##### # ###    documentation for conditions of use
    ________________________________________________________________________

    File:    Icon.InsertText.c
    Author:  Copyright  1995 Simon Truss
    Version: 1.01 (10 Nov 1995)
    Purpose: Insert a string into an icon's text buffer, at the caret if poss.
    History: 1.00 (13 August 1995)
             1.01 (10 Nov 1995) JS Changed to use Desk_DeskMem_Malloc and Desk_Wimp_E*
                                   veneers.
*/

#include "DeskLib:Error2.h"
#include "Desk.DeskMem.h"
#include "Desk.Wimp.h"
#include "Desk.WimpSWIs.h"
#include "Desk.Coord.h"
#include "Desk.Icon.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void Desk_Icon_InsertText(Desk_window_handle w, Desk_icon_handle i, const char *text)
{
  Desk_icon_block  istate;
  Desk_caret_block caret;
  int         len;

  if (text == NULL)
    return;

  Desk_Wimp_EGetIconState(w, i, &istate);
  if (istate.flags.value & (Desk_icon_TEXT | Desk_icon_INDIRECTED)) {
    len = strlen(istate.data.indirecttext.buffer) + strlen(text);
    if (len+1 < istate.data.indirecttext.bufflen) {
      Desk_Wimp_EGetCaretPosition( &caret );
      if ( caret.window == w && caret.icon == i ) {	/* insert into string */
        char *tmp;
      
        tmp = Desk_DeskMem_Malloc(istate.data.indirecttext.bufflen);
        strncpy(tmp, istate.data.indirecttext.buffer, caret.index);
        tmp[caret.index] = '\0';		/* strncpy does not add '\0' */
        strcat(tmp, text);
        strcat(tmp, istate.data.indirecttext.buffer+caret.index);
        strncpy(istate.data.indirecttext.buffer, tmp, len);
        istate.data.indirecttext.buffer[len] = '\0';
        free(tmp);
        caret.index+= strlen(text);
        Desk_Wimp_ESetCaretPosition( &caret );
        }
      else {					/* add to end of string */
        strcat(istate.data.indirecttext.buffer, text);
        }
      }
    Desk_Wimp_ESetIconState(w, i, 0, 0);
    }
}
