function domymenu(method, parameter, object)
%DOMYMENU  handle menus for Plot editor

%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.36 $  $Date: 1998/10/15 14:42:01 $

if strcmp(method,'menubar')
   LDoMenubar(gcbf, parameter);
   return
end

if nargin==3
   CurrentHGObj = object;
else
   CurrentHGObj = gcoall;
end

ud = getappdata(CurrentHGObj,'ScribeObjectData');
if isempty(ud)
   primaryObj = getappdata(CurrentHGObj,'ScribeButtonDownHGObj');
   if ~isempty(primaryObj) & ishandle(primaryObj)
      ud = getappdata(primaryObj,'ScribeObjectData');
   end
end

try
   if ~isempty(ud)
      A = ud.ObjectStore;
   else
      A = [];
   end
   % can't do this:
   % if isstruct(ud) & isfield(ud,'ObjectStore')
   % because we've overloaded subsref for fighandle objects
   % which is what we have in the figure ScribeObjectData
catch
   if strcmp(method,'menubar')
      A = [];
      % we don't need to have plotedit on...
      LDoMenubar(CurrentHGObj, parameter);
      return
   else
      return
   end
end

try
   switch method
   case 'menubar'
      LDoMenubar(CurrentHGObj, parameter);

   case 'update'
      A = doselect(A);
      A = updatemenu(A);
      UIC = gcbo;
      
      [copyBufferFig, copyBufferAx] = getcopybuffer('noforce');
      if ~isempty(copyBufferFig) ...
                 & ~isempty(LGetSelection(copyBufferFig))
         set(findall(UIC,'Label','&Paste'),...
                 'Enable','on');
      else
         set(findall(UIC,'Label','&Paste'),...
                 'Enable','off');
      end

      callingObject = getappdata(UIC,'ScribeOneShotContextMenuFlag');
      if ~isempty(callingObject)
         try
            set(callingObject,{'UIContextMenu' 'ButtonDownFcn'}, ...
                    getappdata(UIC,'ScribeSaveFcns'));
            rmappdata(UIC,'ScribeSaveFcns');
         catch
            warning('Object properties may be corrupted.');
         end
      end
   case 'updatemenu'
      switch parameter
      case 'edit'
         myFig = get(A,'Figure');      
         CCCMenu = findall(myFig,'Tag','scrCCCMenu');
         selection = LGetSelection(myFig);
         if isempty(selection)
            set(CCCMenu,'Enable','off');
         else
            set(CCCMenu,'Enable','on'); 
         end
         
         [copyBufferFig, copyBufferAx] = getcopybuffer('noforce');
         if ~isempty(copyBufferFig) ...
            & ~isempty(LGetSelection(copyBufferFig))
            set(findall(myFig,'Tag','scrPasteMenu'),...
                    'Enable','on');
         else
            set(findall(myFig,'Tag','scrPasteMenu'),...
                    'Enable','off');
         end
         
         switch plotedit(myFig,'getenabletools')
         case 'off'
            PasteMenu = findall(myFig,'Tag','scrPasteMenu');
            set([PasteMenu; CCCMenu],'Enable','off');
         % otherwise % 'on'
         end

      end
   case 'style'
      A = editstyle(A,parameter);
      myFig = get(A,'Figure');      
      myClass = class(A);
      selection = LGetSelection(myFig);
      for aObj = selection
         switch myClass
         case {'arrowline' 'editline'}
            if isa(aObj,'arrowline') | isa(aObj,'editline')
               domethod(aObj, 'editstyle', parameter);
            end
         otherwise
            if isa(aObj,myClass)
               domethod(aObj, 'editstyle', parameter);
            end
         end
      end
      LUpdateLegend(selection);
      
   case 'size'
      A = editsize(A,parameter);
      myFig = get(A,'Figure');
      myClass = class(A);
      selection = LGetSelection(myFig);
      for aObj = selection
         switch myClass
         case {'arrowline' 'editline'}
            if isa(aObj,'arrowline') | isa(aObj,'editline')
               domethod(aObj, 'editsize', parameter);
            end
         otherwise
            if isa(aObj,myClass)
               domethod(aObj, 'editsize', parameter);
            end
         end
      end
      LUpdateLegend(selection);
      
   case 'color'
      myColor = get(A,'Color');
      myFig = get(A,'Figure');
      selection = LGetSelection(myFig);
      if length(selection)==1
         c = uisetcolor(myColor);
      else % multiple objects: we really need to see if there
           % was a cancel
         c = uisetcolor;
      end
      if length(c)==1 & c==0
         % cancel
         return
      end
      
      for aObj = selection
         if ~strcmp(class(aObj),'axisobj')  % don't change
                                            % axes color
            set(aObj,'Color',c);
         end
      end
      LUpdateLegend(selection);
      
   case 'string'
      A = editopen(A);
   case 'moveresize'
      % A = editmoveresize(A);
      newstate = ~get(A,'Draggable');
      % write back current changes
      LWriteBack(A,ud,CurrentHGObj);
      for a = LGetSelection(get(A,'Figure'))
         if strcmp(class(a),'axisobj')
            set(a,'Draggable',newstate);
         end
      end
      return  % avoid second writeback

   case 'showlegend'
      if islegendon(get(A,'MyHGHandle'))
         newstate = 'off';
      else
         newstate = 'on';
      end
      % write back current changes
      LWriteBack(A,ud,CurrentHGObj);
      for a = LGetSelection(get(A,'Figure'))
         if strcmp(class(a),'axisobj')
            domethod(a,'showlegend',newstate);
         end
      end
      return  % avoid second writeback
      
   case 'more'
      A = editopen(A);
   case 'font'
      A = editfont(A);
   case {'cut' 'copy' 'paste' 'clear'}
      myFig = get(A,'Figure');
      cutcopypaste(myFig, method);
      return
   end

   LWriteBack(A,ud,CurrentHGObj);

