Code covered by the BSD License  

Highlights from
MuFFE - figure manager gui

image thumbnail
from MuFFE - figure manager gui by Andres
keep track of your figures and save them easily

muffe(varargin)
function varargout = muffe(varargin)
% MUFFE multiple format figure export gui
% 
% MUFFE is a small gui tool that allows you to easily keep track
% of your open figures and save them to various image files with only
% a few clicks. 
%
% Choose one or more figures in the list of open figures, set your
% preferred output file format(s) by activating the corresponding
% checkboxes, and click the 'Save' button. Or just toggle among your
% figures selecting a figure within the list while the checkbox 'Fetch' is
% active (right click on the list to change its font size).
%
% When you save a single figure, the file name (without extension) will be
% taken from the 'Select File' edit text box. If the text box is empty, or
% if you selected more than one figure in the list, each file name
% (regardless of the file extension) will be queried separately.
%
% Using the Auto-Name checkboxes, MUFFE will generate individual file 
% names for your exported files. Note you can change the order of the part
% strings by the chronology of your clicks or by directly editing the
% position number of the part string.
% The auto-generated file name of the topmost selected figure always
% appears in the 'Select File' edit text box. To view all auto-genererated
% names within the list box, press the 'List Name' togglebutton.
% 
% The use of figure name and/or tag strings in your code is encouraged
% as they will help you to manage your figures.
%
% Several tooltips provide help in using the GUI, and hopefully make it
% self-explaining. The tooltip of the status text box (beside the 'Save'
% button) contains some further status information after a save procedure
% has been finished. 
%
% EXAMPLE:
%
% % create various figures, e.g. in a script
%   figure(1)
%   plot([1 2],[1 2],'b.-')
%   figure(2)
%   plot([2 3],[3 3],'b.-')
%   % ...
%
% % assign figure names to be later used as file names
%   set(1,'Name','Positive Slope')
%   set(2,'Name','Zero Slope')
%   % ...
%
% % change to your preferred save directory
%   cd('c:\mypics')
% % and click the 'CD' button, or use the 'Select Path' button and edit box
%
% % Leave '*.fig' and '*.png' checkboxes checked.
%
% % Activate Auto-Name->Name, select figure numbers, and click 'Save'
% %
% % Your figures will be exported as
% % C:\mypics\Positive Slope.fig
% % C:\mypics\Positive Slope.png
% % C:\mypics\Zero Slope.fig
% % C:\mypics\Zero Slope.png
% % ...
%
% See also: PRINT, SAVEAS, HGSAVE, GETFRAME

% --- Author: -------------------------------------------------------------
%   Copyright 2007-2010 Andres
%   $Revision: 2.16.1 $  $Date: 2010/01/19 21:33:19 $
% --- E-Mail: -------------------------------------------------------------
% x=-2:3;
% disp(char(round([-0.32*x.^5+0.43*x.^4+1.75*x.^3-5.90*x.^2-0.95*x+116,...
%                  -4.44*x.^5+9.12*x.^4+29.8*x.^3-33.6*x.^2-52.9*x+ 98])))
% --- History -------------------------------------------------------------
% 01.47
%    first FEX version
% 01.60
%    allow user defined separator and field order in automatic file name
%    minor style and code changes
% 02.11
%    gui can now resized
%    expandable listbox
%    optional auto-name display in list box
%    selectable font size in list box via uimenu
% 02.12
%    minor fix (re enabling the save button)
% 02.16
%    add some file types, minor rearangements
% 02.16.1
%    fixed a bug with the Save button callback
% --- Wish list -----------------------------------------------------------
%  
% --- Remarks -------------------------------------------------------------
%  If you want to add a new file format checkbox '*.myformat', simply 
%   - add the checkbox to the gui with guide
%   - leave the tag property of the checkbox as it is (at least, it must
%     start with 'checkbox')
%   - copy the code from the other format checkbox callback functions (see
%     'Checkboxes' cell), and
%   - add the appropriate "case '*.myformat'" statements to the switch
%     block in the subfunExportFigureToFiles subfunction, on the analogy of
%     the other "case" statements. 
%   You must only use objects whose tag starts with 'checkbox' for the file
%   format selection. If you add checkboxes for other purposes, rename
%   their tag (e.g. start with 'chk').

% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help muffe

% Last Modified by GUIDE v2.5 22-Jan-2010 12:54:20


% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @muffe_OpeningFcn, ...
                   'gui_OutputFcn',  @muffe_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before muffe is made visible.
function muffe_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to muffe (see VARARGIN)

% Choose default command line output for muffe
handles.output      = hObject;
handles.reso        = 0;                % default bitmap export resolution
handles.ppm         = 'auto';           % default paper position mode
handles.isListNarrow = true;            % default list box appearance
handles.flist       = [];               % initialize figure handle list
handles.hfig        = subfunFindExportableFigureHandles;            % find figures
handles.hcheck      = findobj(hObject,'-regexp','Tag','^checkbox'); % find format checkboxes
handles.has_autosfn = false;            % start without automatic save file names
handles.namePos     = Inf(1,4);         % initialize name part string positions
handles.isNameActive = logical(...      % store part string checkbox values
    [get(handles.chk01_usetext  ,'Value'), ...
     get(handles.chk02_usenumber,'Value'), ...
     get(handles.chk03_usename  ,'Value'), ...
     get(handles.chk04_usetag   ,'Value')]);
set(handles.edit1_path,'String',cd);    % set save path to current directory
% adjustAlignment(handles.edit1_path)   % does not work as expected

