function thisrender(this, opts)
%THISRENDER Render the FDATool

%   Copyright 1988-2017 The MathWorks, Inc.

% Determine the figure position relative to screen size and resolution
sz = fdatool_gui_sizes(this);
menucbs = menus_cbs(this);  % get structure of all local callback functions

% Keep figure invisible until all the uicontrols are displayed.
hFig = figure('IntegerHandle', 'off', ...
    'Color', 'default', ...
    'Visible', 'Off', ...
    'MenuBar', 'none', ...
    'WindowStyle', 'normal', ... %WindowStyle before Resize to avoid docking issues.
    'Resize', 'Off', ...
    'Name', opts.title, ... 
    'DockControls', 'Off', ...
    'NextPlot', 'add', ...
    'CloseRequestFcn', menucbs.exit_cb, ...
    'NumberTitle', 'off', ...
    'Units', 'pixels', ...
    'Pointer', 'Watch', ...
    'HandleVisibility', 'Callback', ...
    'Tag', 'Initializing', ...
    'UserData', opts, ...
    'Position', sz.figpos, ...
    'Color', get(0,'DefaultUicontrolBackgroundColor'));

sigsetappdata(hFig, 'fdatool', 'handle', this);
set(this, 'FigureHandle', hFig);

% Render the status box.
status = getString(message('signal:sigtools:sigtools:InitializingFilterDesignAndAnalysisTool'));
render_statusbar(hFig, status, 'Visible', 'On');

set(hFig, 'Visible', 'On');

% Render the menus.
% Set up main menus
menus = {...
        getString(message('signal:sigtools:sigtools:File')),...
        getString(message('signal:sigtools:sigtools:Edit')),...
        getString(message('signal:sigtools:sigtools:Analysis')),...
        getString(message('signal:sigtools:sigtools:Targets')),...
        getString(message('signal:sigtools:sigtools:Viewamp'))};
callbacks = {[],[],[],[],[]};
tags = {'file',...
        'edit',...
        'analysis', ...
        'targets',...
        'view'};
for i=1:length(menus)
    h.menus.main(i) = uimenu(hFig,'Label',menus{i},...
        'Tag',tags{i}, ...
        'Visible', 'Off', ...
        'Callback',callbacks{i});
end
% Set up the Window menu
i = i + 1;
h.menus.main(i) = matlab.ui.internal.createWinMenu(hFig);
set(h.menus.main(i),'Visible','Off');
set(h.menus.main(i), 'Label', getString(message('signal:sigtools:sigtools:Window'))); 

% setup File menu items. 
str2match = getString(message('signal:sigtools:sigtools:File')); %#ok<NASGU>
menus = {...
        getString(message('signal:sigtools:sigtools:NewSession')),...
        getString(message('signal:sigtools:sigtools:OpenSession')),...
        getString(message('signal:sigtools:sigtools:SaveSession')),...
        getString(message('signal:sigtools:sigtools:SaveSessionAs')),...
        getString(message('signal:sigtools:sigtools:StoreFilter')), ...
        getString(message('signal:sigtools:sigtools:Export')),...
        getString(message('signal:sigtools:sigtools:GenerateMATLABCode')), ...
        getString(message('signal:sigtools:sigtools:PrintPreview')),...
        getString(message('signal:sigtools:sigtools:Print')),...
        getString(message('signal:sigtools:sigtools:Close'))};
tags = {...
        'new',...
        'open',...
        'save',...
        'saveas',...
        'storefilter',...
        'export',...
        'genmcodemain', ...
        'printprev',...
        'print',...
        'exit'};
callbacks = {...
        menucbs.new_cb,...
        menucbs.open_cb,...
        menucbs.save_cb,...
        menucbs.saveas_cb,...
        {menucbs.method, this, 'filtermanager', [], 'save'}, ...
        menucbs.export_cb,...
        [], ...
        menucbs.printprev_cb,...
        menucbs.print_cb,...
        menucbs.exit_cb};
