/* Copyright (C) 2000-2002 Damir Zucic */

/*=============================================================================

				button_press.c

Purpose:
	Handle ButtonPress events (mouse buttons).

Input:
	(1) Pointer to MolComplexS structure, with macromol. complexes.
	(2) Number of macromolecular complexes.
	(3) Pointer to RuntimeS structure.
	(4) Pointer to ConfigS structure, with configuration data.
	(5) Pointer to GUIS structure, with GUI data.
	(6) Pointer to NearestAtomS structure.
	(7) The number of pixels in the main window free area.
	(8) Pointer to refreshI.
	(9) Pointer to XButtonEvent structure.

Output:
	(1) If the  click_modeI is equal to zero and the click occured in
	    the main window, the interatomic distances and angles will be
	    calculated.  If the click_modeI is zero and the click occured
	    in the control window,  it will cause translation,  rotation,
	    slab change or fading change.  If the click_modeI is equal to
	    one, the click will choose the bond for editing.
	(2) Return value.

Return value:
	(1) Positive on success.
	(2) Zero if event is ignored.
	(3) Negative on failure.

========includes:============================================================*/

#include <stdio.h>

#include <string.h>
#include <math.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

int		ControlClick_ (MolComplexS *, int,
			       RuntimeS *, ConfigS *, GUIS *,
			       NearestAtomS *, size_t, unsigned int *,
			       XButtonEvent *);
int		PickBond_ (MolComplexS *, int,
			   RuntimeS *, ConfigS *, GUIS *,
			   NearestAtomS *, size_t, unsigned int *,
			   NearestAtomS *);

/*======handle ButtonPress events:===========================================*/

