function str = callback2string(callback)
; %#ok Undocumented
% Matlab callbacks are passed to us as a function name, a function handle, an
% anonymous function or a cell array.  We only support a restricted form of cell
% arrays that can be displayed in a single line.

%   Copyright 2007-2020 The MathWorks, Inc.

if ischar(callback)
    str = callback;
    return;
end

if isa(callback, 'function_handle')
    str = iFcn2string(callback);
    return;
end

if iscell(callback)
    str = iCell2string(callback);
    return;
end

if isnumeric(callback) && isempty(callback)
    str = '[]';
    return;
end

error(message('parallel:internal:cluster:TypecheckerInvalidCallback', class( callback )));

function str = iFcn2string(callback)
str = func2str(callback);
% Add a @ if the function name isn't an anonymous function which
% already has the @ inserted by func2str
if ~isempty(str) && str(1) ~= '@'
    str = [ '@' str ];
end

function str = iCell2string(callback)
str = '{';
for i = 1:length(callback)
    curr = callback{i};
    
    % Show strings completely
    if ischar(curr) && isrow(curr)
        % Double all the quotes in curr so that quotes in curr are converted into quotes
        % as displayed inside of strings.
        q = '''';
        curr = strrep(curr, q, [q q]);
        str = [str, q, curr, q]; %#ok<AGROW>
    elseif (isnumeric(curr) || islogical(curr)) && isrow(curr) && numel(curr) <= 100
        % Numeric/logical rows until 100 elements will be displayed in the
        % ui
        
        % Use sprintf to get the correct on-screen representation that is
        % independent of the user's format settings.
        currStr = sprintf('%g ', curr);
        if isempty(curr)
            % If the user entered empty values then show []
            str = [str, '[]']; %#ok<AGROW>
        elseif numel(curr) > 1
            % If the user entered an array of values then show [num1 num2 ...]
            str = [str, '[', currStr, ']',  ]; %#ok<AGROW>
        else
            % If the user entered a value then show num1
            str = [str, currStr]; %#ok<AGROW>
        end
    elseif isa(curr, 'function_handle')
        str = [str, iFcn2string(curr)]; %#ok<AGROW>
    else
        % Use getWorkspaceDisplay for the rest
        s = matlab.internal.datatoolsservices.getWorkspaceDisplay({curr});
        str = [str, char(s.Value)]; %#ok<AGROW>
    end
    
    if i < length(callback)
        str = [str, ', ']; %#ok<AGROW>
    end
end
str = [str, '}'];