accelerators = {...
        'n',...
        'o',...
        's',...
        '',...
        '',...
        'e',...
        '', ...
        '',...
        'p',...
        ''};  
% indicate which items have separators and which don't
separator_indx = [5 6 8 10];

if ~opts.flags.filtermanager
    tags(5) = [];
    accelerators(5) = [];
    callbacks(5)    = [];
    menus(5)        = [];
    separator_indx  = [separator_indx(1) separator_indx(3:4)-1];
end

if ~opts.flags.newsession
    tags(1)         = [];
    accelerators(1) = [];
    callbacks(1)    = [];
    menus(1)        = [];
    separator_indx = separator_indx-1;
end

for i = 1:length(menus)
    if any(i == separator_indx)
        separator = 'on';
    else
        separator = 'off';
    end
    
    if strcmpi(tags{i},'genmcodemain')
      % Main menu
      h.menus.file(i) = uimenu(h.menus.main(1), ...
        'Label',menus{i},...
        'Separator',separator,...
        'Accelerator',accelerators{i},...
        'Tag',tags{i});
      
      % Submenus
      h.menus.add = uimenu(h.menus.file(i), ...
        'Label',getString(message('signal:sigtools:sigtools:FilterDesignFunction')),...
        'Callback',{menucbs.method, this, 'genmcode'}, ...,
        'Accelerator','',...
        'Tag','genmcode');
      
      enab = 'off';
      if isfdtbxinstalled
        enab = 'on';
      end
      
      h.menus.add = uimenu(h.menus.file(i), ...
        'Label',getString(message('signal:sigtools:sigtools:FilterDesignFunctionwithSystemObjects')),...
        'Callback',{menucbs.method, this, 'genmcodesysobj'}, ...
        'Accelerator','',...
        'Tag','genmcodesysobj',...
        'Enable',enab);
      
      h.menus.add = uimenu(h.menus.file(i), ...
        'Label',getString(message('signal:sigtools:sigtools:DataFilteringFunctionwithSystemObjects')),...
        'Callback', {menucbs.method, this, 'genfilterfcnsysobj'}, ...
        'Accelerator','',...
        'Tag','genfilterfcnsysobj',...
        'Enable',enab);                  
    else
      
      h.menus.file(i) = uimenu(h.menus.main(1), ...
        'Label',menus{i},...
        'Separator',separator,...
        'Callback',callbacks{i},...
        'Accelerator',accelerators{i},...
        'Tag',tags{i});
    end
end

set(h.menus.file(2), 'Interruptible', 'Off');

render_zoommenus(hFig, [5 1], 'defaultview',~matlabshared.scopes.useWebFigure());

h.menus.targets = uimenu('Parent', h.menus.main(4), 'Label', getString(message('signal:sigtools:sigtools:GenerateCHeader')), ...
    'Callback', {menucbs.method, this, 'cheader'}, 'Tag', 'cheader');

pos = 7; % Position on menubar

% % Render basic Signal Processing Toolbox Help menu. 
[hhelpmenu, h.menus.help] = render_spthelpmenu(hFig, pos);
set(hhelpmenu, 'Visible', 'Off');

% Store the handle to the "Help" menu back in h.main
h.menus.main = [h.menus.main(1:pos-1),hhelpmenu,h.menus.main(pos:end)];

% Render "FDATool Help" separately so that it is on top of "Signal  
% Processing Toolbox Help" (which is rendered by render_spthelpmenu.m 
help_handles = fdatool_help;
h.menus.help = [h.menus.help addmenu(hFig,[pos 1], ...
        getString(message('signal:sigtools:sigtools:FDAToolHelp')),... 
        help_handles.toolhelp_cb,'toolhelp','Off')];
 
% Common FDATool Help menu items 
menuitems = {getString(message('signal:sigtools:sigtools:TipOfTheDay')), ...
        getString(message('signal:sigtools:sigtools:ImportingFilters')), ...
        getString(message('signal:sigtools:sigtools:ExportingFilters')), ...
        getString(message('signal:sigtools:sigtools:SavingOpeningSessions'))}; 
