#!/usr/cogent/bin/phgamma

/*
 * Another powerful feature of Gamma is dynamic arrays.  To make an array
 * in Gamma, the developer can use either the array() or make_array()
 * functions.  The array() function creates a pre_built array, while the
 * make_array() function creates an empty array of a given size.  If the
 * programmer attempts to write to an element beyond the end of the
 * array, the array will expand to accept the new element.  This
 * mechanism allows the programmer to approximate the size of the array,
 * and then increase its size as necessary simply by using it.
 * 
 * This file is best viewed with a tab width of 4.
 */

/*
 * Initailize Graphics Session with Photon.
 */
PtInit(nil);

/*
 * Load Photon Widget Support.
 */
require_lisp ("PhotonWidgets");
require_lisp ("PhabTemplate");

/*
 * Load the base window.
 */
PhabLoad ("wgt/example10.wgtw");

/*
 * Attach callbacks for adding text to the list.
 */
PtAttachCallback(Add_Date, Pt_CB_ACTIVATE, #add(date()));
PtAttachCallback(Add_Seconds, Pt_CB_ACTIVATE, #add(clock()));
PtAttachCallback(Add_Random_Number, Pt_CB_ACTIVATE, #add(random() * 1000));
PtAttachCallback(Add_Random_Text, Pt_CB_ACTIVATE,
				 #add(char(int(random() * (char_val("z") - char_val("A"))) +
						   char_val("A"))));

/*
 * Attach callbacks for Sort and Delete buttons.
 */

PtAttachCallback(Sort, Pt_CB_ACTIVATE, #sort_array());
PtAttachCallback(Delete, Pt_CB_ACTIVATE, #delete_item());

/*
 * Function to add to list.  We increase the dynamic array size simply
 * by setting an element beyond the end of the array.  We are always
 * dealing with strings, so we cast the incoming item to a string
 * before writing it to the PtList.
 */
function add (item_to_add)
{
	local myarray;

	myarray = ExampleList.items;
	myarray[length (myarray)] = string (item_to_add);
	ExampleList.items = myarray;
	Length.text_string = string (length (myarray));
}

/*
 * Sort function for array.  The 'strcmp' function returns an integer
 * less than, greater than, or equal to zero depending on the ASCII
 * ordering of its two string arguments.
 */
function sort_array ()
{
	local myarray;

	myarray = ExampleList.items;
	myarray = sort (myarray, strcmp);
	ExampleList.items = myarray;
}

/*
 * Function to delete item from array using the delete() function.
 * The item at the given index is removed from the array, and the
 * array "collapses" around the hole left by the departing item.  The
 * net effect is that the array is shortened by one.
 */
function delete_item ()
{
	local selected_item, myarray;

	selected_item = ExampleList.selection_indexes[0];
	if (selected_item)
	{
		myarray = ExampleList.items;

		delete(myarray, selected_item - 1);

		ExampleList.items = myarray;
		Length.text_string = string (length (myarray));
		if (selected_item >= length (myarray))
			selected_item = length (myarray);
		ExampleList.selection_indexes = array (selected_item);
	}
}

/*
 * Infinite event loop
 */
PtMainLoop();
