function pass = passcode
%PASSCODE  password input dialog box.
%  passcode creates a modal dialog box that returns user password input.
%  Given characters are substituted with '*'-Signs like in usual password dialogs.
%
%  usage:
%  password = PASSCODE
%
% Adapted from https://www.mathworks.com/matlabcentral/fileexchange/6590-passcode
% Version: v1.2 (03-Mar-2008)
% Author:  Elmar Tarajan [MCommander@gmx.de]


ScreenSize = get(0,'ScreenSize');
hfig = figure('Menubar','none', ...
    'Units','Pixels', ...
    'Resize','off', ...
    'NumberTitle','off', ...
    'Name',['Enter openBIS password'], ...
    'Position',[ (ScreenSize(3:4)-[300 75])/2 300 75], ...
    'Color',[0.8 0.8 0.8], ...
    'WindowStyle','modal');
hedit = uicontrol('Parent',hfig, ...
    'Style','Edit', ...
    'Enable','inactive', ...
    'Units','Pixels','Position',[49 28 202 22], ...
    'FontSize',15, ...
    'String',[], ...
    'BackGroundColor',[0.7 0.7 0.7]);
hpass = uicontrol('Parent',hfig, ...
    'Style','Text', ...
    'Tag','password', ...
    'Units','Pixels','Position',[51 30 198 18], ...
    'FontSize',15, ...
    'BackGroundColor',[1 1 1]);
hwarn = uicontrol('Parent',hfig, ...
    'Style','Text', ...
    'Tag','error', ...
    'Units','Pixels','Position',[50 2 200 20], ...
    'FontSize',8, ...
    'String','character not allowed',...
    'Visible','off',...
    'ForeGroundColor',[1 0 0], ...
    'BackGroundColor',[0.8 0.8 0.8]);

set(hfig,'KeyPressFcn',{@keypress_Callback,hedit,hpass,hwarn}, ...
    'CloseRequestFcn','uiresume')

uiwait
pass = get(hpass,'userdata');
delete(hfig)


function keypress_Callback(~,data,~,hpass,~)

pass = get(hpass,'userdata');

switch data.Key
    case 'backspace'
        pass = pass(1:end-1);
    case 'return'
        uiresume
        return
    otherwise
        try
            pass = [pass data.Character];
        catch
            disp('Some error occured during password entry!')
        end
end

set(hpass,'userdata',pass)
set(hpass,'String',char('*'*sign(pass)))

