function varargout = layout_manager(varargin)
%LAYOUT_MANAGER - Application M-file to manage the window layout
% function varargout = layout_manager(varargin)
%    FIG = LAYOUT_MANAGER launch layout_manager GUI.
%    LAYOUT_MANAGER('callback_name', ...) invoke the named callback.
%
% Clicking on the figure background automatically refreshes the window list.
% Right click the "Set" button or press the "Help" button for information on
%  how to set the BrainStorm margins.

%<autobegin> ---------------------- 12-Oct-2004 01:11:23 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\layout_manager.m  NOTE: Routine calls itself explicitly
%
% Subfunctions in this file, in order of occurrence in file:
%   load_listbox(handles);
%   varargout = pushbutton_align_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_close_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_close_tiles_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_margins_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_full_Callback(h, eventdata, handles, varargin)
%   varargout = listbox_tiles_Callback(h, eventdata, handles, varargin)
%   varargout = pushbutton_refresh_Callback(h, eventdata, handles, varargin)
%   varargout = layout_manager_WindowButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = pushbutton_margins_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = pushbutton_help_Callback(h, eventdata, handles, varargin)
%
% Group : Preference data and their calls in this file:
%   brainstormHomeDirectory = getpref('BrainStorm','brainstormHomeDir');
%
% Application data and their calls in this file:
%   'TileHandle'
%   'TileType'
%   
%   setappdata(fig,'TileType','D');
%   setappdata(hl,'TileHandle',TileHandle);
%   
%   TileHandle = getappdata(h,'TileHandle');
%   tempTileType = getappdata(hf(i),'TileType');
%
% Figure Files opened by this function:
%   mfilename
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure layout_manager.fig
%   figure::layout_manager "" uses WindowButtonDownFcn for <automatic>
%   uicontrol:listbox:listbox_tiles "Listbox" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_align "Snap" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_close "Close All" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_close_tiles "Close Tiles" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_full "Default" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_help "Help" uses ButtonDownFcn for
%     layout_manager('pushbutton_margins_ButtonDownFcn',gcbo,[],guidata(gcbo))
%   uicontrol:pushbutton:pushbutton_help "Help" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_margins "Set" uses ButtonDownFcn for <automatic>
%   uicontrol:pushbutton:pushbutton_margins "Set" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton_refresh "Refresh" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $  $Revision: 27 $  $Date: 10/11/04 11:33p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 23-Sep-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 12-Oct-2004 01:11:23 -----------------------

% Script History---------------------------------------------------------------------------------------------------------------------------
% EK  5-Oct-2004 Tile type 'd' is also included
% -----------------------------------------------------------------------------------------------------------------------------------------

% Last Modified by GUIDE v2.0 17-Nov-2003 10:42:56

