# HG changeset patch
# User Ben Abbott  <bpabbott@mac.com>
# Date 1371816036 -28800
#      Fri Jun 21 20:00:36 2013 +0800
# Node ID 1dd095ff049741de3afe99eab443194fc8eccaff
# Parent  1d1f02e0f6b47b99a8c501952d457c02a9a20772
Use unmodified axes "position" and "outerposition" properties for legend().

legend.m: Preserve parent axes' initial "positon" and "outerposition" values.
Clear figure before each demo. Add demo.  (Bug # 36408).

diff --git a/scripts/plot/legend.m b/scripts/plot/legend.m
--- a/scripts/plot/legend.m
+++ b/scripts/plot/legend.m
@@ -259,7 +259,7 @@
         str = tolower (strtrim (arg));
         switch (str)
           case "off"
-            delete (hlegend);
+            delete (hlegend)
             return;
           case "hide"
             show = "off";
@@ -509,7 +509,7 @@
     if (isempty (hplots))
       if (! isempty (hlegend))
         fkids = get (fig, "children");
-        delete (fkids(fkids == hlegend));
+        delete_legend (fkids(fkids == hlegend));
         hlegend = [];
         hobjects = [];
         hplots  = [];
@@ -555,8 +555,16 @@
       unwind_protect
         set (ca(1), "units", "points");
         set (ca(1), "fontunits", "points");
-        ca_pos = get (ca(1), "position");
-        ca_outpos = get (ca(1), "outerposition");
+        if (isempty (hlegend) || ! isprop (hlegend, "unmodified_axes_position"))
+          unmodified_axes_position = get (ca(1), "position");
+          unmodified_axes_outerposition = get (ca(1), "outerposition");
+        else
+          unmodified_axes_position = get (hlegend, "unmodified_axes_position");
+          unmodified_axes_outerposition = get (hlegend, ...
+            "unmodified_axes_outerposition");
+        endif
+        ca_pos = unmodified_axes_position;
+        ca_outpos = unmodified_axes_outerposition;
         ca_fontsize = get (ca(1), "fontsize");
       unwind_protect_cleanup
         set (ca(1), "units", units);
@@ -567,7 +575,6 @@
       xpad = 2;
       ypad = 2;
 
-      ## Length of line segments in the legend in points
       linelength = 15;
 
       ## Create the axis first
@@ -667,6 +674,30 @@
         else
           lpos = [0, 0, num1 * xstep, num2 * ystep];
         endif
+
+        if (strcmp (get (fig, "__graphics_toolkit__"), "gnuplot"))
+          ## Gnuplot places the key (legend) at edge of the figure window.
+          ## OpenGL places the legend box at edge of the unmodified axes position.
+          if (isempty (strfind (position, "east")))
+            extra_offset = unmodified_axes_outerposition(1) + ...
+              unmodified_axes_outerposition(3) - ...
+              unmodified_axes_position(1) - ...
+              unmodified_axes_position(3);
+          else
+            extra_offset = unmodified_axes_position(1) - ...
+              unmodified_axes_outerposition(1);
+          endif
+          ## FIXME - the "fontsize" is added to match the behavior of OpenGL.
+          ## This implies that a change in fontsize should trigger a listener
+          ## to update the legend.  The "2" was determined using a long legend key
+          ## in the absence of any subplots.
+          extra_offset = extra_offset - 2 * fontsize;
+        else
+          extra_offset = 0;
+        endif
+        ## If subplots then ...
+        #extra_offset = - fontsize;
+
         switch (position)
           case "north"
             if (outside)
@@ -694,6 +725,7 @@
               lpos = [ca_outpos(1) + ca_outpos(3) - lpos(3) - ypad, ...
                       ca_pos(2) + (ca_pos(4) - lpos(4)) / 2, lpos(3), lpos(4)];
               new_pos = [ca_pos(1), ca_pos(2), ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) + ca_pos(3) - lpos(3) - ypad, ...
                       ca_pos(2) + (ca_pos(4) - lpos(4)) / 2, lpos(3), lpos(4)];
@@ -705,6 +737,8 @@
                       lpos(3), lpos(4)];
               new_pos = [ca_pos(1) + lpos(3), ca_pos(2), ...
                          ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(1) = new_pos(1) - extra_offset;
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) +  ypad, ...
                       ca_pos(2) + (ca_pos(4) - lpos(4)) / 2, lpos(3), lpos(4)];