int ButtonPress_ (MolComplexS *mol_complexSP, int mol_complexesN,
		  RuntimeS *runtimeSP, ConfigS *configSP, GUIS *guiSP,
		  NearestAtomS *nearest_atomSP, size_t pixelsN,
		  unsigned int *refreshIP,
		  XButtonEvent *button_eventSP)
{
int			screen_x, screen_y, height;
size_t			pixelI;
NearestAtomS		*curr_pixelSP;
int			n;
AtomS			*atomSP;
RawAtomS		*raw_atomSP;
static int		atoms_pickedN;
char			stringA[STRINGSIZE];
static char		label0A[SHORTSTRINGSIZE];
static char		label1A[SHORTSTRINGSIZE];
static char		label2A[SHORTSTRINGSIZE];
static char		label3A[SHORTSTRINGSIZE];
static double		x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3;
double			delta_x, delta_y, delta_z, distance_squared, distance;
char			formatA[100];
double			dx10, dy10, dz10, dx32, dy32, dz32;
double			abs10, abs32, scalar_product;
double			cos_angle, angle;

/* Check the main window drawing mode index: */
if (guiSP->main_window_modeI != 0) return 0;

/* If the event came from child window, call the corresponding function: */
if (button_eventSP->subwindow != None)
	{
	/** Control window: **/
	if (button_eventSP->subwindow == guiSP->control_winS.ID)
		{
		return ControlClick_ (mol_complexSP, mol_complexesN,
				      runtimeSP, configSP, guiSP,
				      nearest_atomSP, pixelsN, refreshIP,
				      button_eventSP);
		}
	}

/*------If the event came from the main window:------------------------------*/

/* Prepare and check the pixel index: */
screen_x = button_eventSP->x;
screen_y = button_eventSP->y;
pixelI = guiSP->main_win_free_area_width * screen_y + screen_x;
if (pixelI >= pixelsN) return -1;

/* Pointer to the current pixel: */
curr_pixelSP = nearest_atomSP + pixelI;

/* Chech last_refreshI - data associated with this pixel may be obsolete: */
if (curr_pixelSP->last_refreshI != *refreshIP) return 0;

/* Check the edit mode index; if it is equal to one, the */
/* click should be used  to choose the bond for editing: */
if (runtimeSP->click_modeI == 1)
	{
	n = PickBond_ (mol_complexSP, mol_complexesN,
		       runtimeSP, configSP, guiSP,
		       nearest_atomSP, pixelsN, refreshIP,
		       curr_pixelSP);
	if (n > 0) return 1;
	else return -2;
	}

/* If this point is reached, the atom was picked successfully: */
atoms_pickedN++;
if (atoms_pickedN > 4) atoms_pickedN = 4;

/* Pointer to the current atom: */
atomSP = (mol_complexSP + curr_pixelSP->mol_complexI)->atomSP +
	  curr_pixelSP->atomI;
raw_atomSP = &atomSP->raw_atomS;

/* Store the coordinates of the current atom: */
x0 = raw_atomSP->x[0];
y0 = raw_atomSP->y;
z0 = raw_atomSP->z[0];

/* Prepare the label: */
sprintf (stringA, "%s %d %s",
	 raw_atomSP->pure_residue_nameA,
	 raw_atomSP->residue_sequenceI,
	 raw_atomSP->pure_atom_nameA);
strncpy (label0A, stringA, SHORTSTRINGSIZE - 1);
label0A[SHORTSTRINGSIZE - 1] = '\0';

/* If coordinates are not available for at least two atoms, */
/* copy coordinates,  copy label,  set one flag and return: */
if (atoms_pickedN < 2)
	{
	x1 = x0;
	y1 = y0;
	z1 = z0;
	strncpy (label1A, label0A, SHORTSTRINGSIZE - 1);
	label1A[SHORTSTRINGSIZE - 1] = '\0';
	return 2;
	}

/* Prepare text background color: */
XSetForeground (guiSP->displaySP, guiSP->theGCA[1],
		guiSP->main_winS.bg_colorID);

/* Prepare text color: */
XSetForeground (guiSP->displaySP, guiSP->theGCA[0],
		guiSP->main_winS.fg_colorID);

/* Refresh text background: */
height = guiSP->main_winS.font_height + 4;
screen_y = guiSP->main_win_free_area_height - height;
XFillRectangle (guiSP->displaySP, guiSP->main_winS.ID, guiSP->theGCA[1],
		0, screen_y, guiSP->main_win_free_area_width, height);

/* Calculate distance to the atom which was previously clicked: */
delta_x = x0 - x1;
delta_y = y0 - y1;
delta_z = z0 - z1;
distance_squared = delta_x * delta_x + delta_y * delta_y + delta_z * delta_z;
distance = sqrt (distance_squared);

/* Write distance to the output window. Note that */
/* this  string is  not drawn  to hidden  pixmap! */
strcpy (formatA, "dist. = %.2f A [%s]-->[%s]");
sprintf (stringA, formatA, distance, label1A, label0A);
screen_x = 2;
screen_y = guiSP->main_win_free_area_height -
	   guiSP->main_winS.fontSP->descent - 2;
XDrawString (guiSP->displaySP,
	     guiSP->main_winS.ID,
	     guiSP->theGCA[0],
	     screen_x, screen_y,
	     stringA, strlen (stringA));

/* Calculate the angle, if coordinates for four atoms are available: */
if (atoms_pickedN >= 4)
	{
	/** Prepare text coordinates: **/
	height = guiSP->main_winS.font_height + 4;
	screen_y = guiSP->main_win_free_area_height - 2 * height;

	/** Refresh text background: **/
	XFillRectangle (guiSP->displaySP, guiSP->main_winS.ID,
			guiSP->theGCA[1],
			0, screen_y, guiSP->main_win_free_area_width, height);

	/** Calculate absolute values and scalar product: **/
	dx10 = x0 - x1;
	dy10 = y0 - y1;
	dz10 = z0 - z1;
	abs10 = sqrt (dx10 * dx10 + dy10 * dy10 + dz10 * dz10);
	dx32 = x2 - x3;
	dy32 = y2 - y3;
	dz32 = z2 - z3;
	abs32 = sqrt (dx32 * dx32 + dy32 * dy32 + dz32 * dz32);
	scalar_product = dx10 * dx32 + dy10 * dy32 + dz10 * dz32;

	/** Calculate and write the angle, if atoms were properly chosen: **/
	if ((abs10 != 0.0) && (abs32 != 0.0))
		{
		/*** Calculate the angle. Remember that arc cosine ***/
		/*** is very sensitive  to floating point  errors: ***/
		cos_angle = scalar_product / (abs10 * abs32);
		if (cos_angle <= -1.0) angle = 180.0;
		else if (cos_angle >= 1.0) angle = 0.0;
		else angle = RAD_TO_DEG * acos (cos_angle);

		/*** Write angle to the output window. Note that ***/
		/*** this string is not drawn  to hidden pixmap! ***/
		strcpy (formatA,
			"angle = %.2f deg [%s]-->[%s], [%s]-->[%s]");
		sprintf (stringA, formatA,
			 angle, label3A, label2A, label1A, label0A);
		screen_x = 2;
		screen_y = guiSP->main_win_free_area_height - height -
			   guiSP->main_winS.fontSP->descent - 2;
		XDrawString (guiSP->displaySP,
			     guiSP->main_winS.ID,
			     guiSP->theGCA[0],
			     screen_x, screen_y,
			     stringA, strlen (stringA));
		}

	/** On failure,  inform user  that  at least  four **/
	/** atoms should be picked to calculate the angle: **/
	else
		{
		screen_x = 2;
		screen_y = guiSP->main_win_free_area_height - height -
			   guiSP->main_winS.fontSP->descent - 2;
		strcpy (stringA, "The same atom picked twice!");
		XDrawString (guiSP->displaySP,
			     guiSP->main_winS.ID,
			     guiSP->theGCA[0],
			     screen_x, screen_y,
			     stringA, strlen (stringA));
		}
	}

/* Copy the coordinates and labels: */
x3 = x2;
y3 = y2;
z3 = z2;
strncpy (label3A, label2A, SHORTSTRINGSIZE - 1);
label3A[SHORTSTRINGSIZE - 1] = '\0';
x2 = x1;
y2 = y1;
z2 = z1;
strncpy (label2A, label1A, SHORTSTRINGSIZE - 1);
label2A[SHORTSTRINGSIZE - 1] = '\0';
x1 = x0;
y1 = y0;
z1 = z0;
strncpy (label1A, label0A, SHORTSTRINGSIZE - 1);
label1A[SHORTSTRINGSIZE - 1] = '\0';

/* Return positive value: */
return 3;
}

/*===========================================================================*/