cbs = {{@tipoftheday_cb,this} ...
        help_handles.importhelp_cb,... 
        help_handles.exporthelp_cb,... 
        help_handles.saveopensessionshelp_cb}; 
tags = {'tipoftheday', ...
        'importhelp', ...
        'exporthelp', ...
 'saveopensessionhelp'}; 
sep = {'On', 'On','Off','Off'}; 

% Add the menu items to FDATool's Help menu 
h.menus.help = [h.menus.help addmenu(hFig,[pos 3],menuitems,cbs,tags,sep)];

% Render the toolbar.
% Render a Toolbar
h.toolbar.main = uitoolbar('Parent',hFig,'Visible', 'off');

% Render standard buttons (New, Open, Print, Print Preview)

% Load new, open, save print and print preview icons.
bmp = load('mwtoolbaricons');

% -------- FILE PUSHBUTTONS --------
% Cell array of cdata (properties) for the toolbar icons 
% that are file pushbuttons (New, Open, Save, and Print)
pushbuttons = {...
        bmp.newdoc,...
        bmp.opendoc,...
        bmp.savedoc,...
        bmp.printdoc,...
        bmp.printprevdoc};

% List the corresponding tooltips
tooltips = {...
        getString(message('signal:sigtools:sigtools:NewSession_1')),...
        getString(message('signal:sigtools:sigtools:OpenSession_1')),...
        getString(message('signal:sigtools:sigtools:SaveSession_1')),...
        getString(message('signal:sigtools:sigtools:PrintCurrentResponse')),...
        getString(message('signal:sigtools:sigtools:Printpreview'))};

% List tags for the pushbuttons
tags = {...
        'newsession',...
        'opensession',...
        'savesession',...
        'printresp',...
        'printprev'};

% List callbacks for pushbuttons
cbs = {...
        menucbs.new_cb,...
        menucbs.open_cb,...
        menucbs.save_cb,...
        menucbs.print_cb,...
        menucbs.printprev_cb};

if ~opts.flags.newsession
    pushbuttons(1) = [];
    tooltips(1)    = [];
    tags(1)        = [];
    cbs(1)         = [];
end

% Render the pushbuttons
for indx = 1:length(tags)
    h.toolbar.(tags{indx}) = uipushtool(h.toolbar.main, ...
        'CData', pushbuttons{indx}, ...
        'ClickedCallback', cbs{indx}, ...
        'Tag', tags{indx}, ...
        'TooltipString', tooltips{indx});
end

set(h.toolbar.opensession, 'Interruptible', 'Off');

% set([h.toolbar.undo h.toolbar.redo], 'Enable', 'Off');

% % Install the UNDO manager so its icons will be first
% sigsetappdata(this.FigureHandle, 'siggui', 'HasUndo', true);

% uimenu(h.menus.main(2), ...
%     'Label', 'Undo', ...
%     'Enable', 'Off', ...
%     'Tag', 'undo', ...
%     'Accelerator', 'z', ...
%     'Position', 1);
% uimenu(h.menus.main(2), ...
%     'Label', 'Redo', ...
%     'Enable', 'Off', ...
%     'Tag', 'redo', ...
%     'Accelerator', 'y', ...
%     'Position', 2);

% Render the Zoom In and Zoom Out buttons
render_zoombtns(hFig,~matlabshared.scopes.useWebFigure());

% Render the "Full View Analysis" and "Static Response" buttons
% Load the MAT-file with the icon
load(fullfile(matlabroot, 'toolbox', 'signal', 'sigtools', 'private', 'filtdes_icons.mat'));

% Render the "Full View Analysis" push button.
h.toolbar.fullviewanalysis = uipushtool(h.toolbar.main, ...
    'CData',           bmp.fullviewanalysis, ...
    'ClickedCallback', menucbs.fullviewanalysis_cb,...
    'Tag',             'fullviewanalysis', ...
    'Separator',       'On', ...
    'TooltipString', getString(message('signal:sigtools:sigtools:FullViewAnalysis')));