@@ -714,6 +748,7 @@
               lpos = [ca_outpos(1) + ca_outpos(3) - lpos(3) - ypad, ...
                       ca_pos(2) + ca_pos(4) - lpos(4), lpos(3), lpos(4)];
               new_pos = [ca_pos(1), ca_pos(2), ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) + ca_pos(3) - lpos(3) - ypad, ...
                       ca_pos(2) + ca_pos(4) - lpos(4) - ypad, lpos(3), lpos(4)];
@@ -724,6 +759,8 @@
                       lpos(3), lpos(4)];
               new_pos = [ca_pos(1) + lpos(3), ca_pos(2), ...
                          ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(1) = new_pos(1) - extra_offset;
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) + ypad, ...
                       ca_pos(2) + ca_pos(4) - lpos(4) - ypad, lpos(3), lpos(4)];
@@ -734,6 +771,7 @@
                       ca_pos(2), lpos(3), lpos(4)];
               new_pos = [ca_pos(1), ca_pos(2), ...
                          ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) + ca_pos(3) - lpos(3) - ypad, ...
                       ca_pos(2) + ypad, lpos(3), lpos(4)];
@@ -743,6 +781,8 @@
               lpos = [ca_outpos(1) + ypad, ca_pos(2), lpos(3), lpos(4)];
               new_pos = [ca_pos(1) + lpos(3), ca_pos(2), ...
                          ca_pos(3) - lpos(3), ca_pos(4)];
+              new_pos(1) = new_pos(1) - extra_offset;
+              new_pos(3) = new_pos(3) + extra_offset;
             else
               lpos = [ca_pos(1) + ypad, ca_pos(2) + ypad, lpos(3), lpos(4)];
             endif
@@ -825,10 +865,28 @@
 
         ## Add an invisible text object to original axis
         ## that when it is destroyed will remove the legend
-        t1 = text (0, 0, "", "parent", ca(1), "tag", "legend",
-                   "handlevisibility", "off", "visible", "off",
-                   "xliminclude", "off", "yliminclude", "off");
-        set (t1, "deletefcn", {@deletelegend1, hlegend});
+        props = {"parent", ca(1), "tag", "legend", ...
+                 "handlevisibility", "off", "visible", "off", ...
+                 "xliminclude", "off", "yliminclude", "off"};
+        t1 = findall (ca(1), props{:}, "type", "text");
+        if (isempty (t1))
+          ht = findall (ca(1), "type", "text", props{3:end});
+          if (! isempty (ht))
+            set (ht, "deletefcn", "")
+            delete (ht);
+          endif
+          t1 = text (0, 0, "", props{:});
+          set (t1, "deletefcn", {@deletelegend1, hlegend});
+        endif
+        if (isprop (hlegend, "unmodified_axes_position"))
+          set (hlegend, "unmodified_axes_position", unmodified_axes_position)
+          set (hlegend, "unmodified_axes_outerposition", unmodified_axes_outerposition)
+        else
+          addproperty ("unmodified_axes_position", hlegend, "data", ...
+            unmodified_axes_position);
+          addproperty ("unmodified_axes_outerposition", hlegend, "data", ...
+            unmodified_axes_outerposition);
+        endif
 
         ## Resize the axis that the legend is attached to if the
         ## legend is "outside" the plot and create a listener to
@@ -846,9 +904,10 @@
           endfor
 
           set (hlegend, "deletefcn", {@deletelegend2, ca, ...
-                                      ca_pos, ca_outpos, t1, hplots});
+                                      unmodified_axes_position, ...
+                                      unmodified_axes_outerposition, t1, hplots});
           addlistener (hlegend, "visible", {@hideshowlegend, ca, ...
-                                            ca_pos, new_pos});
+                                            unmodified_axes_position, new_pos});
         else
           set (hlegend, "deletefcn", {@deletelegend2, ca, [], [], t1, hplots});
         endif
@@ -856,7 +915,12 @@
         if (addprops)
           addproperty ("edgecolor", hlegend, "color", [0, 0, 0]);
           addproperty ("textcolor", hlegend, "color", [0, 0, 0]);
-          addproperty ("location", hlegend, "radio", "north|south|east|west|{northeast}|southeast|northwest|southwest|northoutside|southoutside|eastoutside|westoutside|northeastoutside|southeastoutside|northwestoutside|southwestoutside");
+          locations = {"north", "south", "east", "west", "{northeast}", ...
+            "southeast", "northwest", "southwest", "northoutside", ...
+            "southoutside", "eastoutside", "westoutside", ...
+            "northeastoutside", "southeastoutside", "northwestoutside", ...
+            "southwestoutside"};
+          addproperty ("location", hlegend, "radio", strjoin (locations, "|"));
           addproperty ("orientation", hlegend, "radio",
                        "{vertical}|horizontal");
           addproperty ("string", hlegend, "any", text_strings);