catch
   warning(['Error executing plot editor menu: ' lasterr]);
end


function LWriteBack(A,ud,HG)
if ~isempty(A)
   ud.ObjectStore = A;
   if ishandle(HG) % we may have deleted the object
      setappdata(HG,'ScribeObjectData',ud);
   end
end


function LDoMenubar(myFig, method)

switch method
case {'cut' 'copy' 'paste' 'clear'}
   cutcopypaste(myFig, method);
case {'save' 'saveas'}
   selection = LGetSelection(myFig);
   plotedit(myFig,'off','silent');
   % clear before saving
   scribeclearmode(myFig,'');
   switch method
   case 'save'
      filemenufcn(myFig,'FileSave');
   case 'saveas'
      filemenufcn(myFig,'FileSaveAs');
   end
   plotedit(myFig,'on');
   % restore selection
   for a = selection
      set(a,'IsSelected',1);
   end
case 'updatetools'
   toolsMenuItems = allchild(findobj(allchild(myFig),'flat',...
           'Type','uimenu','Tag','figMenuTools'));
   set(toolsMenuItems,'Enable','on');
   check = {'off' 'on'};

   % Show Toolbar
   toolbarShowing = ~isempty(findall(myFig,'Tag','ScribeSelectToolBtn'));
   mShowToolbar = findall(myFig,'Label','Show &Toolbar');
   if ~isempty(mShowToolbar)
      set(mShowToolbar,'Checked',check{toolbarShowing+1});
   end
   
   % Enable Plot Editing
   ploteditActive = plotedit(myFig,'isactive');
   mPlotEdit = findall(myFig,'Tag','figMenuToolsPlotedit');
   if ~isempty(mPlotEdit)
      set(mPlotEdit,'Checked',check{ploteditActive+1});
   end

   selection = LGetSelection(myFig);

   % pull out axis objects in the selection
   axisObjects = [];
   if ~isempty(selection)
      for a = selection
         if strcmp(class(a),'axisobj')
            axisObjects = [axisObjects a];
         end
      end
   end
   
   % Show Legend
   mShowLegend = findall(gcbo,'Tag','figMenuToolsShowLegend');
   ax = get(myFig,'CurrentAxes');
   if ploteditActive
      axLegendOn = [];
      for a = axisObjects
         % find the axes and see if they're locked.
         axLegendOn(end+1) = islegendon(get(a,'MyHGHandle'));
      end
      
      if isempty(axLegendOn) & isempty(ax)
         % disable only if the selection includes no axes AND
         % there is no current axis
         mShowLegendEnable = 'off';
      else
         mShowLegendEnable = 'on';
      end
      
      if isempty(axisObjects)
         % no axes are part of the selection
         % look at the current axis.
         if isempty(ax)
            axLegendOn = 0;  % force a "Show Legend"
         else
            axLegendOn = islegendon(ax);
         end
      end
      
      % axes are selected
      if length(find(axLegendOn)) > length(axLegendOn)/2
         % over half are showing legends
         mShowLegendLabel = 'Hide Le&gend';
      else
         mShowLegendLabel = 'Show Le&gend';
      end

   else
      if ~isempty(mShowLegend)
         if ~isempty(ax)
            if islegendon(ax)
               mShowLegendLabel = 'Hide Le&gend';
            else
               mShowLegendLabel = 'Show Le&gend';
            end
            mShowLegendEnable = 'on';            
            % set(mShowLegend,'Checked',check{islegendon(ax)+1});
         else
            mShowLegendLabel = 'Show Le&gend';
            mShowLegendEnable = 'off';
            % set(mShowLegend,'Checked',check{0+1})
         end
      end
   end
   set(mShowLegend, ...
           'Enable', mShowLegendEnable,...
           'Label', mShowLegendLabel)
   
   % Lock Axes Position/Unlock Axes Position
   mLockAxes = findall(gcbo,'Tag','figMenuToolsLockAxes');
   if ploteditActive
      axLock = [];
      for a = axisObjects
         % find the axes and see if they're locked.
         axLock(end+1) = get(a,'Draggable');
      end
      if isempty(axLock)
         mLockAxesEnable = 'off';
         mLockAxesLabel = 'Unloc&k Axes Position';
      else
         mLockAxesEnable = 'on';
         if length(find(axLock)) > length(axLock)/2
            % over half are draggable
            mLockAxesLabel = 'Loc&k Axes Position';
         else
            mLockAxesLabel = 'Unloc&k Axes Position';
         end
      end
   else
      mLockAxesEnable = 'off';
      mLockAxesLabel = 'Unloc&k Axes Position';
   end
   set(mLockAxes,...
           'Label',mLockAxesLabel,...
           'Enable',mLockAxesEnable);
   
   % disable the items under the tools menu if plotedit is suspended.
   switch plotedit(myFig,'getenabletools')
   case 'off'
      set(toolsMenuItems,'Enable','off');
   % otherwise % 'on'
   end