% add some two-line tooltip strings 
% 'List Name' toggle button:
set(handles.toggle_listname,'TooltipString', ...
    ['Display Auto-Name in list', char(10), 'Use Refresh button to update']);
% '*.fig (v6)' checkbox:
set(handles.checkbox18,'TooltipString', ...
    ['MATLAB figure with option ''-v6'' (hgsave)', char(10), 'Save to .v6.fig']);
% '*.tif (nc)' checkbox:
set(handles.checkbox19,'TooltipString', ...
    ['No compression TIFF (print)', char(10), 'Save to .nc.tif']);
% '*.png (gf)' checkbox:
set(handles.checkbox20,'TooltipString', ...
    ['Screenshot PNG (getframe)', char(10), 'Save to .gf.png']);
% '*.gif (gf)' checkbox:
set(handles.checkbox21,'TooltipString', ...
    ['Screenshot GIF, 256 colors (getframe)', char(10), 'Save to .gf.gif']);

% Define the list box context menu - display font sizes
hListCmenu = uicontextmenu;
% Define callbacks for context menu items that change font size
hcb1 = 'set(gco, ''FontSize'',  8)';
hcb2 = 'set(gco, ''FontSize'', 10)';
hcb3 = 'set(gco, ''FontSize'', 12)';
% Define the context menu items and install their callbacks
uimenu(hListCmenu, 'Label', 'Font Size  8', 'Callback', hcb1);
uimenu(hListCmenu, 'Label', 'Font Size 10', 'Callback', hcb2);
uimenu(hListCmenu, 'Label', 'Font Size 12', 'Callback', hcb3);
% Attach the context menu to list box
set(handles.listbox2_handles,'uicontextmenu',hListCmenu)

% first list box update
handles = subfunRefresh(hObject, eventdata, handles);

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes muffe wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = muffe_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


%% Checkboxes (file format)