h.toolbar.staticresponse = uitoggletool(h.toolbar.main, ...
    'Tag',             'staticresponse', ...
    'TooltipString', getString(message('signal:sigtools:sigtools:FilterSpecifications1')), ...
    'State',           'On', ...
    'ClickedCallback', {@staticresp_cb, this}, ...
    'Separator',       'on', ...
    'CData',           bmp.illus);

hm = findall(h.menus.main, 'Tag', 'analysis');

h.menu.analysis = uimenu(hm, 'Label', getString(message('signal:sigtools:sigtools:FilterSpecifications')), ...
    'Callback', {@staticresp_cb, this}, 'Tag', 'filterresponsespecs');

% Render the Analysis frame.
bgc = get(hFig,'Color');

% Position of the frame (axis).
x = sz.fx2;
y = sz.fy1+1;  % Add a pixel; y pos of an axis is different then a frame.
w = sz.fw2;
ht = sz.fh1-1;  % Remove the pixel added a couple of lines above.

% Create an axis to be used as the frame.
h.analysis.frame(1) = axes(...
    'Parent', hFig, ...
    'Units','pixels',...
    'Position',[x y w ht],...
    'Box','On',...
    'Color',bgc,...
    'Tag','analysisframeaxis',...
    'Visible','off',...
    'XTick',[],...
    'YTick',[],...
    'XTickLabel',[],...
    'YTickLabel',[]);
h.analysis.frame(1).Toolbar = [];

h.staticresp = axes('Parent',hFig, ...
    'Units', 'Pixels', ...
    'Position', [277 322 414 169]*sz.pixf, ...
    'Tag', 'staticresponse_axes', ...
    'Visible','Off');
h.staticresp.Toolbar = [];

zoomBehavior = hggetbehavior(h.staticresp, 'Zoom');
zoomBehavior.Enable = false;

% Set axis units to normalize so that we can get free cheap resizing.
% NOTE: The function that sets all the units to normalized doesn't catch this axis
% because this axis' handlevisibility is set to off to avoid zooming.
set(h.analysis.frame(1),'Units','Normalized');

% The appdata will be useful to ignore this axes from being zoomed
setappdata(h.analysis.frame(1),'zoomable','off')

% Determine the width extent of the label for the frame.
frLabel = {getString(message('signal:sigtools:sigtools:FilterSpecifications1'))};
frLabelW = largestuiwidth(frLabel); % 95;

% Render the label.
frameLabelPos = [x+sz.lfs (y+ht)-sz.lh/2 frLabelW sz.lh];
h.analysis.frame(2) = uicontrol(...
    'Parent', hFig, ...
    'Style','Text',...
    'Visible', 'Off', ...
    'BackgroundColor',bgc,...
    'HorizontalAlignment','center', ... 
    'Position',frameLabelPos,...
    'Tag','analysisframelabel',...
    'String',frLabel);

% Don't allow zooming in frame (axis).
set(h.analysis.frame(1),'HandleVisibility','off');

% Use axis to create the frame.
h.recessedFr = axes(...
    'Parent', hFig, ...
    'Units','pixels',....
    'Visible','off',...
    'Tag','recessedframe',...
    'Position',sz.panel);
set(h.recessedFr,...
    'Parent', hFig, ...
    'NextPlot', 'ReplaceChildren', ...
    'Units','normalized',...
    'XLim',[0 1],'YLim',[0 1]);
h.recessedFr.Toolbar = [];

zoomBehavior = hggetbehavior(h.recessedFr, 'zoom');
zoomBehavior.Enable = false;

% Create the recessed visual effect with lines.
h.recessedFr(2) = line([0 1 1],[0 0 1],'Color','white','LineWidth',2,'Visible','off', 'Parent', h.recessedFr(1));
h.recessedFr(3) = line([0 0 1],[0 1 1],'Color',[1 1 1]*0,'LineWidth',1,'Visible','off', 'Parent', h.recessedFr(1));