@@ -904,6 +968,19 @@
     unwind_protect
       hax = getfield (get (h, "userdata"), "handle");
       [hplots, text_strings] = __getlegenddata__ (h);
+      position = get (h, "unmodified_axes_position");
+      outerposition = get (h, "unmodified_axes_outerposition");
+      units = get (hax, "units");
+      set (hax, "units", "points")
+      switch get (hax, "activepositionproperty")
+      case "position"
+        set (hax, "outerposition", outerposition)
+        set (hax, "position", position)
+      case "outerposition"
+        set (hax, "position", position)
+        set (hax, "outerposition", outerposition)
+      endswitch
+      set (hax, "units", units)
       h = legend (hax, hplots, get (h, "string"));
     unwind_protect_cleanup
       recursive = false;
@@ -1068,53 +1145,64 @@
 endfunction
 
 %!demo
+%! clf ()
 %! plot (rand (2));
 %! title ('legend called with cellstr and string inputs for labels');
 %! h = legend ({'foo'}, 'bar');
+%! legend location northeastoutside
 %! set (h, 'fontsize', 20)
 
 %!demo
+%! clf ()
 %! plot (rand (3));
 %! title ('legend() without inputs creates default labels');
-%! legend ();
+%! h = legend ();
+%! get (h, "string")
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:1;
 %! plot (x,x,';I am Blue;', x,2*x, x,3*x,';I am Red;');
+%! legend location northeastoutside
+%! # Placing legend inside should return axes to original size
+%! legend location northeast
 %! title ('Blue and Red keys, with Green missing');
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10, 1:10, fliplr (1:10));
 %! title ('incline is blue and decline is green');
 %! legend ({'I am blue', 'I am green'}, 'location', 'east');
+%! legend hide
+%! legend show
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10, 1:10, fliplr (1:10));
 %! title ('Legend with keys in horizontal orientation');
 %! legend ({'I am blue', 'I am green'}, 'location', 'east', 'orientation', 'horizontal');
 %! legend boxoff;
+%! legend boxon
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10, 1:10, fliplr (1:10));
 %! title ('Legend with box off');
 %! legend ({'I am blue', 'I am green'}, 'location', 'east');
 %! legend boxoff;
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10, 1:10, fliplr (1:10));
 %! title ('Legend with text to the right of key');
 %! legend ({'I am blue', 'I am green'}, 'location', 'east');
 %! legend right;
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10, 1:10, fliplr (1:10));
-%! title ('Using properties to have legend text shown to the right of key');
+%! title ({'Use properties to place legend text to the right of key', ...
+%!         'Legend text color is magenta'});
 %! h = legend ({'I am blue', 'I am green'}, 'location', 'east');
 %! legend ('left');
 %! set (h, 'textposition', 'right');
@@ -1128,37 +1216,38 @@
 %! legend hide;
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:1;
 %! plot (x,x,';I am Blue;', x,2*x,';I am Green;', x,3*x,';I am Red;');
-%! title ('labels embedded in call to plot');
+%! title ({'Labels are embedded in call to plot', ...
+%!         'Legend is hidden and then shown'});
 %! legend boxon
 %! legend hide
 %! legend show
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:1;
 %! plot (x, x, ';\alpha;',  ...
 %!       x, 2*x, ';\beta=2\alpha;',  ...
 %!       x, 3*x, ';\gamma=3\alpha;');
-%! title ('labels with interpreted Greek text');
+%! title ('Labels with interpreted Greek text');
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (rand (2));
 %! title ('Labels with TeX interpreter turned off');
 %! h = legend ('Hello_World', 'foo^bar');
 %! set (h, 'interpreter', 'none');
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (1:10, 1:10);
 %! title ('a very long label can sometimes cause problems');
 %! legend ('hello very big world', 'location', 'northeastoutside');
 
 %!demo
-%! clf;
+%! clf ();
 %! labels = {};
 %! colororder = get (gca, 'colororder');
 %! for i = 1:5
@@ -1173,7 +1262,7 @@
 %! legend (labels, 'location', 'southoutside');
 
 %!demo
-%! clf;
+%! clf ();
 %! x = linspace (0, 10);
 %! plot (x, x);
 %! hold on;
@@ -1183,21 +1272,21 @@
 %! hold off;
 
 %!demo
