-
Notifications
You must be signed in to change notification settings - Fork 2
/
inputsdlg.m
3199 lines (2826 loc) · 118 KB
/
inputsdlg.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function [Answer,Canceled] = inputsdlg(Prompt, Title, Formats, DefAns, Options)
%INPUTSDLG Enhanced input dialog box supporting multiple data types
% ANSWER = INPUTSDLG(PROMPT) creates a modal dialog box that returns user
% input for multiple prompts in the cell array ANSWER. PROMPT is a 1-D
% cell array containing the PROMPT strings.
%
% Alternatively, PROMPT can have up to 4 columns. The first column
% sppecifies the prompt string. The second column to specify the struct
% field names to output ANSWER as a structure. The third column specifies
% units (i.e., post-fix labels to the right of controls) to display. The
% fourth column specifies the tooltip string. The tooltip string is ignored
% for text type.
%
% INPUTSDLG uses UIWAIT to suspend execution until the user responds.
%
% ANSWER = INPUTSDLG(PROMPT,NAME) specifies the title for the dialog.
%
% Note that INPUTSDLG(PROMPT) & INPUTSDLG(PROMPT,NAME) are similar to the
% standard INPUTDLG function, except for the dialog layout.
%
% ANSWER = INPUTSDLG(PROMPT,NAME,FORMATS) can be used to specify the type
% of parameters to display with FORMATS matrix of structures. The dimension
% of FORMATS defines how PROMPT items are laid out in the dialog box. For
% example, if PROMPT has 6 elements and the size of FORMATS is 2x3 then,
% the items are shown in 2 rows, 3 columns format. The items in PROMPT
% correspond to a horizontal traversal of FORMATS.
%
% The fields in FORMATS structure are:
%
% type - Type of control ['check',{'edit'},'list','range','text',
% 'color','table','button','none']
% style - UI control type used. One of:
% {'checkbox'}, for 'check' type
% {'edit'} for 'edit' type
% {'listbox','popupmenu','radiobutton','togglebutton'}
% for 'list' type
% {'slider'} for 'range' type
% {'text'} for 'text' type
% {'edit'} for 'color' type
% {'pushbutton'} for 'button' and 'color' types
% {'table'} for 'table' type
% format - Data format: ['text','date','float','integer','logical',
% 'vector','file','dir']
% limits - [min max] (see below for details)
% required - 'on' - control must have an answer
% {'off'} - control may return empty answer
% items - Type 'edit', Format 'file': File flter spec
% Type 'list': Selection items (cell of strings)
% Type 'table': Names of columns (cell of strings)
% Type 'range': Slider step size spec [minor major]
% size - [width height] in pixels. Set to <=0 to auto-size.
% enable - Defines how to respond to mouse button clicks, including which
% callback routines execute. One of:
% {'on'} - UI control is operational.
% 'inactive' ?UI control is not operational, but looks the
% same as when Enable is on.
% 'off' ?UI uicontrol is not operational and its image
% is grayed out.
% margin - A scalar or 2-element vector specifying the margin between control
% and its labels in pixels.
% labelloc - Prompt label location:
% {'lefttop'} - left of control, aligned to top
% 'leftmiddle' - left of control, aligned to middle
% 'leftbottom' - left of control, aligned to bottom
% 'topleft' - above control, aligned left
% 'topcenter' - above control, aligned center
% 'topright' - above control, aligned right
% unitsloc - Units label location:
% {'righttop'} - right of control, aligned to top
% 'rightmiddle' - right of control, aligned to middle
% 'rightbottom' - right of control, aligned to bottom
% 'bottomleft' - below control, aligned left
% 'bottomcenter' - below control, aligned center
% 'bottomright' - below control, aligned right
% callback - Defines callback funcion, a routine that executes whenever
% you activate the uicontrol object. For the controls with
% separate dialog, their callback functions are executed after
% the dialog is closed. The callback function must be given as
% a function handle with following syntax:
%
% my_callbackfcn(hobj,evt,handles,k)
%
% where hobj and evt are the passed-through standard MATLAB
% callback arguments, handles is a Nx3 array of dialog
% objects. Here, the n-th row corresponds to the n-th PROMPT,
% and handles(n,1) is the calling object handle (i.e., same as
% hobj). handles(n,2) are the prompt texts and handles(n,3)
% are the prompt unit texts.
%
% For example, Formats(n,m).callback.ButtonDownFcn sets the
% the button-press callback function.
% span - Defines size of objects in fields [rows columns]
%
% A missing field (either missing from FORMATS struct or the field value is
% left empty for an element) will be filled with a default field value.
%
% FORMATS type field defines what type of prompt item to be shown.
%
% type Description
% -------------------------------------------------------------------
% edit Standard edit box (single or multi-line mode)
% check Check box for boolean item
% list Chose from a list of items ('listbox' style allows multiple item
% selection)
% range Use slider to chose a value over a range
% text Static text (e.g., for instructions)
% color Color selection using 'uisetcolor'
% button Execute function defined in 'callback'
% table Uitable
% none A placeholder. May be used for its neighboring item to extend
% over multiple columns or rows (i.e., "to merge cells")
%
% The allowed data format depends on the type of the field:
%
% type allowed format
% --------------------------------------------
% check {logical}, integer, text
% edit {text}, date, float, integer, file, dir, vector
% list {integer}, text
% range {float}
% color {float}, integer
% table (a cell string to specify ColumnFormat of uiTable)
% button any data format allowed
%
% Formats 'file' and 'dir' for 'edit' type uses the standard UIGETFILE,
% UIPUTFILE, and UIGETDIR functions to retrieve a file or directory name.
%
% The role of limits field varies depending on other parameters:
%
% style role of limits
% ---------------------------------------------------
% checkbox If data format is integer, limits(1) is the ANSWER value
% if the check box is not selected box is not selected and
% limits(2) is the ANSWER if the check box is selected. If
% data format is text, its limits field must be given as a
% cellstring array.
% edit:text
% If diff(limits)>0, text aligns with the prompt label. If
% diff(limits)<0, tet aligns with the control.
% edit::date
% limits must be a free-format date format string or a
% scalar value specifying the date format. Supported format
% numbers are: 0,1,2,6,13,14,15,16,23. The default date
% format is 2 ('mm/dd/yy'). See the tables in DATESTR help
% for the format definitions. As long as the user entry is
% a valid date/time expression, the dialog box
% automatically converts to the assigned format.
% edit::float, edit::integer
% This style defines the range of allowed values if numeric
% vector is given, including the values specified. For
% other cases, use cell array to customize its
% validateattribute call. For example, {'positive','<',1}
% to specify value between 0 and 1, excluding 0 & 1.
% edit::vector
% limits specifies the allowed number of elements in a
% vector. Use cell array to customize its validateattribute
% call if vector length is fixed or completely arbitrary.
% Note that 'column' attribute is always forced unless
% 'row' attribute is explicitly specified.
% edit::file
% If 0<diff(limits)<=1 uses UIGETFILE in single select
% mode with single-line edit. If diff(limits)>1 uses
% UIGETFILE in multi-select mode with multi-line edit. If
% diff(limits)<=0 usees UIPUTFILE with single-line edit
% list::listbox If diff(limits)>1, multiple items can be selected. If
% auto-height and limits(1)>0, at most limits(1) lines will
% be shown.
% slider limits(1) defines the smallest value while
% limits(2) defines the largest value
% color 'float' format limit must be [0 1] and 'integer' format
% limit must be [0 255]. If not, the behavior is not
% determined.
% table cell array defining ColumnWidths
% none If diff(limits)==0 space is left empty (default)
% If diff(limits)>0 : lets the item from left to extend
% If diff(limits)<0 : lets the item from above to extend
% NOTE: Use 'span' field of a control to automatically set
% the extension mode.
%
% Similar to how PROMPT strings are laid out, when FORMATS.style is set to
% either 'radiobutton' or 'togglebutton', FORMATS.items are laid out
% according to the dimension of FORMATS.items.
%
% There are two quick format options as well:
%
% Quick Format Option 1 (mimicing INPUTDLG behavior):
% FORMATS can specify the number of lines for each edit-type prompt in
% FORMATS. FORMATS may be a constant value or a column vector having
% one element per PROMPT that specifies how many lines per input field.
% FORMATS may also be a matrix where the first column specifies how
% many rows for the input field and the second column specifies how
% many columns wide the input field should be.
%
% Quick Format Option 2:
% FORMATS can specify the types of controls and use their default
% configurations. This option, however, cannot be used to specify
% 'list' control as its items are not specified. To use this option,
% provide a string (if only 1 control) or a cell array of strings. If
% a cell array is given, its dimension is used for the dialog
% layout.
%
% ANSWER = INPUTSDLG(PROMPT,NAME,FORMATS,DEFAULTANSWER) specifies the
% default answer to display for each PROMPT. For a non-tiled layout,
% DEFAULTANSWER must contain the same number of elements as PROMPT (that
% are not of 'none' style). If PROMPT does not provide ANSWER structure
% fields, DEFAULTANSWER should be a cell array with element type
% corresponding to FORMATS.format. Leave the cell element empty for a
% prompt with 'text' type. If ANSWER is a structure, DEFAULTANSWER must be
% a struct with the specified fields. (If additional fields are present in
% DEFAULTANSWER, they will be returned as parts of ANSWER.)
%
% For edit::file controls, a default answer that does not correspond to an
% existing file will be used as a default path and/or file name in the
% browse window. It is passed as the DefaultName parameter to UIGETFILE or
% UIPUTFILE.
%
% To enable Tiled Mode, FORMATS must be given as a vector and DEFAULTANSWER
% must be given as a cell matrix or a struct vector. If FORMATS is a row
% vector, the dialog controls are tiled vertically; conversely if it is a
% column vector, the controls are tiled horizontally. If DEFAULTANSWER is
% given as a cell matrix, the number of rows of DEFAULTANSWER must match
% the number of elements of PROMPT. Each column of DEFAULTANSWER forms a
% tile row/column. If DEFAULTANSWER is given as a struct vector, each
% struct element forms a tile row/column.
%
% Empty rows and empty columns are automatically eliminated by default. To
% add an empty row or column, set the FORMATS entry of one of its cells to
% type = 'none' with its size = [H W] or [-Hmin -Wmin] specified to the
% desired width and height.
%
% ANSWER = INPUTSDLG(PROMPT,NAME,FORMATS,DEFAULTANSWER,OPTIONS) specifies
% additional options. If OPTIONS is the string 'on', the dialog is made
% resizable. If OPTIONS is a structure, the fields recognized are:
%
% Option Field Description {} indicates the default value
% ----------------------------------------------------------------------
% Resize Make dialog resizable: 'on' | {'off'}
% WindowStyle Sets dialog window style: {'normal'} | 'modal'
% Interpreter Label text interpreter: 'latex' | {'tex'} | 'none'
% CancelButton Show Cancel button: {'on'} | 'off'
% ApplyButton Adds Apply button: 'on' | {'off'}
% Sep Space b/w prompts in pixels: {10}
% ButtonNames Customize OK|Cancel|Apply button names: {up to 3 elements}
% AlignControls Align adjacent controls in the same column: 'on' | {'off'}
% FontSize Customize font size. Default: get(0,'DefaultUicontrolFontSize')
% CreateFcn Callback function executed right after dialog creation
% with syntax my_createfcn(hobj,evt,handles) with
% standard MATLAB callback arguments, hobj & evt, and Nx3
% array of handles. Here, the n-th row corresponds to the
% n-th PROMPT, and handles(n,1) is the calling object handle
% (i.e., same as hobj). handles(n,2) are the prompt texts
% and handles(n,3) are the prompt unit texts.
% DeleteFcn Callback function executed just before deleting dialog.
% The function syntax is the same as CreateFcn.
%
% [ANSWER,CANCELED] = INPUTSDLG(...) returns CANCELED = TRUE if user
% pressed Cancel button, closed the dialog, or pressed ESC. In such event,
% the content of ANSWER is set to the default values.
%
% Note on Apply Button feature. Pressing the Apply button makes the current
% change permanent. That is, pressing Cancel button after pressing Apply
% button only reverts ANSWER back to the states when the Apply button was
% pressed last. Also, if user pressed Apply button, CANCELED flag will not
% be set even if user canceled out of the dialog box.
%
% Examples:
%
% prompt={'Enter the matrix size for x^2:';'Enter the colormap name:'};
% name='Input for Peaks function';
% formats(1) = struct('type','edit','format','integer','limits',[1 inf]);
% formats(2) = struct('type','edit','format','text','limits',[0 1]);
% defaultanswer={20,'hsv'};
%
% [answer,canceled] = inputsdlg(prompt,name,formats,defaultanswer);
%
% formats(2).size = -1; % auto-expand width and auto-set height
% options.Resize='on';
% options.WindowStyle='normal';
% options.Interpreter='tex';
%
% answer = inputsdlg(prompt,name,formats,defaultanswer,options);
%
% prompt(:,2) = {'Ndim';'Cmap'};
% defaultanswer = struct(defaultanswer,prompt(:,2),1);
%
% answer = inputsdlg(prompt,name,formats,defaultanswer,options);
%
% See also INPUTDLG, DIALOG, ERRORDLG, HELPDLG, LISTDLG, MSGBOX,
% QUESTDLG, UIGETFILE, UIPUTFILE, UIGETDIR, DATESTR, VALIDATEATTRIBUTE.
% Version 2.2.0 (June 25, 2015)
% Written by: Takeshi Ikuma
% Contributors: Andreas Greuer, Luke Reisner, Florian Hatz
% Created: Nov. 16, 2009
% Revision History:
% v.1.1 (Nov. 19, 2009)
% * Fixed bugs (reported by AG):
% - not returning Canceled output
% - erroneous struct output behavior
% - error if all row elements of a column are auto-expandable
% * Added Apply button option
% * Added support for Units (label to the right of controls)
% * Updated the help text
% v.1.11 (Nov. 20, 2009)
% * Fixed bugs (reported by AG):
% - incorrect Canceled output when Cancel button is pressed
% v.1.12 (Nov. 20, 2009)
% * Fixed bugs (reported by AG):
% - again incorrect Canceled output behavior
% v.1.2 (May 20, 2010)
% * Fixed bugs (reported by AG & Jason):
% - Apply button->Canel button does not revert back to post-apply answers.
% - Line 265 handles.Figure -> handles.fig
% * Added edit::date support
% * Added formats.enable support
% * Added options.CancelButton support
% * Added options.ButtonNames support
% v.1.2.1 (June 11, 2010)
% * Fixed default option bug (reported by Jason)
% v.1.2.2 (July 15, 2010)
% * Rewritten checkoptions() (to correct issues reported by Jason)
% * Bug Fix: file & dir control enable config were interpreted backwards
% v.1.2.3 (July 19, 2010)
% * checkoptions() bug fix (to correct issues reported by Kevin)
% v.1.3 (August 13, 2010, by Luke Reisner)
% * Improved dialog layout:
% - Less wasted space, better control distribution, more consistent margins
% - Buttons are right-aligned per OS standards
% * Changed edit::date to return a simple date vector (see DATEVEC help)
% * Added support for free-form date format specifiers to edit::date
% * Added ability to limit the number of displayed lines for a listbox
% * Added ability to set default browse path/filename for edit::file controls
% * Added options.AlignControls to align adjacent controls in the same column
% * Added options.UnitsMargin to control spacing between controls and units
% * Fixed bugs:
% - Flickering or misplaced controls when dialog first appears
% - Radiobutton and togglebutton controls couldn't be disabled
% - Edit::integer controls allowed non-integer values
% - Slider controls didn't auto-size properly
% - Other minor miscellaneous bugs
% v.2.0 (July 17, 2013, by T. Ikuma & F. Hatz)
% * PROMPT(:,4) to specify tooltip strings
% * Enabled Tiled Mode with DEFAULTANSWER & FORMATS dimension specs. See
% inputsdlg_demo_struct
% * Added types: table, color, button
% * Added formats: logical and vector
% * Added 'text' format for 'list' type
% * Added 'callback' format field
% * Added 'CreateFcn' option field
% * Added 'DeleteFcn' option field
% * Added 'required' format field
% * Added 'labelloc' and 'unitsloc' format fields to customize location of
% the labels
% * removed UnitMargin option field and added 'margin' format field.
% * Added 'span' format field to make spanning across multiple rows and
% columns simpler
% * Improved handling of 'Formats' (new variable 'span' / see inputsdlg_demo)
% * A dialog with non-editable text only displays 'OK' button and does not
% return any argument
% * edit:file: diff(formats.limits)==0 => uiputfile
% v.2.0.1 (Aug 05, 2013, by T. Ikuma)
% * Bug fix on inputdlg compatible calls
% v.2.0.2 (Aug 06, 2013, by T. Ikuma)
% * Version compatibility fix for pre-R2013a
% v.2.0.3 (Sep 07, 2013)
% * Bug fix on parsing popup menu callback (reported by E. Morales)
% v.2.0.4 (Nov 25, 2013)
% * Bug fix on parsing empty callback format field (reported by David v.B.)
% v.2.0.5 (Mar 28, 2014)
% * Improved error message on FORMATS-PROMPT size mismatch.
% * Fixed several bugs relating to neglected ToolTipString support
% (thanks David v.B!)
% * FORMATS.items for Slider style now sets uicontrol's SliderStep
% property
% v.2.0.6 (Jul 01, 2014)
% * bug fix in the text positioning (~Line 2350)
% * bug fix in check_formats to insert type='edit' as default
% v.2.1.0 (Jul 03, 2014)
% * Added support for 'none' Format type with positive size to act as a
% placeholder for a row or column.
% * Removed restriction on Cancel & Apply buttons when there are only text
% controls present.
% * Bug fix on setting default answer for list:radiobutton and
% list:togglebutton
% * Bug fix on ANSWER reporting non-empty default answer for
% list:radiobutton and list:togglebutton with required='off'.
% * Bug fix on multi-select file formats
% v.2.1.1 (Sept 17, 2014)
% * Improved backward compatibility
% * Bug fix in setting default value for list:integer:radiobutton control
% v.2.1.2 (Sept 19, 2014)
% * Improved check_formats routine (faster and better backward
% compatibility)
% v.2.2 (June 25, 2015)
% * Added logical:text control with its limits format field specifying the
% returning string values
% * Numeric editboxes uses validateattribute to check its value. Its
% formats.limits field may now be set to cell array to specify the
% attribute
% * Fixed errorneous behavior when pressed Enter key in Edit control
% containing invalid value
% v.2.3 (June 26, 2015)
% * Added the row vector option for edit:vector via specifying 'row' in
% the cell-array limits definition
% * Bug fix in edit:vector limits parser
% v.2.3.1 (June 29, 2015)
% * Bug fixes in default value processing
% v.2.3.2 (June 30, 2015)
% * Bug fix for list:text default value processing (case insensitive)
% to-do list
% * Add edit:font for the built-in uisetfont dialog
% * Support for DefaultXXX option fields to set default Formats field values
% * Auto-layout given figure's desired width
% * Limits-based option for positioning of text-type
% * Better spanning support
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% # of argument Check %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
narginchk(0,5);
nargoutchk(0,2);
catch
error(nargchk(0,5,nargin)); %#ok
error(nargchk(0,2,nargout)); %#ok
end
%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Handle Input Args %%%
%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<1, Prompt={}; end
if nargin<2, Title = ''; end
if nargin<3, Formats=struct([]); end
if nargin<4, DefAns = {}; end
if nargin<5, Options = struct([]); end
% Check Prompt input
[Prompt,FieldNames,Units,TooltipStrings,err] = checkprompt(Prompt);
if ~isempty(err), error(err{:}); end
NumQuest = numel(Prompt); % number of prompts
if isempty(Title)
Title = ' ';
elseif iscellstr(Title)
Title = Title{1}; % take the first entry
elseif ~ischar(Title)
error('inputsdlg:InvalidInput','Title must be a string of cell string.');
end
% make sure that the Options is valid
[Options,FormatDefaultFields,err] = checkoptions(Options);
if ~isempty(err), error(err{:}); end
% make sure that the Formats structure is valid & fill it in default values
% as needed
[Formats,err] = checkformats(Formats,NumQuest,FormatDefaultFields);
if ~isempty(err), error(err{:}); end
% make sure that the DefAns is valid & set Answer using DefAns and default
% values if DefAns not given
[DefaultAnswer,TileMode,err] = checkdefaults(DefAns,Formats,FieldNames);
if ~isempty(err), error(err{:}); end
Answer = DefaultAnswer;
%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Create Dialog GUI %%%
%%%%%%%%%%%%%%%%%%%%%%%%%
% lay contents out on a dialog box
[Formats,handles,sinfo] ...
= buildgui(Title,Prompt,Units,TooltipStrings,FieldNames,Formats,TileMode,Options);
% fill in the default answers, setup callbacks,
initgui();
IsRequired = arrayfun(@(fmt)strcmp(fmt.required,'on'),Formats);
DefaultReqMet = checkReq(DefaultAnswer);
ReqMet = false; % also modified by the Apply button
ReturnPress = false;
Applied = false; % set true by pressing Apply Button
Canceled = ~ishghandle(handles.fig);
% Go into uiwait if the figure handle is still valid.
% This is mostly the case during regular use.
try
while ~(Canceled || ReqMet) % exit only if Canceled or all the rerequired fields are filled
% Wait till uiresume is called
uiwait(handles.fig);
figflag = get(handles.fig,'UserData');
% if Return key press released from uiwait, make sure associated
% callback did not cause an error
if ReturnPress
ReturnPress = false;
if strcmp(figflag,'Error')
ReqMet = false;
set(handles.fig,'UserData','');
continue;
end
end
% Check handle validity again since figure could be deleted externally
Canceled = strcmp(figflag,'Cancel');
if Canceled % return the default answer
Answer = DefaultAnswer; % revert back to the default answer
else
Answer = getAnswer(); % get the final answers
ReqMet = checkReq(Answer);
if ~ReqMet
h = errordlg('All required parameters must be filled.','Missing Required Value(s)','modal');
uiwait(h);
end
end
end
% if user deletefcn defined, call it now
if ~isempty(Options.DeleteFcn)
Options.DeleteFcn(handles.fig,[],handles.ctrls);
end
% Close the figure if it's still open
delete(handles.fig);
catch ME
if ishghandle(handles.fig)
delete(handles.fig);
ME.getReport
throw(ME);
else
error('Inputsdlg dialog window was closed externally');
end
end
% If Canceled, convert Canceled to integer depending on Applied condition
Canceled = Canceled * (Canceled + (Applied && DefaultReqMet));
% 0 - OK pressed
% 1 - Canceled
% 2 - Canceled but prior to it Applied button has been pressed, filled in
% all the required answers
% If Tiled, reshape the answer
Answer = reshape(Answer,NumQuest,max(TileMode));
% If FieldNames given, convert Answer to struct
Answer = selectivecell2struct(Answer,FieldNames);
% If dialog contains only non-editable texts, return w/o output argument
if nargout==0 && all(sinfo.istext)
clear Answer
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% NESTED FUNCTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function initgui
fig = handles.fig;
% set OK button as the default
fh = handle(fig);
fh.setDefaultButton(handles.btns(1));
% Set callbacks of figure/control buttons
set(fig, 'UserData', 'Cancel',...
'WindowKeyPressFcn', @doFigureKeyPress,...
'ResizeFcn', @(~,~)resizegui(handles,sinfo,Options),...
'CloseRequestFcn', @(hObj,evd)doOKCancel(hObj,evd,false));
for k = 1 : numel(handles.btns)
hbtn = handles.btns(k);
switch get(hbtn, 'UserData')
case 'OK'
set(hbtn, 'Callback', @(hObj,evd)doOKCancel(hObj,evd,true));
case 'Cancel'
set(hbtn, 'Callback', @(hObj,evd)doOKCancel(hObj,evd,false));
case 'Apply'
set(hbtn, 'Callback', @doApply);
end
end
% Set callback functions and set default values
for k = 1:numel(Answer)
h = handles.ctrls(k,1);
val = Answer{k};
fmt = Formats(k);
cbnames = fieldnames(fmt.callback);
ena = {'Enable',fmt.enable};
fcnname = 'Callback';
fcn = {};
aux = {};
% get callback function handles for custom callbacks to be
% called from inputsdlg's default callback
[tf,I] = ismember('callback',lower(cbnames));
if tf
cbfcn = fmt.callback.(cbnames{I});
else
cbfcn = {};
end
[tf,I] = ismember('buttondownfcn',lower(cbnames));
if tf
bdfcn = fmt.callback.(cbnames{I});
else
bdfcn = {};
end
switch fmt.style
case 'checkbox'
ansname = 'Value';
if strcmp(fmt.format,'text')
val = strcmp(val,fmt.limits{2});
end
case 'edit'
ansname = 'String';
switch fmt.format
case {'integer','float'}
% for numeric edit box, check for the range & set mouse down behavior
fcn = @(hObj,evd)checkNumericRange(hObj,evd,k,cbfcn);
%aux = {'UserData',val}; % save the numeric data
val = num2str(val);
case 'date'
fcn = @(hObj,evd)checkDate(hObj,evd,k,cbfcn);
case 'vector'
% for vector edit box, check for the range & set mouse down behavior
fcn = @(hObj,evd)checkVector(hObj,evd,k,cbfcn);
val = num2str(val);
case 'file'
mode = diff(fmt.limits);
fcnname = 'ButtonDownFcn';
if strcmp(ena{2},'on')
ena{2} = 'inactive';
fcn = @(hObj,evd)openFilePrompt(hObj,evd,k,bdfcn);
end
val = cellstr(val);
if ~isempty(val)
dirname = fileparts(val{1});
if ~isdir(dirname), dirname = ''; end
else
dirname = '';
end
aux = {'UserData',dirname};
if mode <= 1 % single-file
val = val{1};
end
case 'dir'
fcnname = 'ButtonDownFcn';
if strcmp(ena{2},'on')
ena{2} = 'inactive';
fcn = @(hObj,evd)openDirPrompt(hObj,evd,k,bdfcn);
end
end
case 'pushbutton'
if strcmp(fmt.type,'color')
if strcmp(ena{2},'on')
fcn = @(hObj,evd)openColorPrompt(hObj,evd,k,bdfcn);
end
ansname = 'BackgroundColor';
else
ansname = 'UserData';
end
case {'radiobutton', 'togglebutton'}
fcnname = 'SelectionChangeFcn';
ansname = 'SelectedObject';
hbtn = get(h,'UserData'); % hButtons
if strcmp(fmt.format,'integer')
val = hbtn(val);
else
val = findobj(hbtn,'flat','String',val);
end
set(hbtn,ena{:});
ena = {};
case 'table'
ansname = 'Data';
fcnname = 'CellEditCallback';
case 'slider'
if strcmp(fmt.format,'integer')
fcn = @(hObj,evd)forceInteger(hObj,evd,k,cbfcn);
end
ansname = 'Value';
case {'listbox' 'popupmenu'}
ansname = 'Value';
end
% Set control's properties
if ~strcmp(fmt.type,'text')
set(h,ena{:},fcnname,fcn,ansname,val,aux{:});
% Set custom callbacks
if ~isempty(fmt.callback)
for n = 1:numel(cbnames)
% set if the specfied callback function not already assigned
% as the part of INPUTSDLG functionality.
if ~strcmpi(cbnames{n},fcnname) || isempty(fcn)
cbfcn = @(hobj,evt)fmt.callback.(cbnames{n})(hobj,evt,handles.ctrls,k);
try
set(h,cbnames{n},cbfcn);
catch
error('Invalid callback function name.');
end
end
end
end
end
end
% make sure we are on screen
movegui(handles.fig)
% if there is a figure out there and it's modal, we need to be modal too
if ~isempty(gcbf) && strcmp(get(gcbf,'WindowStyle'),'modal')
set(handles.fig,'WindowStyle','modal');
end
% if user createfcn defined, call it now
if ~isempty(Options.CreateFcn)
Options.CreateFcn(handles.fig,[],handles.ctrls);
end
set(handles.fig,'Visible','on');
drawnow;
% set focus on the first uicontol
h = findobj(handles.ctrls(:,1),'flat','-not','Style','text');
if ~isempty(h)
h = h(1);
switch get(h,'type')
case 'uicontrol', uicontrol(h);
case {'uipanel' 'uibuttongroup'}
hsel = get(h,'SelectedObject');
if isempty(hsel), hsel = get(h,'Children'); hsel(1:end-1) = []; end
uicontrol(hsel);
case 'uitable', uitable(h);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function answer = getAnswer()
answer = cell(size(Answer));
% retrieve answer from controls
for i = 1:numel(answer)
h = handles.ctrls(i,1);
fmt = Formats(i);
switch fmt.style
case 'checkbox'
val = get(h,'Value');
if ~isempty(val)
switch fmt.format
case 'text' % 'popupmenu' 'listbox'
answer(i) = fmt.limits(val+1);
case 'logical' % 'checkbox'
answer{i} = val==get(h,'Max');
otherwise %{'float' 'integer'}
answer{i} = val;
end
end
case {'popupmenu' 'listbox' 'slider'}
val = get(h,'Value');
if ~isempty(val)
switch fmt.format
case 'text' % 'popupmenu' 'listbox'
str = get(h,'String');
answer{i} = str(val);
case 'logical' % 'checkbox'
answer{i} = val==get(h,'Max');
otherwise %{'float' 'integer'}
answer{i} = val;
end
end
case 'edit'
str = get(h,'String');
switch fmt.format
case {'float','integer'}
if ~isempty(str)
answer{i} = str2double(str);
else
answer{i} = [];
end
case 'date'
if isempty(str)
answer{i} = []; % Return an empty date vector if no date was entered
else
answer{i} = datevec(str, fmt.limits);
end
case 'file'
if diff(fmt.limits)>1
answer{i} = cellstr(str);
else
answer{i} = str;
end
case {'vector'}
answer{i} = str2num(str); %#ok
otherwise %case {'text' 'dir'}
answer{i} = str;
end
case {'radiobutton' 'togglebutton'} % uibuttongroup
hbtn = get(h,'SelectedObject');
if isempty(hbtn) && strcmp(fmt.required,'on')
disp('required but not given')
end
if strcmp(fmt.format,'text')
if isempty(hbtn)
answer{i} = '';
else
answer{i} = get(hbtn,'String');
end
else
if isempty(hbtn)
answer{i} = [];
else
answer{i} = find(hbtn==get(h,'UserData'));
end
end
case 'pushbutton'
if strcmp(fmt.type,'color')
answer{i} = get(h,'BackgroundColor');
if strcmp(fmt.format,'integer')
answer{i} = uint8(round(answer{i}*255));
end
else
answer{i} = get(h,'UserData');
end
case 'table'
answer{i} = get(h,'Data');
end
end
end
function reqmet = checkReq(answer)
idx = cellfun(@isempty,answer);
reqmet = ~any(IsRequired(:)&idx(:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Control Button Callback callback functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function doFigureKeyPress(obj, evd)
[tf,I] = ismember(evd.Key,{'return','space','escape'});
if ~tf, return; end % nothing special to do
ReturnPress = false;
if any(I==[1 2])
% Ignore under a condition when GCO is an edit uicontrol
% Known Potential Issue: GCO could be modified from outside
hedit = findobj(gco,'flat','type','uicontrol','style','edit');
ignore = ~isempty(hedit);
if ignore
% check for the conditions
if I==1 % return
% resume only if not currently in a multi-line edit uicontrol
ignore = get(hedit,'Max')-get(hedit,'Min')>1;
ReturnPress = true;
end
if ignore
return;
end
end
% equivalent to pressing OK button
set(obj,'UserData','OK');
elseif I==3 % Cancel
% equivalent to pressing Cancel button
set(obj,'UserData','Cancel');
else
return;
end
% set focus on OK button (to update the value of the current control)
uicontrol(handles.btns(1));
% if reached this far, valid key press to close the dialog
uiresume(obj);
end
function doOKCancel(~, ~, isok)
if isok
set(gcbf,'UserData','OK');
uiresume(gcbf);
else
set(gcbf,'UserData','Cancel');
uiresume(gcbf); % cancel
end
end
function doApply(~,~)
DefaultAnswer = getAnswer(); % retrieve the current answers from the controls
DefaultReqMet = checkReq(DefaultAnswer);
Applied = true;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UICONTROL ButtonDownFcn callback functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function checkNumericRange(hObj,evt,k,cbfcn)
fmt = Formats(k);
errored = false;
str = get(hObj,'String');
if isempty(str)
if fmt.required
% show an error dialog
h = errordlg('This parameter must be filled with a value.','Required Value','modal');
errored = true;
else
Answer{k} = [];
end
else
% convert to float/integer
val = str2double(str);
isint = strcmp(fmt.format, 'integer');
if isint
val = round(val); % Round to the nearest integer
end
% validate the value
lim = fmt.limits;
if ~iscell(lim)
lim = {'' lim(1) '' lim(2)};
if lim{4}==inf
lim([3 4]) = [];
else
lim{3} = '<=';
end
if lim{2}==-inf
lim([1 2]) = [];
else
lim{1} = '>=';
end
end
try
validateattributes(val,{'numeric'},[{'scalar'} lim]);
% Re-format the control's text according to the value
set(hObj, 'String', num2str(val));
Answer{k} = val; % store the numeric answer to revert to later
catch MExcept
h = errordlg(MExcept.message,'Invalid Value','modal');
errored = true;
end
end
if errored
% set flag
set(handles.fig,'UserData','Error');
% revert back to the previous value
set(hObj,'String',num2str(Answer{k}));
uiwait(h);
elseif ~isempty(cbfcn) % success
% run custom callback function
cbfcn(hObj,evt,handles.ctrls,k);
end
end
function checkVector(hObj,evd,k,cbfcn)
fmt = Formats(k);
errored = false;
str = get(hObj,'String');
if isempty(str)
if fmt.required
% show an error dialog
h = errordlg('This parameter must be filled with a value.','Required Value','modal');
errored = true;
else
Answer{k} = [];
end
else
% convert to float/integer
val = str2num(str); %#ok
lim = fmt.limits;
try
if iscell(lim)