set(h.recessedFr(1),'HandleVisibility','off');  % Don't allow zooming.

set(this, 'Handles', h);

l = [ ...
        handle.listener(this, [this.findprop('FigureTitle') ...
            this.findprop('SubTitle') this.findprop('FileName') ...
            this.findprop('FileDirty')], 'PropertyPostSet', @lcltitle_listener); ...
        handle.listener(this, 'FilterUpdated', @lclmcode_listener);];

set(l, 'CallbackTarget', this);
set(this, 'WhenRenderedListeners', l);

% ---------------------------------------------------------------------
function tipoftheday_cb(hcbo, eventStruct, this) %#ok<*INUSL>

hFig = getappdata(this, 'tipoftheday');
if ishghandle(hFig)
    figure(hFig);
else
    hFig = tipoftheday('fdatool', @getfdatooltip);
    this.centerfigonfig(hFig);
    setappdata(this, 'tipoftheday', hFig);
end

% ---------------------------------------------------------------------
function staticresp_cb(hcbo, eventStruct, this)

hs = find(this, '-class', 'siggui.sidebar');
h  = find(allchild(hs), '-depth', 0, 'Visible', 'On'); %#ok<GTARG>

set(h, 'StaticResponse', 'On');
if strcmpi(get(hcbo, 'Type'), 'uitoggletool'), set(hcbo, 'State', 'on'); end

hFVT = this.FvtoolHandle;
set(hFVT, 'Analysis', '');
sendstatus(this, getString(message('signal:sigtools:siggui:Ready')));


%-------------------------------------------------------------------
function hndls = LOCALpush(hut,cdata,ccbs,tags,sep,ttstr) %#ok<DEFNU>
% Local function to call UIPUSHTOOL in a loop

% Render the Push buttons
hndls = zeros(1, length(cdata));
for i = 1:length(cdata)
    hndls(i) = uipushtool('CData',cdata{i},...
        'Parent',          hut,...
        'ClickedCallback', ccbs{i},...
        'Tag',             tags{i},...
        'Separator',       sep{i},...
        'Visible',         'off', ...
        'TooltipString',   ttstr{i});
end

%----------------------------------------------------------------------
function lclmcode_listener(this, eventStruct)  %#ok<*INUSD>

% The MCodeSupported, and SysObjMCodeSupported flags are set and reset in
% the savemcode method at
% toolbox\signal\sigtools\@sigtools\@fdatool\setfilter.m
if isempty(this.MCode) || ~this.MCodeSupported
  enab = 'off';
  enabSysObj = 'off';
else
  enab = this.Enable;
  enabSysObj = this.Enable;
  currFilter = getfilter(this);
  if strcmpi(enab,'on') && ...
      (~sysobj(currFilter,true) || ~this.SysObjMCodeSupported)
    %We call the sysobj method with a second input flag set to true to
    %see if the System object conversion is supported for the dfilt/mfilt
    %object at hand
    enabSysObj = 'off';
  end
  if strcmpi(enabSysObj,'on') && isa(currFilter, 'mfilt.abstractmultirate')
    % Disable mfilt MCode generation when System object MCode generation is
    % supported.
    enab = 'off';
  end
end
 
h = get(this, 'Handles');
 
set(findobj(h.menus.file, 'tag', 'genmcode'), 'Enable', enab);
set(findobj(h.menus.file, 'tag', 'genmcodesysobj'), 'Enable', enabSysObj);
set(findobj(h.menus.file, 'tag', 'genfilterfcnsysobj'), 'Enable', enabSysObj);

%----------------------------------------------------------------------
function lcltitle_listener(this, eventStruct)

title = gettitle(this);

% Find the handle to the 'save' item in the file menu to set 
% the enable property.
h_file = gethandles(this,'menus','file');
h_save = findobj(h_file,'tag','save');

if get(this, 'FileDirty')
    set(h_save,'Enable','on');
else
    set(h_save,'Enable','off');
end

set(this.FigureHandle, 'Name', title);

% [EOF]