if nargin == 0  % LAUNCH GUI
   
   fig = openfig(mfilename,'reuse');
   
   % Use system color scheme for figure:
   set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
   bst_color_scheme(fig);
   setappdata(fig,'TileType','D'); % dynamic window
   bst_layout('align',fig);
   
   % custom fig handling
   hlistbox = findobj(fig,'tag','listbox_tiles');
   set(hlistbox,'fontname','arial');
   
   % now show it
   set(fig,'visible','on');
   
   % Generate a structure of handles to pass to callbacks, and store it. 
   handles = guihandles(fig);
   guidata(fig, handles);
   
   if nargout > 0
      varargout{1} = fig;
   end
   
   load_listbox(handles);
   
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
   
   try
      if (nargout)
         [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
      else
         feval(varargin{:}); % FEVAL switchyard
      end
   catch
      disp(lasterr);
   end
   
end

% local functions
% --------------------------------------------------------------
function load_listbox(handles);

fig = handles.layout_manager; % handy ref
hl = handles.listbox_tiles;

set(0,'showhidden','on');
hf = findobj(0,'type','figure'); % all of the windows

hf = sort(hf);  % for consistent ordering

% start with the command window
String = cell(1000,1); % allocate
TileHandle = zeros(1000,1);
iString = 0;
TileType = cell(1000,1);

for i = 1:length(hf),
   tempTileType = getappdata(hf(i),'TileType');
   if(~isempty(tempTileType)),
      tempTileType = tempTileType(1); % only care about first letter
      switch tempTileType
      case {'T','M','S','D', 'd'} % a bst tile or window
         iString = iString + 1; % increment counter
         TileType{iString} = tempTileType;
         String{iString} = sprintf('%s',get(hf(i),'Name'));
         TileHandle(iString) = hf(i); % append
         if(strcmp(tempTileType,'M') | strcmp(tempTileType,'S')),
            % don't bring automatically up the tiles
            % since they may have lots of data
            % don't bring up dynamic windows, since they will
            % coverup the Window Manager
            % But do bring forward the message window and static toolbar
            figure(hf(i)); % bring to forefront
         end
      end
   end
end

% add dash line for prettiness
iString = iString + 1; % increment counter
String{iString} = '---- Tiles ----';
TileHandle(iString) = NaN;
TileType{iString} = '-'; % special handling case here

% trim allocations
String = String(1:iString);
TileHandle = TileHandle(1:iString);
TileType = TileType(1:iString);

% sort
[String,ndex] = sort(String);
TileHandle = TileHandle(ndex); % sorted correspondingly
TileType = TileType(ndex);

% Now put the special windows at the top
Types = {'-','D','M','S'}; % reverse order
for i = 1:length(Types),
   ndex = find(strncmp(Types{i},TileType,1));
   if ~isempty(ndex),
      ndex = ndex(:)';
      ndx = 1:iString;
      ndx(ndex) = [];
      String = String([ndex ndx]);
      TileHandle = TileHandle([ndex ndx]);
      TileType = TileType([ndex ndx]);
   end
end

% add top dash line for prettiness
iString = iString + 1; % increment counter
String{iString} = '---- Toolbars ----';
TileHandle(iString) = NaN;
TileType{iString} = '-'; % special handling case here
String = String([end 1:(end-1)]); % put at top
TileHandle = TileHandle([end 1:(end-1)]);
TileType = TileType([end 1:(end-1)]);


set(hl,'Val',1); % reset index
set(hl,'String',String);
setappdata(hl,'TileHandle',TileHandle); % for recalling
figure(fig) % make this gui the current figure



% --------------------------------------------------------------------
function varargout = pushbutton_align_Callback(h, eventdata, handles, varargin)

load_listbox(handles)
bst_layout('align');

% --------------------------------------------------------------------
function varargout = pushbutton_close_Callback(h, eventdata, handles, varargin)
% close all but the BrainStorm toolbar and message window

bst_layout('close all');
layout_manager; % reinstall the layout manager



% --------------------------------------------------------------------
function varargout = pushbutton_close_tiles_Callback(h, eventdata, handles, varargin)
% close only the tiles
bst_layout('close');
load_listbox(handles)



% --------------------------------------------------------------------
function varargout = pushbutton_margins_Callback(h, eventdata, handles, varargin)

bst_layout('margins');
load_listbox(handles)


% --------------------------------------------------------------------
function varargout = pushbutton_full_Callback(h, eventdata, handles, varargin)

bst_layout('full');
load_listbox(handles)




% --------------------------------------------------------------------
function varargout = listbox_tiles_Callback(h, eventdata, handles, varargin)

TileHandle = getappdata(h,'TileHandle'); % list of handles
Val = get(h,'Val'); % what line clicked on

if isnan(TileHandle(Val)),
   % dashed line or other pretty character
   % do nothing
   
elseif ~ishandle(TileHandle(Val)),
   
   % figure has already disappeared, user probably closed
   load_listbox(handles) % reload
   
else
   % figure handle is valid
   
   status = get(handles.layout_manager,'SelectionType');
   switch status
   case 'normal'
      figure(TileHandle(Val)); % bring to front
   case 'open' % user double clicked
      close(TileHandle(Val));
      load_listbox(handles) % refresh
   end
   
end




% --------------------------------------------------------------------
function varargout = pushbutton_refresh_Callback(h, eventdata, handles, varargin)

load_listbox(handles) % refresh



% --------------------------------------------------------------------
function varargout = layout_manager_WindowButtonDownFcn(h, eventdata, handles, varargin)
% make sure window names are refreshed when clicking in this window
% note that frames and static text have been set to "inactive" so that clicking
%  on them also acts like clicking on the background of the figure.
% This function does not activate when clicking on an active uicontrol.

pushbutton_refresh_Callback(handles.pushbutton_refresh, eventdata, handles, varargin);


% ------------------------- HELP FUNCTIONS -------------------------------------

% --------------------------------------------------------------------
function varargout = pushbutton_margins_ButtonDownFcn(h, eventdata, handles, varargin)
% right click on the "Set" button for help



% --------------------------------------------------------------------
function varargout = pushbutton_help_Callback(h, eventdata, handles, varargin)
% Explicit HELP button in the manager
% Now a Word Document

brainstormHomeDirectory = getpref('BrainStorm','brainstormHomeDir');

if 0, % old help style
   
   msg1 = {'Windows:','',['The "control" GUIs "Messages" and "BrainStorm" are always at the bottom of the BrainStorm ',...
            'viewing area, and various "managers" appear along the right hand side. The "tiles" are the ',...
            'GUIs appearing in the large upper left area. Single click any GUI name in the list to ',...
            'have it brought to the foreground. Double-click any GUI name to close it.'],...
         '',['Pressing "Refresh" ',...
            'refreshes the list, as does a single click in the background of the Layout Manager.'],...
         '','Pressing "Close All" closes all "tiles" but not the BrainStorm control GUIs.',...
         '',['Pressing "Snap" realigns all GUIs to their correct locations (as Set by Margins), ',...
            'as resizes all tiles to the nearest standard size.']};
   
   % get the current margin help
   msg2 = pushbutton_margins_ButtonDownFcn(h, eventdata, handles, varargin); % get the margin help
   
   fig = bst_message_window('unique',[msg1 {'','Margins Buttons:',''} msg2]);
   
   set(fig,'name','Help Layout Manager')
   bst_layout('align',fig,1,2,2); % right hand column
   
   pushbutton_refresh_Callback(handles.pushbutton_refresh, eventdata, handles, varargin);
   
end

web(fullfile(brainstormHomeDirectory,'Documents','help_gui_layout_manager.htm'));