-%! clf;
+%! clf ();
 %! x = linspace (0, 10);
 %! plot (x, x, x, x.^2);
 %! title ('First created object gets first label');
 %! legend ('linear');
 
 %!demo
-%! clf;
+%! clf ();
 %! x = linspace (0, 10);
 %! plot (x, x, x, x.^2);
 %! title ('Labels are applied in order of object creation');
 %! legend ('linear', 'quadratic');
 
 %!demo
-%! clf;
+%! clf ();
 %! rand_2x3_data1 = [0.341447, 0.171220, 0.284370; 0.039773, 0.731725, 0.779382];
 %! bar (rand_2x3_data1);
 %! ylim ([0 1.0]);
@@ -1205,7 +1294,7 @@
 %! legend ({'1st Bar', '2nd Bar', '3rd Bar'});
 
 %!demo
-%! clf;
+%! clf ();
 %! rand_2x3_data2 = [0.44804, 0.84368, 0.23012; 0.72311, 0.58335, 0.90531];
 %! bar (rand_2x3_data2);
 %! ylim ([0 1.2]);
@@ -1214,14 +1303,14 @@
 %! legend right;
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:0.1:7;
 %! h = plot (x,sin(x), x,cos(x), x,sin(x.^2/10), x,cos(x.^2/10));
 %! title ('Only the sin() objects have keylabels');
 %! legend (h([1, 3]), {'sin (x)', 'sin (x^2/10)'}, 'location', 'southwest');
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:0.1:10;
 %! plot (x, sin (x), ';sin (x);');
 %! hold all;
@@ -1230,7 +1319,7 @@
 %! title ('legend constructed from multiple plot calls');
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:0.1:10;
 %! plot (x, sin (x), ';sin (x);');
 %! hold all;
@@ -1240,7 +1329,7 @@
 %! legend ({'Sine', 'Cosine'}, 'location', 'northeastoutside');
 
 %!demo
-%! clf;
+%! clf ();
 %! x = 0:10;
 %! plot (x, rand (11));
 %! xlabel ('Indices');
@@ -1251,7 +1340,7 @@
 %! axis ([0, 10, 0 1]);
 
 %!demo
-%! clf;
+%! clf ();
 %! x = (1:5)';
 %! subplot (2,2,1);
 %!  plot (x, rand (numel (x)));
@@ -1267,12 +1356,13 @@
 %!  legend (cellstr (num2str (x)), 'location', 'southeastoutside');
 
 %!demo
-%! clf;
+%! clf ();
 %! plot (rand (2));
 %! title ('legend() will warn if extra labels are specified');
 %! legend ('Hello', 'World', 'interpreter', 'foobar');
 
 %!demo
+%! clf ();
 %! x = 0:10;
 %! y1 = rand (size (x));
 %! y2 = rand (size (x));
@@ -1281,6 +1371,7 @@
 %! legend ([h1, h2], {'Blue', 'Green'}, 'location', 'south');
 
 %!demo
+%! clf ();
 %! x = 0:10;
 %! y1 = rand (size (x));
 %! y2 = rand (size (x));
@@ -1289,6 +1380,7 @@
 %! legend ({'Blue', 'Green'}, 'location', 'south');
 
 %!demo
+%! clf ();
 %! x = 0:10;
 %! y1 = rand (size (x));
 %! y2 = rand (size (x));
@@ -1296,3 +1388,36 @@
 %! title ('plotyy legend test #3: Blue and Green labels');
 %! legend ('Blue', 'Green', 'location', 'south');
 
+%!demo % bug 36408
+%! clf ();
+%! option = "right";
+%! subplot (3,1,1)
+%! plot (rand (1,4));
+%! legend ({"1"}, "location", "northeastoutside")
+%! legend (option)
+%! subplot (3,1,2)
+%! plot (rand (1,4));
+%! legend ({"1234567890"}, "location", "eastoutside")
+%! legend (option)
+%! subplot (3,1,3)
+%! plot (rand (1,4));
+%! legend ({"12345678901234567890"}, "location", "southeastoutside")
+%! legend (option)
+
+%!demo % bug 36408
+%! clf ();
+%! option = "right";
+%! subplot (3,1,1)
+%! plot (rand (1,4));
+%! legend ({"1"}, "location", "northwestoutside")
+%! legend (option)
+%! subplot (3,1,2)
+%! plot (rand (1,4));
+%! legend ({"1234567890"}, "location", "westoutside")
+%! legend (option)
+%! subplot (3,1,3)
+%! plot (rand (1,4));
+%! legend ({"12345678901234567890"}, "location", "southwestoutside")
+%! legend (option)
+
+