case 'toggletoolbar'
   if isempty(findall(myFig,'Tag','ScribeSelectToolBtn'))
      newstate = 'figure';
   else
      newstate = 'none';
   end
   if feature('figuretools')
      set(myFig,'ToolBar',newstate);
   else
      feature('figuretools',1);
      set(myFig,'ToolBar',newstate);
      feature('figuretools',0);
   end
   % shouldn't be necessary
   drawnow

case 'lockaxes'
   selection = LGetSelection(myFig);
   axesObjects = [];
   axLock = [];
   for a = selection
      if strcmp(class(a),'axisobj')
         axesObjects = [axesObjects a];
         axLock(end+1) = get(a,'Draggable');
      end
   end
   if ~isempty(axLock)
      if length(find(axLock)) > length(axLock)/2
         setDrag = 0;  % lock
      else
         setDrag = 1;  % unlock
      end
      for a = axesObjects
         set(a,'Draggable',setDrag);
      end
   end
   
   
case 'axesprop'
   if plotedit(myFig,'isactive')
      % plotedit is active, pass the selection list
      scribeaxesdlg(LGetSelection(myFig));
   else
      ax = get(myFig,'CurrentAxes');
      plotedit(myFig,'on');
      axH = getobj(ax);
      if isempty(axH) & ~isempty(ax)
         axH = scribehandle(axisobj(ax));
      end
      set(axH,'IsSelected',1);
      scribeaxesdlg(axH);
   end
   
case 'lineprop'
   if plotedit(myFig,'isactive')
      % plotedit is active, pass the selection list
      scribelinedlg(LGetSelection(myFig));
   else
      % look for a current line
      co = gcoall(myFig);
      if isempty(co)
         plotedit(myFig,'on');
         scribelinedlg([]);
      elseif strcmp(get(co,'Type'),'line')
         % this will not catch all arrows.  that's okay, we'll
         % get them when plotedit is active.
         if strcmp('legend',get(get(co,'Parent'),'Tag'))
            errordlg(['To change line properties for a legend,' ...
                       sprintf('\n') ...
                       ' change the line properties for its parent axis.']);
            return
         end
         lineH = getobj(co);
         if isempty(lineH)
            lineH = scribehandle(editline(co));
         end
         plotedit(myFig,'on');
         set(lineH,'IsSelected',1);
         scribelinedlg(lineH);
      else
         plotedit(myFig,'on');
         scribelinedlg([]);
      end
   end


case 'textprop'
   if plotedit(myFig,'isactive')
      scribetextdlg(LGetSelection(myFig));
   else
      co = gcoall(myFig);
      % select the current object if possible
      if isempty(co)
         plotedit(myFig,'on');
         scribetextdlg([]);
      else
         if strcmp('legend',get(co,'Tag')) ...
                    | strcmp('legend',get(get(co,'Parent'),'Tag'))
            errordlg(['To change text properties for a legend, change '...
                       sprintf('\n') ...                    
                       'the text properties for its parent axis.']);
            return
         end
         % don't activate text objects with editing on
         % so we don't activate a drag when the editing is
         % over, and don't activate plotedit (which switches
         % the menus) while editing is active.
         if ~strcmp(get(co,'Type'),'text')
            plotedit(myFig,'on');
            scribeeventhandler;
            scribetextdlg(LGetSelection(myFig));
         elseif strcmp(get(co,'Editing'),'on')
            % in the middle of adding a new text object
            uisetfont(co,'Editing Font Properties');
         end
      end
   end

   
