{Copyright or © or Copr. :

CNRS - Laboratoire Mouvement & Perception
franck.buloup@univmed.fr

This software is a computer program whose purpose is to highly simplify  
the use of ADwinPro realtime systems when you develop experimental
protocols  on life's sciences area.

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use, 
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info". 

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability. 

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or 
data to be ensured and,  more generally, to use and operate it in the 
same conditions as regards security. 

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.}
unit UActStimTraitObject;

interface

uses ExtCtrls, Graphics, Messages, Controls, Classes, SysUtils, Forms, StdCtrls,
     XMLClasses, Types, Contnrs, Windows, XMLDoc, XMLIntf, Dialogs,
     XMLClassesEchanges;

type
     ProcIHM = procedure(Application : TApplication);
     TES = class(TStaticText)
     private
       Selecter : TShape;
     public
       Genre : string;
       RefXMLEntree : IXMLENTREEType;
       RefXMLSortie : IXMLSORTIEType;
       constructor Construct(Aowner : TComponent;n:integer;pName,pGenre:string);
       procedure ChangeVisible;
       procedure ChangeES(Sender: TObject;Button: TMouseButton;
                          Shift: TShiftState; X, Y: Integer);
       procedure ChangePosition(Y:integer);
       procedure UpdateHorizontalPosition;
     end;
     TActStimTrait = class(TPanel)
     private
       DeleteImage : TImage;
       EditImage : TImage;
       AffecterImage : TImage;
       FonctionImage : TImage;
       TitreEdit : TEdit;
       NBE : integer;
       NBS : integer;
       EList : TObjectList;
       SList : TObjectList;
       //TEMPORAIRE
  {     AddEButton : TButton;
       AddSButton : TButton;
       SuppEButton : TButton;
       SuppSButton : TButton;
       ZEROESButton :TButton;  { }
       //TEMPORAIRE
			 procedure MoveALLE; 
			 procedure MAJHint;
     public
       Delete : Boolean;
       RefXMLFunction : IXMLFONCTIONType;
       InitialColor : TColor;
       SelectedColor : TColor;
       procedure MoveALLS;
       constructor Construct(AOwner : TComponent;n:integer;pXMLFunction:IXMLFONCTIONType);
       function GetNBE:integer;
       procedure SetNBE(Value:integer);
       function GetNBS:integer;
       procedure SetNBS(Value:integer);
			 procedure DeleteFonction(Sender: TObject);
			 procedure EditerFonction(Sender: TObject);
			 procedure MAJCodeADBASIC_PASCAL;
			 procedure HideTitreEdit;
     protected
       procedure WndProc(var Message : TMessage);override;
       procedure WhenDragOver(Sender,Source:TObject;X,Y:integer;State:TDragState;
                              var Accept : Boolean);
       procedure WhenDragDrop(Sender,Source:TObject;X,Y:integer);
			 function  AjouterEntree(pNOM:string):IXMLENTREEType;
       function  AjouterSortie(pNOM:string):IXMLSORTIEType;
       procedure OnTitreEditKeyPress(Sender: TObject; var Key: Char);
       procedure SuppE(Sender: TObject);
       procedure SuppS(Sender: TObject);
       procedure MyResize;
       procedure AffecterMouseDown(Sender: TObject;Button: TMouseButton;
                          Shift: TShiftState; X, Y: Integer);
       procedure EditerMouseDown(Sender: TObject;Button: TMouseButton;
													Shift: TShiftState; X, Y: Integer);
			 procedure MouseUp(Sender: TObject; Button: TMouseButton;
			 									  Shift: TShiftState; X, Y: Integer);reintroduce;
		 end;

implementation

uses UDocometre, UStimuli, UGLobal;

procedure TActStimTrait.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var Pt : TPoint;
begin
	if Button = mbRight then
	begin
	  Pt.X := X;
		Pt.Y := Y;
		Pt := Self.ClientToScreen(Point(X,Y));
    if RefXMLFunction <> nil
    then if RefXMLFunction.GENRE = 'A'
         then DocoForm.DescriptFrame.FonctionPopupMenu.Popup(Pt.X,Pt.Y);
    if RefXMLFunction <> nil
    then if RefXMLFunction.GENRE = 'T'
		     then DocoForm.DescriptFrame.FonctionPopupMenu.Popup(Pt.X,Pt.Y);
    if RefXMLFunction <> nil
    then if RefXMLFunction.GENRE = 'S'
		     then DocoForm.DescriptFrame.FonctionPopupMenu.Popup(Pt.X,Pt.Y);
	end;
end;

constructor TActStimTrait.Construct(AOwner : TComponent;n:integer;pXMLFunction:IXMLFONCTIONType);
var i : integer;
    NewE,NewS : TES;
begin
	inherited Create(AOwner);
	Self.OnMouseUp := MouseUp;
  Self.ParentBackground := false;
  RefXMLFunction := pXMLFunction;
  Parent := AOwner as TWinControl;
  Name := 'Fonction_'+inttostr(n);
  BorderStyle := bsNone;
  BevelInner := bvRaised;
  BevelOuter := bvLowered;
  Caption := RefXMLFunction.TITRE;
  ShowHint := true;
	//Hint := RefXMLFunction.FICHIER;
	MAJHint;

  Font.Style := [fsBold];

  Top := 100000;
  Align := alTop;
  Color := clInactiveCaptionText;
  SelectedColor := $DDEEFF;
  height := 80;
  DragMode := dmAutomatic;
  OnDragOver := WhenDragOver;
  OnDragDrop := WhenDragDrop;
  Delete := false;

  TitreEdit := TEdit.Create(Self);
  TitreEdit.Parent := Self;
  TitreEdit.Name := 'Titre_' + Name;
  TitreEdit.Text := RefXMLFunction.TITRE;
  TitreEdit.Visible := false;
  TitreEdit.AutoSize := true;
  TitreEdit.OnKeyPress := OnTitreEditKeyPress;
  TitreEdit.AutoSelect := true;

  DeleteImage := TImage.Create(Self);
  DeleteImage.Parent := Self;
  DeleteImage.Name := 'Delete_Image' + Name;
  DeleteImage.Cursor := crHandPoint;
  DeleteImage.ShowHint := true;
  DeleteImage.Hint := 'Supprimer';
  DeleteImage.Top := 0;
  DeleteImage.Width := 17;
  DeleteImage.Height := 17;
  DeleteImage.OnClick := DeleteFonction;
  DeleteImage.Picture.LoadFromFile(rep_racine + 'Icons\delete_edit.bmp');
  DeleteImage.Center := true;
  DeleteImage.Transparent := true;
  DeleteImage.Visible := false;
  
  EditImage := TImage.Create(Self);
  EditImage.Parent := Self;
  EditImage.Name := 'Edit_Image' + Name;
  EditImage.Cursor := crHandPoint;
  EditImage.ShowHint := true;
  EditImage.Hint := 'Editer';
  EditImage.Top := 0;
  EditImage.Width := 17;
  EditImage.Height := 17;
  EditImage.OnMouseDown := EditerMouseDown;
  EditImage.Picture.LoadFromFile(rep_racine + 'Icons\write_obj.bmp');
  EditImage.Center := true;
  EditImage.Transparent := true;
  EditImage.Visible := false;

  AffecterImage := TImage.Create(Self);
  AffecterImage.Parent := Self;
  AffecterImage.Name := 'Affect_Image' + Name;
  AffecterImage.Cursor := crHandPoint;
  AffecterImage.ShowHint := true;
  AffecterImage.Hint := 'Affecter';
  AffecterImage.Top := 0;
  AffecterImage.Width := 17;
  AffecterImage.Height := 17;
  AffecterImage.OnMouseDown := AffecterMouseDown;
  AffecterImage.Picture.LoadFromFile(rep_racine + 'Icons\pin.bmp');
  AffecterImage.Center := true;
  AffecterImage.Transparent := true;
  AffecterImage.Visible := false;


  if RefXMLFunction.GENRE = 'A' then
  begin
    FonctionImage := TImage.Create(Self);
    FonctionImage.Parent := Self;
    FonctionImage.Name := 'FonctionAction' + Name;
    FonctionImage.Hint := 'Action';
    FonctionImage.Width := 17;
    FonctionImage.Height := 17;
    FonctionImage.Top := Self.Height - FonctionImage.Height - 2;
    FonctionImage.Left := Self.Width div 2 - FonctionImage.Width div 2;
    FonctionImage.Picture.LoadFromFile(rep_racine + 'Icons\action.bmp');
    FonctionImage.Center := true;
    FonctionImage.Transparent := true;
    FonctionImage.Visible := true;
    FonctionImage.Anchors := [akBottom];
  end;

  if RefXMLFunction.GENRE = 'S' then
  begin
    FonctionImage := TImage.Create(Self);
    FonctionImage.Parent := Self;
    FonctionImage.Name := 'FonctionStimulus' + Name;
    FonctionImage.Hint := 'Stimulus';
    FonctionImage.Width := 17;
    FonctionImage.Height := 17;
    FonctionImage.Top := Self.Height - FonctionImage.Height - 2;
    FonctionImage.Left := Self.Width div 2 - FonctionImage.Width div 2;
    FonctionImage.Picture.LoadFromFile(rep_racine + 'Icons\stimulus.bmp');
    FonctionImage.Center := true;
    FonctionImage.Transparent := true;
    FonctionImage.Visible := true;
    FonctionImage.Anchors := [akBottom];
  end;

  if RefXMLFunction.GENRE = 'T' then
  begin
    FonctionImage := TImage.Create(Self);
    FonctionImage.Parent := Self;
    FonctionImage.Name := 'FonctionAction' + Name;
    FonctionImage.Hint := 'Traitement';
    FonctionImage.Width := 17;
    FonctionImage.Height := 17;
    FonctionImage.Top := Self.Height - FonctionImage.Height - 2;
    FonctionImage.Left := Self.Width div 2 - FonctionImage.Width div 2;
    FonctionImage.Picture.LoadFromFile(rep_racine + 'Icons\traitement.bmp');
    FonctionImage.Center := true;
    FonctionImage.Transparent := true;
    FonctionImage.Visible := true;
    FonctionImage.Anchors := [akBottom];
  end;


  EList := TObjectList.Create;
  SList := TObjectList.Create;

  //Ajout des Entrees sorties
  for i := 0 to RefXMLFunction.ENTREE.Count - 1 do
  begin
    NewE := TES.Construct(self,EList.Count + SList.Count,
                          RefXMLFunction.ENTREE.Items[i].NOM,'E');
    NewE.RefXMLEntree := RefXMLFunction.ENTREE.Items[i];
    EList.Add(NewE);
    if Elist.Count * NewE.Height > Height - 20
    then Height := height + 20;
    inc(NBE);
  end;
  MoveALLE;

  for i := 0 to RefXMLFunction.SORTIE.Count - 1 do
  begin
    NewS := TES.Construct(self,EList.Count + SList.Count,
                          RefXMLFunction.SORTIE.Items[i].NOM,'S');
    NewS.RefXMLSortie := RefXMLFunction.SORTIE.Items[i];
    SList.Add(NewS);
    if Slist.Count * NewS.Height > Height - 20
    then Height := height + 20;
    inc(NBS);
  end;
  MoveALLS;

  Visible := true;
end;

procedure TActStimTrait.MAJHint;
var i : integer;
		S : string;
begin
	Hint := RefXMLFunction.FICHIER;

	for i := 0 to  RefXMLFunction.ADBASIC.CODE.Count - 1 do
	begin
		S := RefXMLFunction.ADBASIC.CODE[i].TEXT;
		while (pos('%',S)<>0) do System.delete(S,pos('%',S),1);
		Hint := Hint + #13 + S;
	end;
end;

procedure TActStimTrait.MyResize;
var i : integer;
begin
//  (self.Parent as TWinControl).Visible := false;
  height := 80;
  //Parcours des Entrees sorties
  for i := 0 to RefXMLFunction.ENTREE.Count - 1 do
  begin
    if (i+1) * (EList.First as TES).Height > Height - 20
    then Height := height + 20;
  end;
  MoveALLE;

  for i := 0 to RefXMLFunction.SORTIE.Count - 1 do
  begin
    if (i+1) * (SList.First as TES).Height  > Height - 20
    then Height := height + 20;
  end;
  MoveALLS;
//  (self.Parent as TWinControl).Visible := true; 
end;


procedure TActStimTrait.HideTitreEdit;
var returnKey : char;
begin
	returnKey := Char(VK_RETURN);
	OnTitreEditKeyPress(Self,returnKey);
end;

procedure TActStimTrait.OnTitreEditKeyPress(Sender: TObject; var Key: Char);
begin
	if (key = Char(VK_RETURN)) and TitreEdit.Visible then
	begin
		RefXMLFunction.TITRE := TitreEdit.Text;
		Caption := RefXMLFunction.TITRE;
		TitreEdit.Visible := false;
		//ClipCursor(nil);
	end;
end;

procedure TActStimTrait.AffecterMouseDown(Sender: TObject;Button: TMouseButton;
                            Shift: TShiftState; X, Y: Integer);
var Pt : TPoint;
begin
  Pt.X := X;
  Pt.Y := Y;
  Pt := Self.AffecterImage.ClientToScreen(Point(X,Y));
  if RefXMLFunction.GENRE = 'A'
  then DocoForm.DescriptFrame.ActionPopupMenu.Popup(Pt.X,Pt.Y);
  if RefXMLFunction.GENRE = 'T'
  then DocoForm.DescriptFrame.TraitementPopupMenu.Popup(Pt.X,Pt.Y);
  if RefXMLFunction.GENRE = 'S'
  then DocoForm.DescriptFrame.StimulusPopupMenu.Popup(Pt.X,Pt.Y);
end;

procedure TActStimTrait.MAJCodeADBASIC_PASCAL;
var Num_Fonction,N : integer;
		ANode,ANodeParent : IXMLNode;
		InfoCanaux : TInfoCanaux;
begin

  ANode := DocoForm.DescriptFrame.CurentXMLBloc;
  Num_fonction := ANode.ChildNodes.IndexOf(RefXMLFUNCTION) + 1;
  ANodeParent := ANode.ParentNode;
  N := 10;
  repeat
    Num_fonction := Num_fonction + (ANodeParent.ChildNodes.IndexOf(ANode)+1)*N;
    ANode := ANodeParent;
    ANodeParent :=  ANodeParent.ParentNode;
    N := 10*N;
	until ANodeParent.NodeName = 'ROOT';


	ANode := ANodeParent;
	InfoCanaux := (ANode as IXMLROOTType).RendreListeInfoCanaux;
	RefXMLFUNCTION.MAJCodeADBasic_Pascal(Num_fonction, Rep_FichiersInf,InfoCanaux);
	InfoCanaux.Free;
	
	MAJHint;
end;

procedure TActStimTrait.EditerMouseDown(Sender: TObject;Button: TMouseButton;
                          Shift: TShiftState; X, Y: Integer);
var Hinst : THandle;
    FPointer : TFarProc;
    LancerIHM : ProcIHM;
    Nom_fichier : string;
    ListeCanaux : TInfoCanaux;
    i : integer;
    CANAL : IXMLEchangeCANALType;
    FONCTIONEchange : IXMLEchangeROOTType;
    CurentST : IXMLSTType;
    ANode : IXMLNode;
    ListeCanauxTrsfrt : TStringList;
    testCANINT : boolean;
begin
  if Self.RefXMLFunction.GENRE <> 'S' then
  begin
    //Recupérer ts les canaux présent ds les stim de la ST
    ANode := RefXMLFunction;
    repeat
      ANode := ANode.ParentNode;
    until ANode.NodeName = 'ST';
    CurentST := (ANode as IXMLSTType);
    ListeCanauxTrsfrt := TStringList.Create;
    CurentST.RendreListeCanauxTransfertPCKeithley(ListeCanauxTrsfrt);
    //Edition d'une Action ou d'un traitement
    //Exportation du XML de la fonction et Listant toutes les entrees/sorties
    Nom_fichier := Rep_Fonctions + 'Echange.xml';
    DocoForm.DescriptFrame.FichierEchangeXML.FileName := Nom_fichier;
    FONCTIONEchange := GetRootEchange(DocoForm.DescriptFrame.FichierEchangeXML);
    FONCTIONEchange.ChildNodes.Clear;
    FONCTIONEchange.ChildNodes.Add(RefXMLFunction.CloneNode(true));
    ListeCanaux := DocDOCOMETRE.RendreListeInfoCanaux;
    for i := 0 to ListeCanaux.Nom.Count - 1 do
    begin
      if RefXMLFunction.FICHIER <> 'Transfert' then
      begin
        CANAL := FONCTIONEchange.CANAL.Add;
        CANAL.NOM := ListeCanaux.Nom[i];

        if (ListeCanaux.floatORint[i] = 'float') and (ListeCanaux.inORoutORcanint[i] = 'in')
        then CANAL.SORTE := 'EAN';
        if (ListeCanaux.floatORint[i] = 'float') and (ListeCanaux.inORoutORcanint[i] = 'out')
        then CANAL.SORTE := 'SAN';
        if (ListeCanaux.floatORint[i] = 'int') and (ListeCanaux.inORoutORcanint[i] = 'in')
        then CANAL.SORTE := 'ENUM';
        if (ListeCanaux.floatORint[i] = 'int') and (ListeCanaux.inORoutORcanint[i] = 'out')
        then CANAL.SORTE := 'SNUM';

        testCANINT := (ListeCanaux.floatORint[i] = 'float') or (ListeCanaux.floatORint[i] = 'int');
        testCANINT := testCANINT and (ListeCanaux.inORoutORcanint[i] = 'canint');
        if testCANINT then
        begin
          if ListeCanaux.ISArray[i] = '1' then
          begin
            if pos('[',CANAL.NOM) <> 0
            then CANAL.SORTE := 'CANINT/ArrayElement[' + ListeCanaux.ArraySizeOrElementNum[i] + ']'
            else CANAL.SORTE := 'CANINT/ArraySize[' + ListeCanaux.ArraySizeOrElementNum[i] +  ']';
          end else CANAL.SORTE := 'CANINT';
        end;
        if ListeCanaux.ISPSerie[i] = '1'
        then CANAL.SORTE := 'PSERIE';

      end else
      begin
        if ListeCanauxTrsfrt.IndexOf(ListeCanaux.Nom[i]) = - 1 then
        begin
          CANAL := FONCTIONEchange.CANAL.Add;
          CANAL.NOM := ListeCanaux.Nom[i];

          if (ListeCanaux.floatORint[i] = 'float') and (ListeCanaux.inORoutORcanint[i] = 'in')
          then CANAL.SORTE := 'EAN';
          if (ListeCanaux.floatORint[i] = 'float') and (ListeCanaux.inORoutORcanint[i] = 'out')
          then CANAL.SORTE := 'SAN';
          if (ListeCanaux.floatORint[i] = 'float') and (ListeCanaux.inORoutORcanint[i] = 'canint')
          then CANAL.SORTE := 'CANINT';
          if (ListeCanaux.floatORint[i] = 'int') and (ListeCanaux.inORoutORcanint[i] = 'in')
          then CANAL.SORTE := 'ENUM';
          if (ListeCanaux.floatORint[i] = 'int') and (ListeCanaux.inORoutORcanint[i] = 'out')
          then CANAL.SORTE := 'SNUM';
          if (ListeCanaux.floatORint[i] = 'int') and (ListeCanaux.inORoutORcanint[i] = 'canint')
          then CANAL.SORTE := 'CANINT';
          if ListeCanaux.ISPSerie[i] = '1'
          then CANAL.SORTE := 'PSERIE';

        end;
      end;
    end;
    ListeCanauxTrsfrt.Free;
    ListeCanaux.Free;
    deletefile(PChar(Nom_fichier));
    DocoForm.DescriptFrame.FichierEchangeXML.SaveToFile();
    //Chargement DLL
    if Self.RefXMLFunction.GENRE = 'A'
    then Nom_fichier := Rep_Actions
    else Nom_fichier := Rep_Traitements;
    Nom_fichier := Nom_fichier + RefXMLFunction.FICHIER + '.dll';
    Hinst := LoadLibrary(PChar(Nom_fichier));
    if Hinst > 32 then
    begin
      FPointer := GetProcAddress(Hinst,'LancerIHM');
      if FPointer <> nil then
      begin
        LancerIHM := ProcIHM(FPointer);
        LancerIHM(Application.Handle);
        //Rechargement de la fonction
        DocoForm.DescriptFrame.FichierEchangeXML.FileName := Rep_Fonctions + 'Echange.xml';
        DocoForm.DescriptFrame.FichierEchangeXML.LoadFromFile(Rep_Fonctions + 'Echange.xml');
        FONCTIONEchange := GetRootEchange(DocoForm.DescriptFrame.FichierEchangeXML);

        //Recopie dans la fonction courante
        RefXMLFunction.DUREE := FONCTIONEchange.FONCTION.DUREE;
        RefXMLFunction.FICHIER := FONCTIONEchange.FONCTION.FICHIER;
        RefXMLFunction.GENRE := FONCTIONEchange.FONCTION.GENRE;

        SetNBE(0);
        SetNBS(0);

        for i := 0 to FONCTIONEchange.FONCTION.ENTREE.Count - 1
        do AjouterEntree(FONCTIONEchange.FONCTION.ENTREE.Items[i].NOM);
        MOVEALLE;

        for i := 0 to FONCTIONEchange.FONCTION.SORTIE.Count - 1
        do AjouterSortie(FONCTIONEchange.FONCTION.SORTIE.Items[i].NOM);
        MOVEALLS;

        RefXMLFunction.PARAM.Clear;
        for i := 0 to FONCTIONEchange.FONCTION.PARAM.Count - 1 do
        begin
          RefXMLFunction.PARAM.Add;
          RefXMLFunction.PARAM.Items[i].NOM := FONCTIONEchange.FONCTION.PARAM.Items[i].NOM;
        end;

        MyResize;
				MAJCodeADBASIC_PASCAL;
				MAJHint;
      end else showmessage('Impossible de charger la DLL "'+Nom_fichier+'"');
    end else showmessage('La DLL suivante est introuvable "'+Nom_fichier+'"');
    FreeLibrary(Hinst);
  end else
  begin
    //Edition d'un stimuli
    DocoForm.Hide;
    StimuliForm.XMLFunction := Self.RefXMLFunction.CloneNode(true) AS IXMLFONCTIONType;
    StimuliForm.ShowModal;
    DocoForm.Show;

    RefXMLFunction.FICHIER := StimuliForm.XMLFunction.FICHIER;
    Self.Hint := RefXMLFunction.FICHIER;

    SetNBS(0);

    for i := 0 to StimuliForm.XMLFunction.SORTIE.Count - 1
    do AjouterSortie(StimuliForm.XMLFunction.SORTIE[i].NOM);

    MyResize;
    MAJCodeADBASIC_PASCAL
  end;
end;

procedure TActStimTrait.WndProc(var Message : TMessage);
var Titre : String;
    Rgn : TRect;
		TheCanvas : TControlCanvas;
		returnKey:char;
begin
  returnKey := Char(VK_RETURN);
  case Message.Msg of
    CM_MOUSEENTER :
    begin
      if Self.RefXMLFunction.GENRE = 'S' then
      begin
        DeleteImage.Left := Width div 2 + 5;//+ 1;
        EditImage.Left := Width div 2 - DeleteImage.Width - 5;
        AffecterImage.Left := Width div 2 + EditImage.Width - 1;
        EditImage.Visible := true;
        DeleteImage.Visible := true;
        AffecterImage.Visible := false;
      end else
      begin
				//DeleteImage.Left := Width div 2 - EditImage.Width div 2 - DeleteImage.Width - 5; //+1
				DeleteImage.Left := Width div 2 + EditImage.Width div 2 + 5;
				EditImage.Left := Width div 2 - EditImage.Width div 2;
				//AffecterImage.Left := Width div 2 + EditImage.Width div 2 + 5;//- 1;
				AffecterImage.Left := Width div 2 - EditImage.Width div 2 - DeleteImage.Width - 5; //- 1;
				EditImage.Visible := true;
        DeleteImage.Visible := true;
        AffecterImage.Visible := true;
      end;

      InitialColor := Self.Color;
			Self.Color := SelectedColor;

			if DocoForm.DescriptFrame.CurentFct <> nil
			then if DocoForm.DescriptFrame.CurentFct <> Self
					 then DocoForm.DescriptFrame.CurentFct.HideTitreEdit;

			DocoForm.DescriptFrame.CurentFct := self;
      //BorderStyle := bssingle;
      //BevelInner := bvNone;
      //BevelOuter := bvNone;
      //MOVEALLE;
      //MOVEALLS;
			if TitreEdit.Visible then TitreEdit.SetFocus;
    end;
    CM_MOUSELEAVE :
    begin
			Self.Color := InitialColor;
      EditImage.Visible := false;
      DeleteImage.Visible := false;
      AffecterImage.Visible := false;
      //DocoForm.DescriptFrame.CurentFct := nil;
      BorderStyle := bsNone;
      BevelInner := bvRaised;
			BevelOuter := bvLowered;
      //MOVEALLE;
			//MOVEALLS;
		end;
    WM_LBUTTONDBLCLK :
    begin
      TheCanvas := TControlCanvas.Create;
      try
        TheCanvas.Control := TitreEdit;
        Titre := TitreEdit.Text;
        Rgn     := TitreEdit.ClientRect;
        TheCanvas.FillRect(Rgn);
        TitreEdit.Width := TheCanvas.TextWidth(Titre) + 50;
				if TitreEdit.width < 70 then TitreEdit.width := 70;
      finally
				TheCanvas.Free;
      end;
      TitreEdit.Top := Self.Height div 2 - TitreEdit.Height div 2;
			TitreEdit.Left := Self.Width div 2 - TitreEdit.Width div 2;
			TitreEdit.Visible := true;
		end;
		WM_LBUTTONDOWN :
		begin
		  if TitreEdit.Visible then OnTitreEditKeyPress(Self,returnKey);
		end;
  end;  
  inherited;
end;

procedure TActStimTrait.WhenDragOver(Sender,Source:TObject;X,Y:integer;State:TDragState;
                                     var Accept : Boolean);
begin
  if Source is TActStimTrait then Accept := true;
  {caption := Source.ClassName;
  if Self.DragMode = dmManual
  then caption := caption + ' manuel '
  else caption := caption + ' auto ';
  caption := caption + TimeToStr(Time);           }
end;

procedure TActStimTrait.WhenDragDrop(Sender,Source:TObject;X,Y:integer);
var IndexFonctionSource,IndexFonctionSender : integer;
    ListFunction : IXMLFonctionTypeList;
    NewFonction,SourceFonction : IXMLFonctionType;
begin
  if Source <> Sender then
  begin
    (Source as TActStimTrait).Top := (Sender as TActStimTrait).Top - 1;
    //Deplacement de la balise XML correspondante
    //recherche index de la fonction soeur (Sender)
    ListFunction := RefXMLFunction.Collection as IXMLFonctionTypeList;
    IndexFonctionSender := ListFunction.ChildNodes.IndexOf(RefXMLFunction);
    IndexFonctionSource := ListFunction.ChildNodes.IndexOf((Source as TActStimTrait).RefXMLFunction);
    SourceFonction := ListFunction.ChildNodes.Get(IndexFonctionSource) as IXMLFonctionType;
    NewFonction := SourceFonction.CloneNode(true) as IXMLFONCTIONType;;
    ListFunction.ChildNodes.Insert(IndexFonctionSender,NewFonction);
    //Recherche index de la fonction deplacée  a supprimer(Source)
    IndexFonctionSource := ListFunction.ChildNodes.IndexOf((Source as TActStimTrait).RefXMLFunction);
    ListFunction.ChildNodes.Delete(IndexFonctionSource);
    //Actualisation du pointeur
    (Source as TActStimTrait).RefXMLFunction := NewFonction;
  end;
end;

procedure TActStimTrait.DeleteFonction(Sender: TObject);
var i : integer;
    ListFunction : IXMLFonctionTypeList;
begin
  if RefXMLFunction.Genre = 'S' then
  begin
   if MessageDlg('Souhaitez-vous également supprimer le fichier stimulus ' + RefXMLFunction.FICHIER + '  ?',mtInformation,[mbYes,mbNo],0) = mrYes
   then SysUtils.DeleteFile(RefXMLFunction.FICHIER);//Supprimer le fichier dat aussi si souhaité
  end;
  ListFunction := RefXMLFunction.Collection as IXMLFonctionTypeList;
  for i := 0 to ListFunction.Count - 1 do
  begin
    if ListFunction.Items[i] = RefXMLFunction
    then break;
  end;
  ListFunction.Delete(i);
  EList.Free;
  SList.Free;
  Delete := true;
  Self.OnMouseUp := nil;
  DocoForm.DescriptFrame.DeleteFunctionTimer.Enabled := true;
end;

procedure TActStimTrait.EditerFonction(Sender: TObject);
begin
  Self.EditerMouseDown(Sender,mbLeft,[],0,0);
end;

procedure TActStimTrait.MoveALLE;
var i : integer;
begin
  for i := 0 to EList.Count - 1
  do (EList.Items[i] as TES).ChangeVisible;
  for i := 0 to EList.Count - 1
  do(EList.Items[i] as TES).ChangePosition((Height div (EList.Count + 1))*(i+1));
  for i := 0 to EList.Count - 1
  do (EList.Items[i] as TES).ChangeVisible;
end;

procedure TActStimTrait.MoveALLS;
var i : integer;
begin
  for i := 0 to SList.Count - 1
  do (SList.Items[i] as TES).ChangeVisible;
  for i := 0 to SList.Count - 1
  do(SList.Items[i] as TES).ChangePosition((Height div (SList.Count + 1))*(i+1));
  for i := 0 to SList.Count - 1
  do (SList.Items[i] as TES).ChangeVisible;
end;

function TActStimTrait.GetNBE:integer;
begin
  result := NBE;
end;

procedure TACtStimTrait.SetNBE(Value : integer);
var i : integer;
    NewE : TES;
    NewXMLE : IXMLENTREEType;
begin
  if Value <> NBE then
  begin
    if Value = 0 then
    begin
      RefXMLFunction.ENTREE.Clear;
      EList.Clear;
    end else
    begin
      if NBE < Value then
      begin
        for i := NBE to Value - 1 do
        begin
          NewXMLE := RefXMLFunction.ENTREE.Add;
          NewXMLE.NOM := 'IN';
          NewE := TES.Construct(self,EList.Count + SList.Count,'IN','E');
          NewE.RefXMLEntree := NewXMLE;
          EList.Add(NewE);
          if Elist.Count * NewE.Height > Height - 20
          then Height := height + 20;
        end;
        MoveALLE;
      end else
      begin
        repeat
          SuppE(Self);
        until RefXMLFunction.ENTREE.Count = Value
      end;
    end;
    NBE := Value;
  end;
end;

function TActStimTrait.GetNBS:integer;
begin
  result := NBS;
end;

procedure TActStimTrait.SetNBS(Value : integer);
var i : integer;
    NewS : TES;
    NEwXMLS : IXMLSORTIEType;
begin
  if Value <> NBS then
  begin
    if Value = 0 then
    begin
      RefXMLFunction.SORTIE.Clear;
      SList.Clear;
    end else
    begin
      if NBS < Value then
      begin
        for i := NBS to Value - 1 do
        begin
          NewXMLS := RefXMLFunction.SORTIE.Add;
          NewXMLS.NOM := 'OUT';
          NewS := TES.Construct(self,EList.Count + SList.Count,'OUT','S');
          NewS.RefXMLSortie := NewXMLS;
          SList.Add(NewS);
          if Slist.Count * NewS.Height > Height - 20
          then Height := height + 20;
        end;
        MoveALLS;
      end else
      begin
        repeat
          SuppS(Self);
        until RefXMLFunction.SORTIE.Count = Value
      end;
    end;
    NBS := Value;
  end;
end;

function TActStimTrait.AjouterEntree(pNOM:string):IXMLENTREEType;
var NewXMLE : IXMLENTREEType;
    NewE : TES;
begin

//  RefXMLFunction.ENTREE.ChildNodes.Insert(-1,);
  NewXMLE := RefXMLFunction.ENTREE.Add;
  NewXMLE.NOM := pNOM;
  NewE := TES.Construct(self,EList.Count + SList.Count,NewXMLE.NOM,'E');
  NewE.RefXMLEntree := NewXMLE;
  EList.Add(NewE);
  if Elist.Count * NewE.Height > Height - 20
  then Height := height + 20;
  inc(NBE);
  Result := NewXMLE;
end;

function TActStimTrait.AjouterSortie(pNOM:string):IXMLSORTIEType;
var NewXMLS : IXMLSORTIEType;
    NewS : TES;
begin
  NewXMLS := RefXMLFunction.SORTIE.Add;
  NewXMLS.NOM := pNOM;
  NewS := TES.Construct(self,EList.Count + SList.Count,NewXMLS.NOM,'S');
  NewS.RefXMLSortie := NewXMLS;
  SList.Add(NewS);
  if Slist.Count * NewS.Height > Height - 20
  then Height := height + 20;
  inc(NBS);
  Result := NewXMLS;
end;

                        {
procedure TActStimTrait.ADDE(Sender: TObject);
var n : integer;
begin
  n := NBE + 1;
  SetNBE(n);
end;
procedure TActStimTrait.ADDS(Sender: TObject);
var n : integer;
begin
  n := NBS + 1;
  SetNBS(n);
end;
                       }
procedure TActStimTrait.SuppE(Sender: TObject);
begin
  if EList.Count > 0 then
  begin
    RefXMLFunction.ENTREE.Delete(RefXMLFunction.ENTREE.Count - 1);
    EList.Delete(EList.Count-1);
  end;
end;

procedure TActStimTrait.SuppS(Sender: TObject);
begin
  if SList.Count > 0 then
  begin
    RefXMLFunction.SORTIE.Delete(RefXMLFunction.SORTIE.Count - 1);
    SList.Delete(SList.Count-1);
  end;
end;

constructor TES.Construct(AOwner : TComponent;n:integer;pName,pGenre:string);
begin
  inherited Create(AOwner);
  Parent := AOwner as TWinControl;

  Name := 'ES' + inttostr(n) + '_' + AOwner.Name;
  if pName = '' then pName := '    ';
  Caption := pName;
  Genre := pGenre;
  Transparent := false;

  BorderStyle := sbsSingle;
  if Genre = 'E'
  then Color := clSilver
  else Color := clInfoBk;
  Selecter := TShape.Create(Self);
  Selecter.Parent := AOwner as TWinControl;
  Selecter.Name := 'Selecter_' + Name;
  Selecter.Shape := stCircle;
  Selecter.Brush.Color := clWhite;
  Selecter.Height := Height;
  Selecter.Width := Selecter.Height;
  if (Parent as TActStimTrait).RefXMLFunction.GENRE <> 'S'
  then Selecter.Cursor := crHandPoint;
  Selecter.Top := Top;
  Selecter.Left := Left - Selecter.Width div 2;
  Selecter.Visible := true;
  if (Parent as TActStimTrait).RefXMLFunction.GENRE = 'S'
  then Selecter.OnMouseDown := nil
  else Selecter.OnMouseDown := ChangeES;



  visible := true;
end;

procedure TES.ChangeVisible;
begin
  visible  := not visible;
  Selecter.Visible := not Selecter.Visible;
end;

procedure TES.ChangeES(Sender: TObject;Button: TMouseButton;
                   Shift: TShiftState; X, Y: Integer);
var Pt : TPoint;
    CurentST : IXMLSTType;
    ANode : IXMLNode;
    ListeCanauxTrsfrt : TStringList;
    i : integer;
begin
  DocoForm.DescriptFrame.CurentES := self;
  Pt.X := X;
  Pt.Y := Y;
  Pt := ClientToScreen(Point(X,Y));

  for i := 0 to DocoForm.DescriptFrame.ESPopupMenu.Items.Count - 1
  do DocoForm.DescriptFrame.ESPopupMenu.Items[i].Enabled := true;

  if (Self.Parent as TActStimTrait).RefXMLFunction.FICHIER = 'Transfert' then
  begin
    //Recupérer ts les canaux présent ds les stim de la ST
    ANode := (Self.Parent as TActStimTrait).RefXMLFunction;
    repeat
      ANode := ANode.ParentNode;
    until ANode.NodeName = 'ST';
    CurentST := (ANode as IXMLSTType);
    ListeCanauxTrsfrt := TStringList.Create;
    CurentST.RendreListeCanauxTransfertPCKeithley(ListeCanauxTrsfrt);

		for i := 0 to DocoForm.DescriptFrame.ESPopupMenu.Items.Count - 1
    do if ListeCanauxTrsfrt.IndexOf(DocoForm.DescriptFrame.ESPopupMenu.Items[i].Caption) > -1
			 then DocoForm.DescriptFrame.ESPopupMenu.Items[i].Enabled := false
			 else if DocoForm.DescriptFrame.ESPopupMenu.Items[i].Caption = 'temps'
						then DocoForm.DescriptFrame.ESPopupMenu.Items[i].Enabled := false;

    ListeCanauxTrsfrt.Free;
  end;
  
  DocoForm.DescriptFrame.ESPopupMenu.Popup(Pt.X,Pt.Y);
end;

procedure TES.ChangePosition(Y:integer);
begin
  if Genre = 'E' then
  begin
    Top := Y - Height div 2;
    Left := Selecter.Width div 2;
    Selecter.Top := Top;
    Selecter.Left := 1;
  end else
  begin
    Top := Y - Height div 2;
    Left := Parent.ClientWidth - width - Selecter.Width div 2;
    Selecter.Top := Top;
    Selecter.Left := Parent.ClientWidth - Selecter.Width - 1;
  end;
end;

procedure TES.UpdateHorizontalPosition;
begin
  if Genre = 'S'
  then Left := Parent.ClientWidth - width - Selecter.Width div 2;
end;

end.
