// Based on scilab-5.4.1\modules\gui\demos\uicontrol.dem.sce
// Copyright (C) ????-2008 - INRIA
// Copyright (C) 2009 - DIGITEO - Vincent COUVERT
// Modified by baptiste.jammet@cea.fr - 2014

// x_multi_choose try to be a drop-in replacement for x_choose
// with the possibility to choose several items

// This file is released under the 3-clause BSD license. See COPYING-BSD.

// TODO : Add a "select all" button

function indices = ret_selected_ind()
    listbox_handle = findobj("Tag","ze_listbox");
    indices = get(listbox_handle, "Value");
    delete(findobj("Tag", "uicontrols_list"));
endfunction

function indices = cancel()
    indices = 0 ;
    delete(findobj("Tag", "uicontrols_list"));
endfunction

function indices = x_multi_choose(liste_in, varargin)
    clear indices
    if argn(2)>1 then
        WinTitle = string(varargin(1)) ;
    else
        WinTitle = 'Multi-choices list' ;
    end
    // Set window size
    largR = 200 ;
    hautR = 300 ;
    if (getos() == "Windows") then
        // Get screen resolution (windows only)
        hres = getsystemmetrics('SM_CXSCREEN') ;
        vres = getsystemmetrics('SM_CYSCREEN') ;
        // Set figure position
        xorig = hres/2 - largR/2 ;
        yorig = vres/2 - hautR/2 ;
        clear hres vres ;
    else // What a hack on non-Windows !
        xorig = 200 ; //maybe -1
        yorig = 100 ; //maybe -1
    end
    
    // Create a figure
    f = figure("Figure_name", WinTitle,...
    "Position",[xorig yorig largR hautR],...
    "BackgroundColor",[0.9 0.9 0.9],...
    "Tag", "uicontrols_list");

    // Remove Scilab 'standard' menus
    delmenu(f.figure_id, gettext("&File"));
    delmenu(f.figure_id, gettext("&Tools"));
    delmenu(f.figure_id, gettext("&Edit"));
    delmenu(f.figure_id, gettext("&?"));

    // Disable graphics toolbar
    toolbar(f.figure_id, "off");

    // Listbox used to display list
    thelistbox = uicontrol(f, "Position", [0 30 largR hautR-15], ...
    "Style", "listbox", ...
    "FontSize", 12, ...
    "String",  liste_in, ...
    "BackgroundColor", [1 1 1], ...
    "Max", 50, ... //if Max>1 then allowed multiple selection
    "Tag", "ze_listbox");

    // Button OK
    disp_OK_button = uicontrol(f, "Position", [0 5 50 20], ...
    "Style", "pushbutton", ...
    "FontSize", 11, ...
    "String", "OK", ...
    "callback", "indices = ret_selected_ind()");

    // Button Cancel
    disp_Annul_button = uicontrol(f, "Position", [130 5 70 20], ...
    "Style", "pushbutton", ...
    "FontSize", 11, ...
    "String", "Cancel", ...
    "callback", "indices = cancel()");

// uiwait is NOT documented, I can't use it !
//uiwait(thelistbox) ;
// Workaround :
while ~exists('indices')
    sleep(500) ;
end


endfunction
