view m-toolbox/m/gui/gltpda/pan1main.m @ 52:daf4eab1a51e database-connection-manager tip

Fix. Default password should be [] not an empty string
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Wed, 07 Dec 2011 17:29:47 +0100
parents f0afece42f48
children
line wrap: on
line source

function pan1main(varargin)
% This is the function for the main panel of the GUI LTPDA, the package of
% data analysis functions developed for the LISA Pathfinder Mission / LISA
% Technology Package.
%
%  $Id: pan1main.m,v 1.57 2010/08/02 18:30:20 ingo Exp $

global LTPDAinvar LTPDAoutvar currentsystem gl loop selBlocks

% Initialize the list of AOs:
InputObjList=''; % OutputObjList='';
UpdateListbox();
set(gcf,'NextPlot','new');

selBlocks = [];
scaleX = getappdata(0, 'ltpda_gui_scalefactor');
guiFontSize = round(8*scaleX);

alltimers = timerfindall;
stop(alltimers(2));
set(alltimers(2),'TimerFcn',@ContinuousCheck,'Period',.5);
start(alltimers(2));
set(gcf,'NextPlot','new')
set(gcf,'CloseRequestFcn',{@AskConfirm,'close'})

%%

currPanel   = varargin{1};
if nargin>1, runSim = varargin{2}; else runSim = 0; end
panelDimens = get(currPanel, 'Position');
backColor   = get(currPanel, 'BackgroundColor');

  uicontrol('Parent',currPanel,'TooltipString','login/logout','Units','pixels','HorizontalAlignment','center','Position',[60 panelDimens(4)*0.925 40 20],'String','log','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@LogoutCallback,'Style','pushbutton');
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'TooltipString','username','Units','pixels','HorizontalAlignment','left','Position',[110 panelDimens(4)*0.93 150 15],'String',getappdata(0,'ltpda_repo_user'),'FontSize',guiFontSize+1,'Style','text');
  currsystem = bdroot;
    if isempty(currsystem) || isempty(find_system(currsystem,'FindAll','on','Type','Annotation','Tag','ltpda model')), currsystem = 'None'; end
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','pixels','Position',[230 panelDimens(4)*0.93 300 15],'String',['Current system: ',currsystem],'FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Tag','currsystem','Style','text');

  
    AnalysPanPos   = [.005 .8 .990 .111];
  hanalysisPanel = uipanel('Parent',currPanel,'Title',' Analyses Control ','BackgroundColor',backColor,'FontSize',guiFontSize-1,'Units','normalized','Position',AnalysPanPos);
    nbuttons    = 3;
    buttonWidth = (AnalysPanPos(3)-.01*(nbuttons))/nbuttons;
    buttonPos   = [AnalysPanPos(1) .2 buttonWidth .6];
  uicontrol('Parent',hanalysisPanel,'Units','pixels','Units','normalized','Position',buttonPos,'String','New model','TooltipString','Create a new LTPDA Simulink model','HorizontalAlignment','center','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hNewButtonCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  uicontrol('Parent',hanalysisPanel,'Units','pixels','Units','normalized','Position',buttonPos,'String','Open model','TooltipString','Open an existing LTPDA Simulink model','HorizontalAlignment','center','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hOpenCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  uicontrol('Parent',hanalysisPanel,'Units','pixels','Units','normalized','Position',buttonPos,'String','Save model','TooltipString','Save the currently selected LTPDA Simulink model','HorizontalAlignment','center','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hSaveCallback,'Style','pushbutton');
    clear AnalysPanPos nbuttons buttonWidth buttonPos


    DataPanPos   = [.005 .1633 .990 .615];
  hDataPanel    =  uipanel('Parent',currPanel,'Title',' Data Control ','BackgroundColor',backColor,'FontSize',guiFontSize-1,'Units','normalized','Position',DataPanPos);
    nbuttons    = 3;
    buttonWidth = (DataPanPos(3)-.01*(nbuttons))/nbuttons;
    buttonPos   = [DataPanPos(1) .9 buttonWidth .08];
  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Clear all input','TooltipString','Clear from memory the entire list of input objects','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',{@AskConfirm,'clear'},'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
% uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Load','TooltipString','Load data from file','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hLoadDataButtonCallback,'Style','pushbutton');
%   buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
% uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Remove','TooltipString','Clear the selected object from memory','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hRemoveButtonCallback,'Style','pushbutton');
%   buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
% uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Create','FontSize',guiFontSize,'Visible','on','Enable','off','UserData',InputObjList,'Callback',@hExploreButtonCallback,'Style','pushbutton');
%   buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
% uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Edit','FontSize',guiFontSize,'Visible','on','Enable','off','UserData',InputObjList,'Callback',@hExploreButtonCallback,'Style','pushbutton');
%   buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Report','TooltipString','Report','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hReportButtonCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  hExploreButton =  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Explore','TooltipString','Explore the selected objects with the LTPDA Explorer','FontSize',guiFontSize,'Visible','on','Enable','on','UserData',InputObjList,'Callback',@hExploreButtonCallback,'Style','pushbutton');
    clear nbuttons buttonWidth buttonPos
    nbuttons    = 3;
    buttonWidth = (DataPanPos(3)-.01*(nbuttons))/nbuttons;
    buttonPos   = [DataPanPos(1) .8 buttonWidth .08];
  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Export to workspace','TooltipString','Export the selected objects from LTPDA to MATLAB workspace','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@hExportButtonCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Save workspace','TooltipString','Save the LTPDA Workspace as .MAT file','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@SaveWorkspaceCallback,'Style','pushbutton');
    buttonPos(1) = buttonPos(1)+buttonWidth+.0125;
  uicontrol('Parent',hDataPanel,'Units','normalized','HorizontalAlignment','center','Position',buttonPos,'String','Load workspace','TooltipString','Load a workspace from a .MAT file','FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@LoadWorkspaceCallback,'Style','pushbutton');
    clear nbuttons buttonWidth buttonPos


    nlists    = 2;
    listWidth = (DataPanPos(3)-.01*(nlists))/nlists;
    listPos   = [.01 .03 listWidth .7];
  InputObjList   = uicontrol('Parent',hDataPanel,'BackgroundColor',[0.95,0.95,0.95],'HorizontalAlignment','center','Units','normalized','Position',listPos,'String',listInput,'Value',1,'Max',10,'Min',1,'FontSize',guiFontSize,'FontWeight','normal','Visible','on','Enable','on','Callback',@hListObjsCallback,'Tag','InputObjList','Style','listbox');
    set(hExploreButton,'UserData',InputObjList);
    listPos(1) = listPos(1)+listWidth+.01;
  % Info panel:
  uicontrol('Parent',hDataPanel,'BackgroundColor',[0.94,0.94,1],'Style','listbox','HorizontalAlignment', 'left','Fontsize', guiFontSize,'Units','pixels','Units','normalized','Position',listPos,'Tag','infoPanel');
    hListObjsCallback(InputObjList,1);
    clear DataPanPos nlists listWidth listPos
    
    
  hExecutionPanel =  uipanel('Parent',currPanel,'Title',' Execution control ','BackgroundColor',[1,1,1],'FontSize',guiFontSize-1,'Units','normalized','Position',[.0125 .0222 .975 .121]);
    if isempty(getappdata(0,'maintainresults')), setappdata(0,'maintainresults',0); end
  uicontrol('Parent',hExecutionPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','normalized','Position',[.03 .3 .3 .5],'Value',getappdata(0,'maintainresults'),'String',' Maintain all results','FontSize',guiFontSize+1,'TooltipString','Enable this if you want to maintain the results from all blocks at the end of the analysis calculation','ForeGroundColor','black','Visible','on','Enable','off','Callback','setappdata(0,''maintainresults'',get(gco,''Value''))','Style','checkbox','Tag','enableCheckbox');
  GUIprefs = getappdata(0, 'GUIpreferences');
    if ~isfield(GUIprefs,'CAD'), GUIprefs.CAD = 0; setappdata(0, 'GUIpreferences',GUIprefs); end
  uicontrol('Parent',hExecutionPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','normalized','Position',[.3 .3 .3 .5],'Value',GUIprefs.CAD,'String',' Quick design mode','FontSize',guiFontSize+1,'TooltipString','To enable quick model drawing: each copied block will be replaced by an hollow block and automatically connected','ForeGroundColor','black','Visible','on','Enable','off','Callback','GUIprefs.Copied=0; GUIprefs.CAD=get(gco,''Value'');setappdata(0, ''GUIpreferences'',GUIprefs); if get(gco,''Value''), ltpdagui(''Redraw'',2); end;','Style','checkbox','Tag','enableCheckbox');
    if ~isfield(GUIprefs,'Detach'), GUIprefs.Detach = 0; setappdata(0, 'GUIpreferences',GUIprefs); end
  uicontrol('Parent',hExecutionPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','normalized','Position',[.6 .3 .3 .5],'Value',GUIprefs.Detach,'String',' Detach panel','FontSize',guiFontSize+1,'TooltipString','','ForeGroundColor','black','Visible','on','Enable','off','Callback','GUIprefs.Detach=get(gco,''Value'');setappdata(0, ''GUIpreferences'',GUIprefs);try close(findobj(''Tag'',''parampanelFigure'')); catch, end;','Style','checkbox','Tag','enableCheckbox');
  
if runSim == 1, StartExec(); end

%%

% ========================================================================
% ========================================================================
% ============================== FUNCTIONS ===============================
% ========================================================================
% ========================================================================

%%
    %----------------------------------------------------------------------
    function ContinuousCheck(varargin)   
        % This is the function to execute a continuous timer check
        
       % Keep alive the first timer:
         alltimers = timerfindall;
         if strcmp(get(alltimers(1),'Running'),'off'), start(alltimers(1)); end
         
         currsys = bdroot;
         if ~isempty(currsys) && ~isempty(find_system(currsys,'FindAll','on','Type','Annotation','Tag','ltpda model'))
             set(findobj('Tag', 'currsystem'), 'String', ['Current system: ',currsys])
             set(findobj('Tag', 'enableCheckbox'), 'enable', 'on')
         else
             set(findobj('Tag', 'currsystem'), 'String', 'Current system: None')
             set(findobj('Tag', 'enableCheckbox'), 'enable', 'off')
         end

         nestBlock = find_system(bdroot,'BlockType','SubSystem','Tag','nestedloops');
         if ~isempty(nestBlock), set(findobj('String',' Enable nested loops'),'Value',1); else set(findobj('String',' Enable nested loops'),'Value',0);  end
         
    end
    %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function LogoutCallback(varargin)
    % Callback function: run when the user click the "Logout" button
         setappdata(0,'ltpda_repo_pass','');
         userID = getappdata(0,'ltpda_repo_user');
         if isempty(userID), userID = ''; end
         [userID passwd] = utils.mysql.logindlg(userID,'');
         setappdata(0,'ltpda_repo_user',userID)
         setappdata(0,'ltpda_repo_pass',passwd)
         ltpdagui('Redraw',1);
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function AskConfirm(varargin)
    % Whenever the user click the Reset Parameters button
    
         if strcmp(varargin{3},'close'), set(gcf,'Visible','off'); end
         
       % Ask for confirmation:
         screenSize = get(0,'ScreenSize');
         backColor   = [1 1 1];
         position   = [(screenSize(3)-250)/2,(screenSize(4)-160)/2,250,160];
         confirmFig = figure('Position',position,'Name','Please confirm','Tag','ConfirmReset','Resize','off','NumberTitle','off','Toolbar','none','Menubar','none');
       % Text
         uicontrol('Parent',confirmFig,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[0 position(4)-40 position(3) 20],'String','Are you sure?','FontName','Times New Roman','FontSize',13,'FontWeight','normal','Visible','on','Style','text');
       % Button Yes
         dimension = position;
         logosize = [77 95];
         dimension = [50 , dimension(4)-logosize(2)-50 , logosize];
         yesbut = axes('Parent',confirmFig,'Units','pixels','Position',dimension,'Tag','Yes');
         image(imread('buttonyes2.jpg'),'Parent',yesbut,'ButtonDownFcn','set(findobj(''Tag'',''ConfirmReset''),''UserData'',0); uiresume;','Tag','YesButton');
         axis(yesbut,'off');
       % Button No
         dimension = position;
         logosize = [77 95];
         dimension = [127 , dimension(4)-logosize(2)-50 , logosize];
         nobut = axes('Parent',confirmFig,'Units','pixels','Position',dimension,'Tag','No');
         image(imread('buttonno2.jpg'),'Parent',nobut,'ButtonDownFcn','set(findobj(''Tag'',''ConfirmReset''),''UserData'',1); uiresume;','Tag','NoButton');
         axis(nobut,'off');

         uiwait;
         
         if get(confirmFig,'UserData'), delete(confirmFig); set(findobj('Tag','LTPDAGUI'),'Visible','on'); return; end
         
         if strcmp(varargin{3},'close')
            delete(confirmFig);
            disp('Closing LTPDA GUI...');
            delete(timerfindall);
            clear global LTPDAinvar LTPDAoutvar;
            setappdata(0,'ltpda_repo_user',''); setappdata(0,'ltpda_repo_pass','');
            closereq
         elseif strcmp(varargin{3},'clear')
            delete(confirmFig);
            LTPDAinvar={};
            set(InputObjList,'Value',1)
            set(findobj('Tag', 'infoPanel'), 'String', '')
            set_param(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'),'UserData','');
            UpdateListbox();
         end
         
    end
    %----------------------------------------------------------------------
    
%%
%     %----------------------------------------------------------------------
%     function hLoadDataButtonCallback(varargin)   
%     % Callback function: run when the user click the "Add data" button
%     
%          filenames = uipickfiles('REFilter','.txt');
%          if ~isempty(filenames) && ~isnumeric(filenames(1,1))
%              y = size(filenames,2);
%              for j=1:y
%                  ext = filenames{j}(end-2:end);
%                  if strcmpi(ext,'mat')
%                      varlist = whos('-file',filenames{j});
%                      for k=1:numel(varlist)
%                          newObj = load(filenames{j},varlist(k).name); %#ok<NASGU>
%                          newObj = eval(['newObj.',varlist(k).name]);
%                          if isa(newObj,'ltpda_uo')
%                              LTPDAinvar = [LTPDAinvar; {newObj,1,'From file'} ];
%                              disp('  + 1 Obj added to the global variable LTPDAinvar')
%                          end
%                      end
%                  elseif strcmpi(ext,'xml')
%                     newObj = utils.xml.xmlread(xmlread(filenames{j}));
%                     if isa(newObj,'ltpda_uo')
%                        LTPDAinvar = [LTPDAinvar; {newObj,1,'From file'} ];
%                        disp(sprintf('  + 1 %s added to the global variable LTPDAinvar',class(newObj)))
%                     end
%                  else
%                     try
%                      newObj = {ao(filenames{j}),1,'From file'};
%                      LTPDAinvar = [LTPDAinvar; {newObj,1,'From file'} ];
%                      disp('  + 1 AO added to the global variable LTPDAinvar')
%                     catch
%                        disp(['  *** Impossible to load file ',filenames{j}])
%                     end
%                  end
%              end
%              UpdateListbox();
%          end
%     
%     end
%     %----------------------------------------------------------------------
% 
%     %----------------------------------------------------------------------
%     function hRemoveButtonCallback(varargin)   
%     % Callback function: run when the user click the "Remove data" button
% 
%            index_selected = get(InputObjList,'Value');
%            listObjs = get(InputObjList,'String');
%            if ~strcmp(listObjs,'The memory is empty')
%                for i=1:numel(index_selected)
%                    objSelect = str2double(strtok(listObjs{index_selected(i),1},'.'));
%                    LTPDAinvar{objSelect,1} = [];
%                end
%                UpdateListbox();
%            end
%            set(findobj('Tag', 'infoPanel'), 'String', '')
% 
%     end
%     %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hExportButtonCallback(varargin)   
    % Callback function: run when the user click the "Export data" button

         currSelObjs   = get(InputObjList,'Value');
         listObjs = get(InputObjList,'String');
         if ~strcmp(listObjs,'The memory is empty')
             selectedObjs  = {};
             for i=1:numel(currSelObjs)
                 objSelect = str2double(strtok(listObjs{currSelObjs(i),1},'.'));
                 selectedObjs = [selectedObjs,LTPDAinvar(objSelect,1)];
             end
             if ~isempty(selectedObjs)
                 for i=1:numel(selectedObjs)
                     objName = [class(selectedObjs{i}),'_',selectedObjs{i}.name];
                     objName = genvarname(objName,evalin('base','who'));
                     assignin('base', objName, selectedObjs{i});
                     disp(['Saved to workspace with name ',objName])
                 end
             end
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hExploreButtonCallback(varargin)   
    % Callback function: run when the user click the "Update list" button

         currSelObjs   = get(InputObjList,'Value');
         listObjs = get(InputObjList,'String');
         if ~strcmp(listObjs,'The memory is empty')
             selectedObjs  = {};
             for i=1:numel(currSelObjs)
                 objSelect = str2double(strtok(listObjs{currSelObjs(i),1},'.'));
                 selectedObjs = [selectedObjs,LTPDAinvar(objSelect,1)];
             end

             if ~isempty(selectedObjs)
                 ltpda_explorer(selectedObjs);
             else
                 ltpda_explorer(LTPDAinvar);
             end

             UpdateListbox();
         end

    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hReportButtonCallback(varargin)   
    % Callback function: run when the user click the "Update list" button

         currSelObjs   = get(InputObjList,'Value');
         listObjs = get(InputObjList,'String');
         if ~strcmp(listObjs,'The memory is empty')
             selectedObjs  = {};
             for i=1:numel(currSelObjs)
                 objSelect = str2double(strtok(listObjs{currSelObjs(i),1},'.'));
                 selectedObjs = [selectedObjs,LTPDAinvar(objSelect,1)];
             end

             if ~isempty(selectedObjs)
                report(selectedObjs,'dir',[cd,'\Reports']);
             else
                ltpda_explorer(LTPDAinvar);
             end

             UpdateListbox();
         end

    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function SaveWorkspaceCallback(varargin)
    % Callback function: run when the user click the "Save all"
    % button

         try
             [FileName,PathName] = uiputfile('*.mat','Save Workspace As');
             if ~isa(FileName,'double'), save(strcat(PathName,FileName),'LTPDAinvar','LTPDAoutvar'); disp('Workspace saved'); end
         catch
         end
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function LoadWorkspaceCallback(varargin)
    % Callback function: run when the user click the "Load workspace"
    % button
    
         try
             [FileName,PathName] = uigetfile('*.mat','Load Workspace');
             temp = load(strcat(PathName,FileName),'LTPDAinvar');
             LTPDAinvar = [LTPDAinvar ; temp.LTPDAinvar];
             temp = load(strcat(PathName,FileName),'LTPDAoutvar');
             LTPDAoutvar = [LTPDAoutvar ; temp.LTPDAoutvar];
             disp('Workspace loaded')
             clear temp
             UpdateListbox()
         catch
         end
    end
    %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function UpdateListbox(varargin)
    % Updates the listboxes

         %==================================
         % Update the list of active AOs
         xx = size(LTPDAinvar,1);
         listInput=cell(xx,1);
         if xx>0
             for j=1:xx
                 listInput{j,1} = num2str(j);
                 [rows,columns] = size(LTPDAinvar{j,1});
                 if (rows>1 && columns==1) || (rows==1 && columns>1), listInput{j,1} = [listInput{j,1}, ' .(Vector ',num2str(rows),'x',num2str(columns),') '];
                 elseif rows>1 && columns>1, listInput{j,1} = [listInput{j,1}, ' .(Matrix ',num2str(rows),'x',num2str(columns),') '];
                 end
                 if isempty(LTPDAinvar{j,1}), listInput{j,1} = [];
                 else
                    switch class(LTPDAinvar{j,1})
                       case 'ao'
                          anobject  = LTPDAinvar{j,1};
                          aoname    = anobject.name;
                          aocreated = char(anobject.created);
                          listInput{j,1} = [listInput{j,1}, ' . AO .' , aoname , '__' , aocreated];
                       case 'plist'
                          paramNumb = nparams(LTPDAinvar{j,1});
                          objcreated = char(LTPDAinvar{j,1}.created);
                          listInput{j,1}=[listInput{j,1}, ' . PLIST .',num2str(paramNumb),' params','__',objcreated];
                       case {'pzmodel','miir','mfir'}
                          objcreated = char(LTPDAinvar{j,1}.created);
                          listInput{j,1}=[listInput{j,1}, ' . ',upper(class(LTPDAinvar{j,1})),' .__',objcreated];
                       case 'double'
                          if numel(LTPDAinvar{j,1})==1, objclass  = ' . Scalar .__ ';
                          elseif size(LTPDAinvar{j,1},1)==1 || size(LTPDAinvar{j,1},2)==1, objclass = ' . Vector .__ ';
                          else objclass = ' . Matrix .__ ';
                          end
                          listInput{j,1}=[listInput{j,1}, objclass, mat2str(LTPDAinvar{j,1})];
                       otherwise
                          listInput{j,1}=[listInput{j,1}, ' . ',upper(class(LTPDAinvar{j,1}))];
                    end
                 end
             end
             for j=xx:-1:1, if isempty(listInput{j,1}), listInput(j,:)=[]; end; end
         else
             listInput{1,1}='The workspace is empty';
         end
         
         InputObjList = findobj('Tag','InputObjList');
         if ~isempty(InputObjList)
             set(InputObjList,'Value',1)
             set(InputObjList,'String',listInput)
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hListObjsCallback(hObject, varargin)   
    % This callback is called whenever the user double click upon one of
    % the AOs in use.
    
        if ~isempty(varargin{1}) && varargin{1}==1 && size(LTPDAinvar,1)>0
                val = get(hObject, 'Value');
                if length(val) == 1
                    objLines = get(hObject, 'String');
                    selVal = str2double(deblank(strtok(objLines{val})));
                    if isempty(objLines) || isempty(LTPDAinvar{selVal ,1}) || (isnumeric(LTPDAinvar{selVal ,1}) && numel(LTPDAinvar{selVal ,1})>1)
                        objtxt = '';
                    else
                        objtxt = display(LTPDAinvar{selVal,1});
                    end
                else
                    objtxt = '';
                end
                set(findobj('Tag', 'infoPanel'), 'String', objtxt)
        elseif size(LTPDAinvar,1)>0
            if strcmp(get(gcf,'SelectionType'),'normal')
                val = get(hObject, 'Value');
                if length(val) == 1
                    objLines = get(hObject, 'String');
                    objnumb = str2double(deblank(strtok(objLines{val})));
                    try
                        objtxt = display(LTPDAinvar{objnumb});
                    catch
                        if isa(LTPDAinvar{objnumb},'double') || isa(LTPDAinvar{objnumb},'logical'), objtxt = mat2str(LTPDAinvar{objnumb});
                        elseif isa(LTPDAinvar{objnumb},'char'), objtxt = LTPDAinvar{objnumb,1};
                        else objtxt = class(LTPDAinvar{objnumb});
                        end
                    end
                    if isempty(LTPDAinvar{objnumb,1}), objtxt=''; end
                else
                    objtxt = '';
                end
                set(findobj('Tag', 'infoPanel'), 'String', objtxt)
            end

            if strcmp(get(gcf,'SelectionType'),'open') && ~isempty(get(hObject, 'String')) && ~isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'))
                val = get(hObject, 'Value');
                objLines = get(hObject, 'String');
                number = deblank(strtok(objLines{val}));
                if isempty(LTPDAinvar{str2double(number),1}), return; end
                set_param(utils.prog.gcbsh,'Selected','off');
                newBlkHandle=add_block('ltpda_library/Input/Object from list', strcat(bdroot,'/AO1'),'MakeNameUnique', 'on');
                children=get_param(newBlkHandle,'Blocks');
                inputblock=strcat(get(newBlkHandle,'Path'),'/',get(newBlkHandle,'Name'),'/',children{1});
                set_param(inputblock,'Value',number );
              % Set the MaskDisplay = n� of input:
                set_param(newBlkHandle,'LinkStatus','inactive');
                set_param(newBlkHandle,'MaskDisplay',sprintf('disp(''%s'')',num2str(number)));
              % Modify the block annotation:
                objName = LTPDAinvar{str2double(number),1}.name;
                if numel(objName)>3 && strcmpi(objName,'none'), objName = class(LTPDAinvar{str2double(number),1}); end
                if numel(objName)>20, objName = ['...',LTPDAinvar{str2double(number),1}.name(end-20:end)]; end
                set_param(newBlkHandle,'AttributesFormatString',[number,': ',objName]);
                set_param(newBlkHandle,'Selected','on');

            end
        end
         
    end
    %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function hNewButtonCallback(varargin)
    % Callback function: run when the user click the "New model" button.
    % It starts also the timer associated to the continuous selection check
    % (this must be changed in order to allow multiple system execution).

         hour          = datestr(now,13); % HH:MM:SS
         hour(3:4)     = hour(4:5);hour(5:6)=hour(7:8);
         currentsystem = strcat(genvarname(strrep(getappdata(0,'ltpda_repo_user'),'.','_')),'_',datestr(now,7),datestr(now,5),datestr(now,11),'_',hour(1:6));
         if ~isempty(find_system('Name',currentsystem)), return; end
         simulink
         new_system(currentsystem)
         open_system(currentsystem)
         
         systemHandle = get_param(gcs,'Handle');
         evalin('base','load ltpdaSimConfigSet.mat;');
         ltpdaSimConfigSet = evalin('base','ltpdaSimConfigSet');
         attachConfigSetCopy(systemHandle, ltpdaSimConfigSet);
         setActiveConfigSet(systemHandle, 'LTPDA');
         detachConfigSet(systemHandle, 'Configuration');
         evalin('base','clear ltpdaSimConfigSet;');
         
         set(systemHandle,'Location',[200 100 1100 600]);
         set(systemHandle,'Toolbar','OFF');
         
         caption = [gcs,'/1'];
         libraryNote = add_block('built-in/Note',caption,'Position', [100 0 0 400]);
         guiNote     = add_block('built-in/Note',caption,'Position', [100 0 0 430]);
         set_param(guiNote,'ClickFcn','ltpdagui(''Redraw'',2); figure(findobj(''Tag'',''LTPDAGUI''))')
         set_param(libraryNote,'ClickFcn','simulink')
         set_param(guiNote,'Text','    GUI   ','FontSize',14,'HorizontalAlignment','center','BackgroundColor','[0.686275, 0.686275, 0.847059]','DropShadow','on')
         set_param(libraryNote,'Text',' Library ','FontSize',14,'HorizontalAlignment','center','BackgroundColor','[0.870588, 0.870588, 0.937255]','DropShadow','on')
         
         mainNote = add_block('built-in/Note',caption,'Position', [200 0 0 400],'UserData',1);
         caption1 = ['          Analysis designed by ',getappdata(0,'ltpda_repo_user')];
         caption2 = ['created (UTC): ',char(time)];
         caption3 = ['                 IP: ',char(getHostAddress(java.net.InetAddress.getLocalHost))];
         caption4 = ['               OS: ',computer];
         caption5 = ['MATLAB ver: ',getappdata(0, 'matlab_version')];
         caption6 = ['   LTPDA ver: ',getappdata(0, 'ltpda_version')];
         caption = strvcat(caption1,caption2,caption3,caption4,caption5,caption6); %#ok<VCAT>
         set_param(mainNote, 'HorizontalAlignment','left','Text',caption,'Tag','ltpda model')
         ltpdaClickFcn = 'load_system(''ltpda_library''); blk = add_block(''ltpda_library/Commonly Used Blocks/hollow'', strcat(bdroot,''/func1''),''MakeNameUnique'', ''on'');     set(blk,''LinkStatus'',''inactive'',''MaskDisplay'',''disp(''''hollow'''')'');     set(utils.prog.find_in_models(blk,''LookUnderMasks'',''all'',''BlockType'',''M-S-Function'',''FunctionName'',''ltpdasim''),''Tag'','''',''Name'',''hollow'');    set(blk,''Selected'',''on'');set(find_system(bdroot,''FindAll'',''on'',''Type'',''Annotation'',''Tag'',''ltpda model''),''Selected'',''off'');     ltpdagui(''callback'',1,''redraw'',2);';
         set_param(mainNote,'ClickFcn',ltpdaClickFcn)

    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hSaveCallback(varargin)   
    % This callback is called whenever the user click the 'Save' button to
    % store the current model on disk.
    
         if ~isempty(bdroot) && ~isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'))
             inputBlockHandles = get_param(find_system(bdroot,'AncestorBlock','ltpda_library/Input/Object from list'),'handle');
             for i=1:numel(inputBlockHandles)
                 children   = get_param(inputBlockHandles{i},'Blocks');
                 inputblock = strcat(get(inputBlockHandles{i},'Path'),'/',get(inputBlockHandles{i},'Name'),'/',children{1});
                 currIndex(i)  = str2double(get_param(inputblock,'Value'));
                 if currIndex(i)~=0
                     objcommand = string(LTPDAinvar{currIndex(i)});
                     set_param(inputBlockHandles{i},'Description',objcommand);
                 end
             end

             oldName  = bdroot;
             if ~isempty(oldName) && ~isempty(find_system(oldName,'FindAll','on','Type','Annotation','Tag','ltpda model'))
                 try
                     try cd(getappdata(0,'DefaultAnalysesDirectory')); catch, end
                     [fileName,filePath] = uiputfile([oldName,'.mdl'],'Choose destination folder');
                     fileName = [filePath,fileName];
                     save_system(oldName,fileName)
                     try cd(getappdata(0,'DefaultDataDirectory')); catch, end
                 catch
                 end
             end
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function hOpenCallback(varargin)   
    % This callback is called whenever the user click the 'Open' button, to
    % retrieve a previously saved model from disk.
    
         try
             try cd(getappdata(0,'DefaultAnalysesDirectory')); catch, end
             [fileName,filePath] = uigetfile('.mdl','Choose source file');
             try cd(getappdata(0,'DefaultDataDirectory')); catch, end
             fileName = [filePath,fileName];
             open_system(fileName)
             simulink
             
           % Load the globals into memory:
             globBlock = find_system(bdroot,'BlockType','SubSystem','Tag','globals');
             if ~isempty(globBlock), gl = get_param(globBlock{1},'UserData'); end

           % Load the nested loop variable into memory:
             nestBlock = find_system(bdroot,'BlockType','SubSystem','Tag','nestedloops');
             if ~isempty(nestBlock), loop = get_param(nestBlock{1},'UserData'); set(findobj('String',' Enable nested loops'),'Value',1); end

           % Update the indexes inside 'Object from list':
             inputBlockHandles = get_param(find_system(gcs,'AncestorBlock','ltpda_library/Input/Object from list'),'handle');
             for i=1:numel(inputBlockHandles)
                 objcommand = get_param(inputBlockHandles{i},'Description');
                 if ~isempty(objcommand)
                     xx         = size(LTPDAinvar,1);
                     objcommand = ['LTPDAinvar{',num2str(xx+1),',1}=',objcommand,';LTPDAinvar{',num2str(xx+1),',2}=0'];
                     eval(objcommand);

                     % Update the pointer inside the input block and the annotation:
                     children   = get_param(inputBlockHandles{i},'Blocks');
                     inputblock = strcat(get(inputBlockHandles{i},'Path'),'/',get(inputBlockHandles{i},'Name'),'/',children{1});
                     set_param(inputblock,'Value',num2str(xx+1))
                     set_param(inputBlockHandles{i},'AttributesFormatString',num2str(xx+1));
                 end
             end
             
             UpdateListbox()
         catch
         end
         
         
    end
    %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function StartExec(varargin)   
    % This callback is called whenever the user click the 'Start' button.
    
         if isempty(bdroot) || isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model')), return; end
         button = findobj('Tag','StartButton');
         set(button,'CData',imread('startred.jpg'),'ButtonDownFcn','');
             
       % Check availability of inputs expected by the model:
         inputBlocks = find_system(bdroot,'Tag','input');
         missInputs = {};
         for nn = 1:numel(inputBlocks)
            innerBlocks = get_param(inputBlocks{nn},'Blocks');
            inputVal = str2double(get_param([inputBlocks{nn},'/',innerBlocks{1}],'Value'));
            if inputVal>size(LTPDAinvar,1) || isempty(LTPDAinvar{inputVal,1}) % one expected input is missing
               missInputs = [missInputs;{['The block ''',inputBlocks{nn},''' expects input n�',num2str(inputVal)]}];
            end
         end
         if ~isempty(missInputs)
            screenSize = get(0,'ScreenSize');
            backColor   = [1 1 1];
            position   = [(screenSize(3)-400)/2,(screenSize(4)-160)/2,400,160];
            inputMissFig = figure('Position',position,'Name','Input missing','Resize','off','NumberTitle','off','Toolbar','none','Menubar','none','CloseRequestFcn','uiresume; closereq');
            uicontrol('Parent',inputMissFig,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[50 position(4)-90 position(3)-60 50],'String',{'The model expects an input, but';'none is loaded.'},'FontName','Times New Roman','FontSize',13,'FontWeight','normal','Visible','on','Style','text');
            uicontrol('Parent',inputMissFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[70 30 310 20],'String',missInputs,'Value',1,'Visible','on','Style','popup')
            logosize = [40 40];
            nobut = axes('Parent',inputMissFig,'Units','pixels','Position',[10 , position(4)-logosize(2)-60 , logosize],'Tag','No');
            image(imread('startred.jpg'),'Parent',nobut);
            axis(nobut,'off');
            uiwait;
            set(button,'CData',imread('startgreen.jpg'),'ButtonDownFcn','ltpdagui(''redraw'',1.1);');
            return;
         end
         
         disp('============================')
         disp('   Beginning the analysis')
         disp('============================')
         stop(timerfindall)
           drawnow
         currSystem = bdroot;
            allBlocks = find_system(currSystem,'LookUnderMasks','all');
            for i=2:numel(allBlocks), set_param(allBlocks{i},'LinkStatus','inactive'); set_param(allBlocks{i},'MaskVariables',''); end
         addterms(currSystem)
         
       % Check if it's a partial execution:
         if ismember('executionList',evalin('base','who')), partialExecution = 1; else partialExecution = 0; end
         
       % Clear the previous execution history:
         if ~partialExecution, set_param(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'),'UserData',''); end

       % Set all objects present at the startup to be maintained:
         if size(LTPDAinvar,1)>0, LTPDAinvar(:,2) = {1}; end

       % Load the globals from the current model:
         globBlock = find_system(bdroot,'BlockType','SubSystem','Tag','globals');
         if ~isempty(globBlock), gl = get_param(globBlock{1},'UserData'); end
         
         executionTime = [];
         nestBlock = find_system(currSystem,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         
       % Check for nested loops:
         if ~isempty(nestBlock) && str2double(get_param(nestBlock{1},'Description'))
            disp('  Execution in nested loops')
            disp('============================')
            paramLoop = get_param(nestBlock{1},'UserData');
          % To disable unused nested loop parameters:
            allfuncBlocks = utils.prog.find_in_models(gcs,'LookUnderMasks','all','BlockType','M-S-Function','FunctionName','ltpdasim');
            paramLoopnumb = size(paramLoop,1);
            enabledNestedParams = get_param(nestBlock,'MaskDescription');
            if ~isempty(enabledNestedParams{1}), eval(enabledNestedParams{1});
            else enabledNestedParams = ones(1,paramLoopnumb);
            end
            usedParamsLoop = zeros(paramLoopnumb,1);
            for mmm = 1:paramLoopnumb
               for nnn = 1:numel(allfuncBlocks)
                  if ~isempty(findstr(get_param(get_param(allfuncBlocks{nnn},'parent'),'Description'),paramLoop{mmm,3})), usedParamsLoop(mmm)=1; break; end
               end
            end
            for mmm = paramLoopnumb:-1:1
               if ~usedParamsLoop(mmm) || ~enabledNestedParams(mmm)
                % then the mmm-th line in paramLoop must be removed
                  ii = mmm+1;
                  while ii <= paramLoopnumb && paramLoop{ii,2} > paramLoop{mmm,2}
                     paramLoop{ii,2} = paramLoop{ii,2}-1;
                     ii = ii+1;
                  end
                  if ~usedParamsLoop(mmm), disp(sprintf(' Parameter %s has been ignored for nested loops, being unused.',paramLoop{mmm,3}))
                  else disp(sprintf(' Parameter %s has been ignored for nested loops, being disabled.',paramLoop{mmm,3}))
                  end
                  paramLoop(mmm,:)    = [];
                  usedParamsLoop(mmm) =[];
                  paramLoopnumb       = paramLoopnumb-1;
               end
            end
            if ~isempty(paramLoop), useNestedLoop = 1; else useNestedLoop =0; end
         else useNestedLoop =0;
         end
         
         try
            if useNestedLoop
             % ==================================================================
             % Execution with nested loops
             % ==================================================================

             % paramLoop has 6 columns:
             %    n�   |   order  |  parameter's name  |  n� of iterations   |   range settings   |  cell arrays of values
             %
             % Example:      n�  order    appearance
             % paramLoop={    1   1  ...   x-------
             %                2   2  ...   .x------
             %                3   3  ...   ..x-----
             %                4   2  ...   .x------
             %                5   3  ...   ..x-----
             %                6   1  ...   x-------

               branches=[];

               for ii=1:paramLoopnumb, if ii==paramLoopnumb || paramLoop{ii+1,2}<=paramLoop{ii,2}, branches=[branches,ii]; end; end
             % 'branches' contains the ordinal number of those rows which do not have
             % a children row, ie. the following rows have higher order.
             % In the example above, branches = [ 3 , 5 , 6 ];

               family={};
               numbIter={};
               for ii=1:numel(branches)
                  currOrder=paramLoop{branches(ii),2};
                  family{ii,1}  = 0;
                  numbIter{ii,1} = 1;
                  for jj=branches(ii):-1:1
                     if paramLoop{jj,2}==currOrder
                        family{ii,currOrder+1}   = jj;
                        family{ii,1}             = family{ii,1}+1;
                        numbIter{ii,currOrder+1} = paramLoop{jj,4};
                        numbIter{ii,1}           = numbIter{ii,1}*paramLoop{jj,4};
                        currOrder                = paramLoop{jj,2}-1;
                     end
                  end
               end
               totalIter = sum(cell2mat(numbIter(:,1)));
               currIter  = 0;
             % 'family' contains all the parents information for each branch: the
             % first column contains how many parents there are. In the example:
             % family = {  3    1    2    3
             %             3    1    4    5
             %             1    6              }
             % Similarly, numbIter contains the number of iteration necessary to
             % complete each param. The first column contains the total for each
             % branch/row.
             % numbIter   = {  40   2    4    5
             %                 36   2    6    3
             %                 10   10             }

               for ii=1:numel(branches)
                  x = family{ii,1};   % x = how many params to change in this branch
                  status = ones(1,x); % status shows the current step in the loop;
                % [2,3,5] means that we've executed the 2nd value for the first param,
                % the 3rd for the second param, and the 5th for the third param.

                  for iter = 1:numbIter{ii,1}
                   % ==============================================================
                   % Here goes what must be executed
                   % ==============================================================
                     currIter = currIter+1;
                     disp(['  ..... starting loop ',num2str(currIter),', ',num2str(totalIter-currIter),' more to go.'])
                     statusString = '  ***** Executing now with ';
                     setappdata(0,'loopStatus',[totalIter currIter])
                     progressBar(executionTime);
                     drawnow

                     for mm=1:size(paramLoop,1)
                        if isempty(paramLoop{mm,7}), disp(['*** Error: default value not set for parameter ',paramLoop{mm,3}]); return; end
                        eval([paramLoop{mm,3},'=',paramLoop{mm,7},';'])
                     end
                     for nn=1:numel(status)
                        value = paramLoop{family{ii,nn+1},6}{status(nn)};
                        if ~ischar(value), value = mat2str(value); end
                        eval([paramLoop{family{ii,nn+1},3},'=',  value  ,';'])
                        statusString = [statusString, paramLoop{family{ii,nn+1},3}(6:end) , ' = ' , value ,'; '];
                     end
                     disp(statusString)
                     startingTime = now;

                   % ==============================================================
                     varargout = sim(currSystem);  %#ok<NASGU>
                   % ==============================================================
                     
                     executionTime = [executionTime; now-startingTime];
                   
                   % Check if the user wants to stop the execution:
                     lastChar = get(findobj('Name','LTPDA Progress Bar'),'CurrentCharacter');
                     if ~isempty(lastChar) && strcmp(lastChar,'x'), break; end

                     for jj=x:-1:1
                        if status(jj)<numbIter{ii,jj+1} % then we still have to complete iterations on i-th row
                           status(jj)=status(jj)+1;
                           if jj~=x % if we've just increased a line which is not the last one, reset the lower lines
                              for kk=jj+1:x
                                 status(kk)=1;
                              end
                           end
                           break
                        end
                     end
                  end
               end % End of execution with nested loops
            else % Execution without nested loops
               if ~isempty(nestBlock) && ~str2double(get_param(nestBlock{1},'Description'))
                % Nested loops are set but disabled
                  disp('*** Nested loops, while set, are disabled; using default values.')
                  paramLoop = get_param(nestBlock{1},'UserData');
                  for mm=1:size(paramLoop,1)
                     if isempty(paramLoop{mm,7}), disp(['*** Error: default value not set for parameter ',paramLoop{mm,3}]); return; end
                   % Setting every nested loops variable = default
                     eval([paramLoop{mm,3},'=',paramLoop{mm,7},';'])
                     disp(['    ',paramLoop{mm,3},' =  ',paramLoop{mm,7}])
                  end
               end
               setappdata(0,'loopStatus',[]);
               progressBar();
               drawnow
             % ==============================================================
               varargout = sim(currSystem);  %#ok<NASGU>
             % ==============================================================
            end

            close(findobj('Name','LTPDA Progress Bar'))

          % Remove final results (intermediate were removed during analysis, as
          % soon as they became not useful anymore):
            if ~getappdata(0,'maintainresults') % && ~partialExecution
               for i=size(LTPDAinvar,1):-1:1
                  if LTPDAinvar{i,2}==0
                     LTPDAinvar(i,:)=[];
                     % Update the execution history:
                     ltpda_annotation = find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model');
                     execHistory = get_param(ltpda_annotation,'UserData');
                     for paramLoopnumb=1:size(execHistory,1)
                        for yy=3:size(execHistory,2),
                           if execHistory{paramLoopnumb,yy} == i, execHistory{paramLoopnumb,yy} = -1; end
                           if execHistory{paramLoopnumb,yy} > i, execHistory{paramLoopnumb,yy} = execHistory{paramLoopnumb,yy}-1; end
                        end
                        if execHistory{paramLoopnumb,1} == i, execHistory{paramLoopnumb,1} = -1; end
                        if execHistory{paramLoopnumb,1} > i, execHistory{paramLoopnumb,1} = execHistory{paramLoopnumb,1}-1; end
                     end
                     set_param(ltpda_annotation,'UserData',execHistory);

                  end
               end
            end

            UpdateListbox();
            set(button,'CData',imread('startgreen.jpg'),'ButtonDownFcn','ltpdagui(''redraw'',1.1);');
            evalin('base','clear executionList');
            disp('============================')
            disp('     Analysis concluded')
            disp('============================')
            start(timerfindall)

       % ==================================
         catch ME
       % ==================================

           % Remove anyway intermediate results:
             keepRes = getappdata(0,'maintainresults');
             if ~keepRes, for i=size(LTPDAinvar,1):-1:1, if LTPDAinvar{i,2}==0, LTPDAinvar(i,:)=[]; end; end; end

             UpdateListbox();
             close(findobj('Name','LTPDA Progress Bar'))
             set(button,'CData',imread('startgreen.jpg'),'ButtonDownFcn','ltpdagui(''redraw'',1.1);');
             evalin('base','clear executionList');
             start(timerfindall)

             rethrow(ME)
         end

    end
    %----------------------------------------------------------------------
%%

end