% --- Executes on button press in checkbox09.
function checkbox09_Callback(hObject, eventdata, handles)  %#ok<*DEFNU>
% hObject    handle to checkbox1_fig (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox09
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox10.
function checkbox10_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox11.
function checkbox11_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox12.
function checkbox12_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox13.
function checkbox13_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox14.
function checkbox14_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox15.
function checkbox15_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox16.
function checkbox16_Callback(hObject, eventdata, handles) 
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox18.
function checkbox18_Callback(hObject, eventdata, handles)
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox19.
function checkbox19_Callback(hObject, eventdata, handles)
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox20.
function checkbox20_Callback(hObject, eventdata, handles)
subfunCountFormats(hObject, eventdata, handles);


% --- Executes on button press in checkbox21.
function checkbox21_Callback(hObject, eventdata, handles)
subfunCountFormats(hObject, eventdata, handles);


%%  Checkboxes (other) and Togglebuttons

% --- Executes on button press in chk01_usetext.
function chk01_usetext_Callback(hObject, eventdata, handles) 
handles.lastPosEdited = -1;
handles.isNameActive(1) = logical(get(hObject,'Value'));
handles = subfunSetNamePosOrder(hObject, eventdata, handles);
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes on button press in chk02_usenumber.
function chk02_usenumber_Callback(hObject, eventdata, handles) 
if get(hObject,'Value')
    set(handles.edit5_fieldwidth,'ForeGroundColor','k');
else
    set(handles.edit5_fieldwidth,'ForeGroundColor',[0.5 0.5 0.5]);
end
handles.isNameActive(2) = logical(get(hObject,'Value'));
handles.lastPosEdited = -2;
handles = subfunSetNamePosOrder(hObject, eventdata, handles);
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes on button press in chk03_usename.
function chk03_usename_Callback(hObject, eventdata, handles) 
handles.lastPosEdited = -3;
handles.isNameActive(3) = logical(get(hObject,'Value'));
handles = subfunSetNamePosOrder(hObject, eventdata, handles); 
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes on button press in chk04_usetag.
function chk04_usetag_Callback(hObject, eventdata, handles) 
handles.lastPosEdited = -4;
handles.isNameActive(4) = logical(get(hObject,'Value'));
handles = subfunSetNamePosOrder(hObject, eventdata, handles); 
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes on button press in chk11_overwrite.
function chk11_overwrite_Callback(hObject, eventdata, handles) 
% hObject    handle to chk11_overwrite (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of chk11_overwrite


% --- Executes on button press in chk12_fetch.
function chk12_fetch_Callback(hObject, eventdata, handles) 


% --- Executes on button press in chk13_ppmauto.
function chk13_ppmauto_Callback(hObject, eventdata, handles) 
if get(hObject,'Value')
    handles.ppm  = 'auto';
else
    handles.ppm  = 'manual';
end
guidata(hObject, handles);

% --- Executes on button press in toggle_listname.
function toggle_listname_Callback(hObject, eventdata, handles)
listboxValue = get(handles.listbox2_handles,'Value');
if get(hObject,'Value')
    set(handles.listbox2_handles,'Value',[],'String',handles.listboxAutoname)
else
    set(handles.listbox2_handles,'Value',[],'String',handles.listboxNumbers)
end
set(handles.listbox2_handles,'Value',listboxValue )


%% Edits


function edit1_path_Callback(hObject, eventdata, handles) 
% hObject    handle to edit1_path (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns listcontents of edit1_path as text
%        str2double(get(hObject,'String')) returns listcontents of edit1_path as a double
% adjustAlignment(hObject)  % does not work as expected
set(handles.text11_savestatus,'String','Not saved.')
set(handles.text11_savestatus,'TooltipString','')
set(handles.text11_savestatus,'ForegroundColor','k')


% --- Executes during object creation, after setting all properties.
function edit1_path_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit1_path (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit2_file_Callback(hObject, eventdata, handles) 
handles.has_autosfn = false;
set(handles.text11_savestatus,'String','Not saved.')
set(handles.text11_savestatus,'TooltipString','')
set(handles.text11_savestatus,'ForegroundColor','k')
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit2_file_CreateFcn(hObject, eventdata, handles) 
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit3_reso_Callback(hObject, eventdata, handles) 
e = str2double(get(hObject,'String'));
if isfinite(e) && e>=0
    handles.reso = min(round(e),1048576);
else
    set(hObject,'String',num2str(handles.reso));
end
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit3_reso_CreateFcn(hObject, eventdata, handles) 
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit5_fieldwidth_Callback(hObject, eventdata, handles) 
fw = str2double(get(hObject,'String'));
fw = round(fw);
if isnan(fw)
    fw = 3;
elseif fw < 1
    fw = 1;
elseif fw > 10
    fw = 10;
end
set(hObject,'String',num2str(fw))
handles = subfunUpdatePanel(hObject, eventdata, handles);
if get(handles.chk02_usenumber,'Value')
    handles = subfunSetAutoFilename(hObject, eventdata, handles);
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function edit5_fieldwidth_CreateFcn(hObject, eventdata, handles) 
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit6_prefix_Callback(hObject, eventdata, handles) 
if get(handles.chk01_usetext,'Value')
    handles = subfunSetAutoFilename(hObject, eventdata, handles);
    guidata(hObject, handles);
end

% --- Executes during object creation, after setting all properties.
function edit6_prefix_CreateFcn(hObject, eventdata, handles) 
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit7_AutoNameTextPos_Callback(hObject, eventdata, handles) 
% hObject    handle to edit7_AutoNameTextPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit7_AutoNameTextPos as text
%        str2double(get(hObject,'String')) returns contents of edit7_AutoNameTextPos as a double
handles.lastPosEdited = 1;
handles = subfunSetNamePosOrder(hObject, eventdata, handles);
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit7_AutoNameTextPos_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit7_AutoNameTextPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit8_AutoNameNumberPos_Callback(hObject, eventdata, handles) 
% hObject    handle to edit8_AutoNameNumberPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit8_AutoNameNumberPos as text
%        str2double(get(hObject,'String')) returns contents of edit8_AutoNameNumberPos as a double
handles.lastPosEdited = 2;
handles = subfunSetNamePosOrder(hObject, eventdata, handles); 
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit8_AutoNameNumberPos_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit8_AutoNameNumberPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit9_AutoNameNamePos_Callback(hObject, eventdata, handles) 
% hObject    handle to edit9_AutoNameNamePos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit9_AutoNameNamePos as text
%        str2double(get(hObject,'String')) returns contents of edit9_AutoNameNamePos as a double
handles.lastPosEdited = 3;
handles = subfunSetNamePosOrder(hObject, eventdata, handles); 
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit9_AutoNameNamePos_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit9_AutoNameNamePos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit10_AutoNameTagPos_Callback(hObject, eventdata, handles) 
% hObject    handle to edit10_AutoNameTagPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit10_AutoNameTagPos as text
%        str2double(get(hObject,'String')) returns contents of edit10_AutoNameTagPos as a double
handles.lastPosEdited = 4;
handles = subfunSetNamePosOrder(hObject, eventdata, handles); 
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit10_AutoNameTagPos_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit10_AutoNameTagPos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function edit11_separator_Callback(hObject, eventdata, handles) 
% hObject    handle to edit11_separator (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit11_separator as text
%        str2double(get(hObject,'String')) returns contents of edit11_separator as a double
handles = subfunSetAutoFilename(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edit11_separator_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to edit11_separator (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
set(hObject,'String',' ')


%% Listboxes

% --- Executes on selection change in listbox2_handles.
function listbox2_handles_Callback(hObject, eventdata, handles) 
% hObject    handle to listbox2_handles (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: listcontents = get(hObject,'String') returns listbox2_handles listcontents as cell array
%        listcontents{get(hObject,'Value')} returns selected item from listbox2_handles

if numel(handles.hfig)>=1
    listselectedidc = get(hObject,'Value');

    if isempty(listselectedidc)
        % Clean up if no item is selected
        subfunClearPanel(hObject, eventdata, handles)
    else
        % Update display to 1st selected item (if it is a valid handle)
        hsel = handles.flist(listselectedidc(1));
        if ishandle(hsel)
            handles.hcf = hsel;
            guidata(hObject, handles);
            handles = subfunUpdatePanel(hObject, eventdata, handles);
            set(handles.text11_savestatus,'String','Not saved.')
            set(handles.text11_savestatus,'TooltipString','')
            set(handles.text11_savestatus,'ForegroundColor','k')
            guidata(hObject, handles);
        else
            subfunClearPanel(hObject, eventdata, handles)
        end
    end
end


% --- Executes during object creation, after setting all properties.
function listbox2_handles_CreateFcn(hObject, eventdata, handles) 
% hObject    handle to listbox2_handles (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%% Pushbuttons

% --- Executes on button press in pushbutton1_spath.
function pushbutton1_spath_Callback(hObject, eventdata, handles) 
% hObject    handle to pushbutton1_spath (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
prev_directory_name = get(handles.edit1_path,'String');
directory_name = uigetdir(prev_directory_name); 
if ischar(directory_name) && ~strcmp(prev_directory_name,directory_name);
    set(handles.edit1_path,'String',directory_name)
    set(handles.text11_savestatus,'String','Not saved.')
    set(handles.text11_savestatus,'TooltipString','')
    set(handles.text11_savestatus,'ForegroundColor','k')
end


% --- Executes on button press in pushbutton2_sfile.
function pushbutton2_sfile_Callback(hObject, eventdata, handles) 
subfunFileDialogUpdate(hObject, eventdata, handles);


% --- Executes on button press in pushbutton3_refresh.
function pushbutton3_refresh_Callback(hObject, eventdata, handles) 
handles.hfigOld = handles.hfig;
handles.hfig = subfunFindExportableFigureHandles;
handles = subfunRefresh(hObject, eventdata, handles);
guidata(hObject, handles);


% --- Executes on button press in pushbutton5_save.
function pushbutton5_save_Callback(hObject, eventdata, handles) 
% This function calls 'subfunExportFigureToFiles' consecutively for all selected
% figures. subfunExportFigureToFiles cares about saving a single figure to the
% various selected image file formats.
%
% The variable savec controls the proceeding of the save process. It is
% passed from subfunOverwriteCheck to subfunExportFigureToFiles and to this function.
% savec can be set in different ways:
%  savec is set by subfunOverwriteCheck and checked in subfunExportFigureToFiles
%   before any hgsave/print/imwrite command:
%       2: overwrite file in all given file extension variants
%          (subfunOverwriteCheck's questdlg was answered with 'All Formats')
%       1: overwrite file with specified file extension
%          (questdlg was answered with 'Yes')
%       0: do not overwrite file with specified file extension
%          (questdlg was answered with 'No')
%      -1: do not overwrite file in any given file extension variant
%          (questdlg was closed by [x] in upper right corner)
%  savec can be set by subfunExportFigureToFiles to
%      -1: do not write a file as the save directory does not exist
%  savec can also be set by subfunExportFigureToFiles itself when it has to ask
%   for an individual file name (by uiputfile). subfunExportFigureToFiles is told
%   to do so if handles.do_forceuiput is true (see below). savec is then
%   set to 
%       2: overwrite file in all given file extension variants
%          (uiputfile has assured this is ok)
%      -2: do not save this figure at all, but skip it 
%          (uiputfile was canceled)
%
% In this function, savec==-1 aborts the the whole save process for any
% figure handle, and savec==-2 entails a one-time query whether to continue
% with the remaining figures or to abort the whole save process.

listselectedidc = get(handles.listbox2_handles,'Value');
numselected    	= numel(listselectedidc);
hcf             = handles.hcf;
% Determine whether to ask for an individual file name via uiputfile. This
% becomes necessary if the file name edit text box is empty, or if none of
% the latter three Auto-Name radiobuttons is selected.
handles.do_forceuiput   = isempty(get(handles.edit2_file,'String')) || ...
                  (numselected>1 && ~( ...
                  get(handles.chk02_usenumber,'Value') || ...
                  get(handles.chk03_usename  ,'Value') || ...
                  get(handles.chk04_usetag   ,'Value')    ) );
do_forcecontinue= false;
set(handles.text11_savestatus,'ForegroundColor','k')
appenderrorstring = [char(10) 'No errors.'];    % default tooltip appendix if no error occured.

% check for valid handles
if all(ishandle( handles.flist(listselectedidc) ))    

    num_cbc = subfunCountFormats(hObject, eventdata, handles);

    if numselected >= 1
        totalsavecntr = 0;
        try
            % Step through selected items in list and export them
            for sdx = 1:numselected 
                set(handles.text11_savestatus,'String','Saving...')
                set(handles.listbox2_handles,'Value',listselectedidc(sdx))
                handles.hcf = handles.flist(listselectedidc(sdx));
                handles = subfunUpdatePanel(hObject, eventdata, handles);
                [savecntr, savec, errorinfo] = subfunExportFigureToFiles(hObject, eventdata, handles);
                if errorinfo.has_error
                    appenderrorstring = [char(10) 'Last error: ' char(10) errorinfo.msg];
                    set(handles.text11_savestatus,'ForegroundColor','r')
                end
                totalsavecntr = totalsavecntr + savecntr;
                % Stop saving if user has closed overwrite-dialogue by [x]
                % or tries to write to a nonexisting directory
                if savec == -1
                    break
                % or ask whether to continue if user has canceled a
                % uiputfile dialogue for the first time
                elseif savec == -2 && ~do_forcecontinue && sdx < numselected
                    button = questdlg({'The "Save Image" dialogue has been canceled.'; ...
                        'Do you want to continue anyway?'},'Continue saving?',...
                        'Continue','Cancel all','Continue');
                    if strcmp(button,'Continue')
                        do_forcecontinue = true;
                    else
                        break
                    end
                end
            end
            
            % Display info in savestatus text and its tooltip
            if totalsavecntr == num_cbc*numselected
                set(handles.text11_savestatus,'String','Saved.')
                set(handles.text11_savestatus,'TooltipString',...
                    [num2str(totalsavecntr) '/' num2str(num_cbc*numselected) ' files.' appenderrorstring])
            elseif totalsavecntr == 0
                set(handles.text11_savestatus,'String','Not saved.')
                set(handles.text11_savestatus,'TooltipString',...
                    ['0/' num2str(num_cbc*numselected) ' files.' appenderrorstring])
            elseif totalsavecntr < num_cbc*numselected
                set(handles.text11_savestatus,'String','Partially saved.')
                set(handles.text11_savestatus,'TooltipString',...
                    [num2str(totalsavecntr) '/' num2str(num_cbc*numselected) ' files.' appenderrorstring])
            end
            
        catch   %#ok<CTCH> % catch other errors
            s = lasterror; %#ok<LERR>
            set(handles.text11_savestatus,'String','Error!')
            set(handles.text11_savestatus,'ForegroundColor','r')
            set(handles.text11_savestatus,'TooltipString',s.message)
        end
        
        % Restore the list selection
        set(handles.listbox2_handles,'Value',listselectedidc)
        handles.hcf = hcf;
        handles = subfunUpdatePanel(hObject, eventdata, handles);
    end
    
else
    set(handles.text11_savestatus,'String','Error!')
    set(handles.text11_savestatus,'ForegroundColor','r')
    set(handles.text11_savestatus,'TooltipString',...
        'A non-existing figure number is selected in the list. Please refresh.')
    set(handles.pushbutton5_save,'Enable','off')
end
guidata(hObject, handles);


% --- Executes on button press in pushbutton6_close.
function pushbutton6_close_Callback(hObject, eventdata, handles) 
delete(handles.figure1);


% --- Executes on button press in pushbutton7_cd.
function pushbutton7_cd_Callback(hObject, eventdata, handles) 
set(handles.edit1_path,'String',cd);
% adjustAlignment(handles.edit1_path)   % does not work as expected

% --- Executes on button press in pushbutton_All.
function pushbutton_All_Callback(hObject, eventdata, handles) 
% hObject    handle to pushbutton_All (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.listbox2_handles,'Value',1:numel(get(handles.listbox2_handles,'String')))
subfunUpdatePanel(hObject, eventdata, handles);

% --- Executes on button press in pushbutton_expand.
function pushbutton_expand_Callback(hObject, eventdata, handles) 
% hObject    handle to pushbutton_expand (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.isListNarrow = ~handles.isListNarrow;

if handles.isListNarrow
    set([handles.uipanel_autoname,handles.uipanel_select,handles.uipanel_export],'Visible','on')
    set(handles.listbox2_handles,'Pos',...
        handles.posDefaultListbox   + [0 0 0 1].*(handles.posFigure(4) - handles.posDefault(4)) ...
                                    + [0 0 1 0].*(handles.posFigure(3) - handles.posDefault(3)));
    set(hObject,'String','>>','TooltipString','Expand list');
else
    set([handles.uipanel_autoname,handles.uipanel_select,handles.uipanel_export],'Visible','off')
    set(handles.listbox2_handles,'Pos',...
        handles.posDefaultListboxXp + [0 0 0 1].*(handles.posFigure(4) - handles.posDefault(4)) ...
                                    + [0 0 1 0].*(handles.posFigure(3) - handles.posDefault(3)));
    set(hObject,'String','<<','TooltipString','Narrow list');
end

guidata(hObject, handles);


%% Subfunctions

function [savecntr, savec, errorinfo] = subfunExportFigureToFiles(hObject, eventdata, handles)
% subfunExportFigureToFiles exports a figure to the selected formats. It is
% called by pushbutton5_save
%
% see the commented header lines in 'pushbutton5_save_Callback' for details
% about controlling the save process by the variable savec

savepath = get(handles.edit1_path, 'String');
savefile = get(handles.edit2_file, 'String');
saveffn  = fullfile(savepath, savefile);
savefhst = get(handles.text7_figno, 'String');

listselectedidc = get(handles.listbox2_handles,'Value');
savefigh = handles.flist(listselectedidc);
errorinfo.has_error = false;
errorinfo.msg       = '';

savecntr = 0;       % init., count number of saved files
savec    = 1;       % init., overwrite behaviour

if ~exist(savepath,'dir')
    savec = -1;
    errorinfo.has_error = true;
    errorinfo.msg       = 'Directory does not exist.';
    return 
end

% handles.do_forceuiput tells us if we need uiputfile (wrapped in
% subfunFileDialogUpdate) to determine an individual save file name. If
% uiputfile is canceled then, return to pushbutton5_save without saving.
if handles.do_forceuiput
    isFileSelectionCancelled = subfunFileDialogUpdate(hObject, eventdata, handles);
    if isFileSelectionCancelled
        savec    = -2;
        return
    else
        savepath = get(handles.edit1_path, 'String');
        savefile = get(handles.edit2_file, 'String');
        saveffn  = fullfile(savepath, savefile);
        savec    = 2;
    end
end

hcheck = handles.hcheck;
CheckBoxVals = cell2mat(get(hcheck,'Value'));
cbc = find(CheckBoxVals)';
try
    if ~ishandle(savefigh)  % last check for figure handle
        error('No such figure handle')
    end
    savefppm = get(savefigh,'PaperPositionMode');   % get original PPM
    set(savefigh,'PaperPositionMode',handles.ppm);  % set to desired PPM
    for idx = cbc
        switch get(hcheck(idx),'String');
            % for any file type, construct file name and save depending on
            % overwrite-status <savec>:
            %   case '' (= closed by [x])       savec = -1;
            %   case 'No',                      savec = 0;
            %   case 'Yes' / new file name      savec = 1;  
            %   case 'All Formats',             savec = 2;
            case '*.fig'
                % ==============================
                fffn = [saveffn '.fig'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    hgsave(savefigh,fffn)       % export
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.fig (v6)'
                % ==============================
                fffn = [saveffn '.v6.fig'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    hgsave(savefigh,fffn,'-v6')  % export
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.bmp'
                % ==============================
                fffn = [saveffn '.bmp'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dbmp',['-r' num2str(handles.reso)])
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.eps'
                % ==============================
                fffn = [saveffn '.eps'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-depsc2')
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.emf'
                % ==============================
                fffn = [saveffn '.emf'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dmeta')
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.jpg'
                % ==============================
                fffn = [saveffn '.jpg'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-djpeg',['-r' num2str(handles.reso)])
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.pdf'
                % ==============================
                fffn = [saveffn '.pdf'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dpdf')
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.png'
                % ==============================
                fffn = [saveffn '.png'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dpng',['-r' num2str(handles.reso)])
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.tif'
                % ==============================
                fffn = [saveffn '.tif'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dtiff',['-r' num2str(handles.reso)])
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.tif (nc)'
                % ==============================
                fffn = [saveffn '.nc.tif'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    print(fffn,['-f' savefhst],'-dtiffn',['-r' num2str(handles.reso)])
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.png (gf)'
                % ==============================
                fffn = [saveffn '.gf.png'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    F = getframe(savefigh);
                    imwrite(F.cdata,fffn,'png');
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
            case '*.gif (gf)'
                % ==============================
                fffn = [saveffn '.gf.gif'];
                savec = subfunOverwriteCheck(fffn,savec, handles);
                if savec > 0
                    F = getframe(savefigh);
                    [X,map] = rgb2ind(F.cdata, 256);
                    imwrite(X,map,fffn,'gif');
                    savecntr = savecntr + 1;
                elseif savec < 0
                    set(savefigh,'PaperPositionMode',savefppm);
                    return;
                end
                % ==============================
        end
    end
catch %#ok<CTCH>
    s = lasterror; %#ok<LERR>
    msg = s.message;
    % convert char array msg to a row vector containing line breaks
    msg = [msg, repmat(char(10),size(msg,1),1)];
    msg = msg(:)';
    msg = [s.identifier, char(10), msg(1:end-1)];
    errorinfo.has_error = true;
    errorinfo.msg       = msg;
end
if ishandle(savefigh)
    set(savefigh,'PaperPositionMode',savefppm); % set to original PPM
end


function savec = subfunOverwriteCheck(ffn, prevsavec, handles)
% Find out what to do if an existing file may be overwritten

% see the commented header lines in 'pushbutton5_save_Callback' for details
% about controlling the save process by the variable savec

if prevsavec == 2 || get(handles.chk11_overwrite,'Value')
    savec = 2;
    return
end

if exist(ffn,'file')
    [pname, fname, fext] = fileparts(ffn);

    button =  questdlg({'File';[fname fext];...
              'already exists. Do you want to replace it?'},...
              'Replace file?','Yes','All Formats','No','No');
    switch button
        case ''
            savec = -1;
        case 'No'
            savec = 0;
        case 'Yes'
            savec = 1;
        case 'All Formats'
            savec = 2;
    end
else
    savec = 1;
end


function isFileSelectionCancelled = subfunFileDialogUpdate(hObject, eventdata, handles)
% Call uiputfile to get file and path name for the edit text boxes
savepath = get(handles.edit1_path, 'String');
savefile = get(handles.edit2_file, 'String');

[FileName,PathName] = ...
          uiputfile({'*.fig;*.bmp;*.eps;*.emf;*.jpg;*.pdf;*.tif;*.png;*.gif', ...
          'All Image Files';'*.*','All Files' }, ...
          'Save image file (extension will be set automatically)', ...
          fullfile(savepath,savefile));
      
if ischar(FileName)
    isFileSelectionCancelled = 0;
    [d, fname] = fileparts(FileName);
    set(handles.edit1_path, 'String',PathName);
    set(handles.edit2_file, 'String',fname);
    if ~strcmp(get(handles.text11_savestatus,'String'),'Saving...')
        set(handles.text11_savestatus,'String','Not saved.')
        set(handles.text11_savestatus,'ForegroundColor','k')
        set(handles.text11_savestatus,'TooltipString','')
    end
else % no file was selected
    isFileSelectionCancelled = 1;
end


function handles = subfunUpdatePanel(hObject, eventdata, handles)
% Update panel strings to current list box selection
if ishandle(handles.hcf)
    fwstr   = get(handles.edit5_fieldwidth,'String');
    set(handles.text7_figno,'String',sprintf(['%0' fwstr 'd'],handles.hcf))
    set(handles.text8_figname,'String',get(handles.hcf,'Name'))
    set(handles.text9_figtag,'String',get(handles.hcf,'Tag'))
    handles = subfunSetAutoFilename(hObject, eventdata, handles);
    subfunCountFormats(hObject, eventdata, handles);
    if get(handles.chk12_fetch,'Value')
        figure(handles.hcf)
    end
else
    subfunClearPanel(hObject, eventdata, handles)
end


function subfunClearPanel(hObject, eventdata, handles)
% Clear panel if no list box item is selected
set(handles.text7_figno,'String','')    
set(handles.text8_figname,'String','')	
set(handles.text9_figtag,'String','') 	
set(handles.pushbutton5_save,'Enable','off')
set(handles.text11_savestatus,'String','Not saved.')
set(handles.text11_savestatus,'ForegroundColor','k')
set(handles.text11_savestatus,'TooltipString','')
% clear filename only if it was auto-generated:
if handles.has_autosfn
    set(handles.edit2_file,'String','')
end


function handles = subfunRefresh(hObject, eventdata, handles)
% Update displays

% handles.hfig      : currently detected figure handles
% handles.hcf       : handle of figure to display in panels
% handles.flist     : sorted figure handles as appearing in listbox
if numel(handles.hfig)>0
    % find out previously selected figure handles to keep them selected
    listboxValueOld = get(handles.listbox2_handles,'Value');
    hfigOldSelected = handles.flist(listboxValueOld);
    % sorted existing figure handles
    handles.flist = sort(handles.hfig);  
    % get indices of existing figures that were selected before
    [idcSelect,idcSelect] = intersect(handles.flist,hfigOldSelected);
    % alternative listbox strings
    handles.listboxNumbers  = cellstr(num2str(handles.flist));
    %- handles.listboxAutoname
    handles.listboxAutoname = subfunGenAutoFilenameList(hObject, eventdata, handles,handles.flist);
    % determine selected items
    if numel(idcSelect)>0   % preserve selection
        if ~ismember(handles.hcf,handles.flist)
            handles.hcf = handles.flist(idcSelect(end));
        end
    else                    % select current figure
        handles.hcf = handles.hfig(1);
    end
    % update panel
    handles = subfunUpdatePanel(hObject, eventdata, handles);
else % no figures
    idcSelect = [];
    handles.hcf = NaN;
    set(handles.listbox2_handles,'Value',[])
    handles.listboxAutoname = {};
    handles.listboxNumbers  = {};
    subfunClearPanel(hObject, eventdata, handles)
end
set(handles.text11_savestatus,'String','Not saved.')
set(handles.text11_savestatus,'ForegroundColor','k')
set(handles.text11_savestatus,'TooltipString','')
% update list box
if get(handles.toggle_listname,'Value')
    set(handles.listbox2_handles,'Value',[],'String',handles.listboxAutoname)
else
    set(handles.listbox2_handles,'Value',[],'String',handles.listboxNumbers)
end
set(handles.listbox2_handles,'Value',idcSelect)



function hfi = subfunFindExportableFigureHandles
% Return all integer figure handles
hfi = findobj('Type','figure');
is_integer = ( mod(hfi,1) == 0 );
hfi = hfi(is_integer);


function num_cbc = subfunCountFormats(hObject, eventdata, handles)
% Count checked file format checkboxes
hcheck = handles.hcheck;
CheckBoxVals = cell2mat(get(hcheck,'Value'));
num_cbc = numel(find(CheckBoxVals)');  
if num_cbc>0 && numel(get(handles.listbox2_handles,'Value'))>0   
    set(handles.pushbutton5_save,'Enable','on')
else
    set(handles.pushbutton5_save,'Enable','off')
end


function handles = subfunSetNamePosOrder(hObject, eventdata, handles)
% Update automatic file name position numbers

editTags         = {'edit7_AutoNameTextPos', ...
                    'edit8_AutoNameNumberPos', ...
                    'edit9_AutoNameNamePos', ...
                    'edit10_AutoNameTagPos'};

lastPosEdited = abs(handles.lastPosEdited);
previousPos   = handles.namePos(lastPosEdited);

if handles.lastPosEdited < 0;
    % a radio button has been toggled
    if ~handles.isNameActive(lastPosEdited)
        % it has been toggled off
        handles.namePos(lastPosEdited) = Inf;
        set(handles.(editTags{lastPosEdited}),'String','', ...
            'ForeGroundColor',[0.5 0.5 0.5]);
    else
        set(handles.(editTags{lastPosEdited}), ...
            'ForeGroundColor','k');
    end
    
else
    % a position number has been edited
    newPosString = get(handles.(editTags{lastPosEdited}),'String');
    newPosNum = str2double(newPosString);
    if ~isfinite(newPosNum)
        newPosNum = Inf;
    end
    handles.namePos(lastPosEdited) = newPosNum;
end

% indicate whether the position number was increased or decreased
diffSign = sign(handles.namePos(lastPosEdited)-previousPos);

% sort position numbers of active fields, treat the edited number according
% to diffSign
numActive     = sum(handles.isNameActive);
sortbias      = zeros(1,numel(handles.isNameActive));
sortbias(lastPosEdited) = 4*diffSign*eps;

[si,si]       = sort(handles.namePos(handles.isNameActive) + ...
                     sortbias(handles.isNameActive));
posActive     = 1:numActive;
posActive(si) = posActive;

% change position values of active fields to consecutive integers
handles.namePos(handles.isNameActive) = posActive;

% update edit fields correspondingly
for k = find(handles.isNameActive)
        set(handles.(editTags{k}),'String', ...
            num2str(handles.namePos(k)));
end


function handles = subfunSetAutoFilename(hObject, eventdata, handles)
% Display automatic file name in edit text box

if numel(get(handles.listbox2_handles,'Value'))>0
    autostr = subfunGenAutoFilename(hObject, eventdata, handles, handles.hcf);
else
    autostr = '';
end

if isempty(autostr)
    handles.has_autosfn = false;
else
    set(handles.edit2_file,'String',autostr)
    handles.has_autosfn = true;
end


function autostr = subfunGenAutoFilename(hObject, eventdata, handles, fighandle)
% Generate automatic file name for a given figure handle

partstr{1} = get(handles.edit6_prefix,'String');        % text
    fwstr  = get(handles.edit5_fieldwidth,'String');    % number field width
partstr{2} = sprintf(['%0' fwstr 'd'],fighandle);       % figure number
partstr{3} = get(fighandle,'Name');                     % figure name
partstr{4} = get(fighandle,'Tag');                      % figure tag
separator  = get(handles.edit11_separator,'String');    % separator

% get active auto-name positions
idcActive  = find(handles.isNameActive);
[activePos,activePos]  = sort(handles.namePos(idcActive));

autostr    = '';    % default/initialization

% compose name
if ~isempty(idcActive) && ~all(cellfun(@isempty, partstr(idcActive)))
        for k = idcActive(activePos)
            autostr = [autostr, partstr{k}]; %#ok<AGROW>
            if k ~= idcActive(activePos(end)) && ~isempty(partstr{k})
                autostr = [autostr, separator]; %#ok<AGROW>
            end
        end
end


function listboxAutoname = subfunGenAutoFilenameList(hObject, eventdata, handles,fighandlelist)
% Generate a cell array of automatic file names for the listbox

numFigh = numel(fighandlelist);
listboxAutoname = repmat({''},numFigh,1);

for idx = 1:numFigh
    listboxAutoname{idx} = subfunGenAutoFilename(hObject, ...
        eventdata, handles, fighandlelist(idx));
    % prepend figure number if it is not appearing within the generated
    % name:
    if ~get(handles.chk02_usenumber,'Value')
        listboxAutoname{idx} = [handles.listboxNumbers{idx}, ': ', ...
            listboxAutoname{idx}];
    end
end

% % does not work as expected as strings whose extent exceeds their edit
% % box width *always* appear left aligned  :-(
% function adjustAlignment(h)
% % Adjust horizontal alignment in edit boxes depending on string extent
% 
% extent = get(h,'Extent');
% position = get(h,'Position');
% if extent(3) <= position(3);
%     set(h,'HorizontalAlignment','left')
% else
%     set(h,'HorizontalAlignment','right')
% end


%% Resize Function

% --- Executes when figure1 is resized.
function figure1_ResizeFcn(hObject, eventdata, handles) 
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isfield(handles,'posDefault')
    posResize = get(hObject,'Pos');
    posNew    = posResize;
    % guarantee minimum figure size
    if any(posResize([3,4])<handles.posDefault([3,4]))
        if posResize(4)<handles.posDefault(4)
            % preserve figure's top edge position on screen
            posNew(2) = posResize(2)+posResize(4)-handles.posDefault(4);
        end
        posNew([3,4]) = max(posResize([3,4]),handles.posDefault([3,4]));
        set(hObject,'Pos',posNew)
    end
    handles.posFigure = posNew;
    
    % adjust some object's position property ...
    % ... Listbox height and width
    if handles.isListNarrow
        set(handles.listbox2_handles,'Pos',...
            handles.posDefaultListbox   + [0 0 0 1].*(posNew(4) - handles.posDefault(4)) ...
                                        + [0 0 1 0].*(posNew(3) - handles.posDefault(3)));
    else
        set(handles.listbox2_handles,'Pos',...
            handles.posDefaultListboxXp + [0 0 0 1].*(posNew(4) - handles.posDefault(4)) ...
                                        + [0 0 1 0].*(posNew(3) - handles.posDefault(3)));
    end
    % ... EditPath width
    set(handles.edit1_path,'Pos',...
        handles.posDefaultEditPath + [0 0 1 0].*(posNew(3) - handles.posDefault(3)));
    % ... EditFile width
    set(handles.edit2_file,'Pos',...
        handles.posDefaultEditFile + [0 0 1 0].*(posNew(3) - handles.posDefault(3)));
    % ... CloseButton x-position
    set(handles.pushbutton6_close,'Pos',...
        handles.posDefaultCloseBut + [1 0 0 0].*(posNew(3) - handles.posDefault(3)));
    % ... ExportPanel x-position
    set(handles.uipanel_select,'Pos',...
        handles.posDefaultExport   + [1 0 0 0].*(posNew(3) - handles.posDefault(3)));
    % ... SelectPanel x-position
    set(handles.uipanel_export,'Pos',...
        handles.posDefaultSelect   + [1 0 0 0].*(posNew(3) - handles.posDefault(3)));
    % ... AutonamePanel x-position
    set(handles.uipanel_autoname,'Pos',...
        handles.posDefaultAutoName + [1 0 0 0].*(posNew(3) - handles.posDefault(3)));

else % get defaults during first call
    handles.posDefault              = get(hObject,'Pos');
    handles.posFigure               = handles.posDefault;
    handles.posDefaultListbox       = get(handles.listbox2_handles,'Pos');
    handles.posDefaultListboxXp     = handles.posDefaultListbox;
    handles.posDefaultListboxXp(3)  = handles.posDefault(3)-handles.posDefaultListbox(1)-7;
    handles.posDefaultEditPath      = get(handles.edit1_path,'Pos');
    handles.posDefaultEditFile      = get(handles.edit2_file,'Pos');
    handles.posDefaultCloseBut      = get(handles.pushbutton6_close,'Pos');
    handles.posDefaultExport        = get(handles.uipanel_select,'Pos');
    handles.posDefaultSelect        = get(handles.uipanel_export,'Pos');
    handles.posDefaultAutoName      = get(handles.uipanel_autoname,'Pos');
end
% adjustAlignment(handles.edit1_path) % does not work as expected

guidata(hObject, handles);

Contact us at files@mathworks.com