case 'legend'
   ploteditOn = plotedit(myFig,'isactive');
   if ploteditOn
      % first, look for selected axes
      selection = LGetSelection(myFig);
      axObjects = [];
      axLegendOn = [];
      for a = selection
         if strcmp(class(a),'axisobj')
            % find the axes and see if they're locked.
            axLegendOn(end+1) = ...
                    islegendon(get(a,'MyHGHandle'));
            axObjects = [axObjects a];
         end
      end
      
      % if there's no selected axes, see if there's a single
      % axis in the figure
      if isempty(axObjects)
         ax = get(myFig,'CurrentAxes');
         if isempty(ax)
            % no axes to add a legend to
            return
         else
            % act on the current axes
            
            % visibleAxes = findobj(myFig,...
            %         'Visible','on',...
            %         'Type','axes',...
            %         'HandleVisibility','on');
            % if visibleAxes == ax
               % we just have a single axis in this figure
               axObjects = getobj(ax);
               if isempty(axObjects)
                  axObjects = scribehandle(axisobj(ax));
               end
               axLegendOn = islegendon(ax);
            % else
            %    % multiple axes in the figure:  command is
            %    % ambiguous
            %    errordlg(['There are multiple axes in this' ...
            %               ' figure window.  ' 10 'Select the axes' ...
            %               ' to which you would like to' ...
            %               ' add a legend.'],'Error','modal');
            %    return
            % end
         end
      end
      
      if length(find(axLegendOn)) > length(axLegendOn)/2
         % over half are showing legends
         mShowLegendState = 'off';
      else
         mShowLegendState = 'on';
      end
      for a = axObjects
         domethod(a, 'showlegend', mShowLegendState);
      end
      
   else
      a = get(myFig,'CurrentAxes');
      if ~isempty(a)
         if ~ploteditOn
            plotedit(myFig,'on','silent')
         end
         axObj = getobj(a);
         if isempty(axObj)
            axObj = scribehandle(axisobj(a));
         end
         domethod(axObj, 'showlegend');
         if ~ploteditOn
            plotedit(myFig,'off','silent');
         end
      end
   end
case 'addaxes'
   putdowntext('axesstart');
   
case 'addtext'
   toolButton = findall(myFig,'ToolTip', 'Add text');
   putdowntext('textstart',toolButton);
case 'addarrow'
   toolButton = findall(myFig,'ToolTip', 'Add arrow');
   putdowntext('arrowstart',toolButton);
case 'addline'
   toolButton = findall(myFig,'ToolTip', 'Add line');
   putdowntext('linestart',toolButton);
   
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'zoomin'
   fixtoolbar(myFig);   
   switch zoom(myFig,'getmode')
      case {'off' 'out'}
         zoom(myFig,'inmode');
      case {'in' 'on'}
         zoom(myFig,'off');
   end
case 'zoomout'
   fixtoolbar(myFig);   
   switch zoom(myFig,'getmode')
      case {'on' 'off' 'in'}
         zoom(myFig,'outmode');
      case 'out'
         zoom(myFig,'off');
   end
case 'rotate3d'
   fixtoolbar(myFig);
   rotate3d(myFig);
end


function objectVector = LGetSelection(aFig)
objectVector = [];
aFigObjH = getobj(aFig);
if ~isempty(aFigObjH)
   dragBinH = aFigObjH.DragObjects;
   objectVector = dragBinH.Items;
end


function LUpdateLegend(objects)
parents = [];
for a = objects
   parents(end+1) = get(a,'Parent');
end
parents = findobj(unique(parents),'flat','Type','axes');
parents(find(strcmp(get(parents,'Tag'),'ScribeOverlayAxesActive'))) = [];
if ~isempty(parents)
   for ax = parents'
      legend(ax);
   end
end

function LSetFont(co,dlgtitle)
fontprops = {'FontName'...
           'FontUnits'...
           'FontSize'...
           'FontWeight'...
           'FontAngle'};
fontvals = get(co,fontprops);
c = reshape(cat(1,fontprops,fontvals),5,2);
s = struct(c{:});
s = uisetfont(s,dlgtitle);
if isstruct(s)
   set(co,s);
   if strcmp('axes',get(co,'Type'))
      legend(co);
   end
end
