Changeset 18904


Ignore:
Timestamp:
12/02/14 11:40:53 (10 years ago)
Author:
Mathieu Morlighem
Message:

CHG: upgrading export_fig for hg2 support and matlab R2014b

Location:
issm/trunk-jpl/externalpackages/export_fig
Files:
7 added
11 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/externalpackages/export_fig/copyfig.m

    r11803 r18904  
    2121end
    2222% Is there a legend?
    23 if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend'))
     23if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
    2424    % Safe to copy using copyobj
    2525    fh = copyobj(fh, 0);
     
    3131    delete(tmp_nam);
    3232end
    33 return
     33end
  • issm/trunk-jpl/externalpackages/export_fig/eps2pdf.m

    r11803 r18904  
    8484    try
    8585        % Convert to pdf using ghostscript
    86         [status message] = ghostscript(options);
    87     catch
     86        [status, message] = ghostscript(options);
     87    catch me
    8888        % Delete the intermediate file
    8989        delete(tmp_nam);
    90         rethrow(lasterror);
     90        rethrow(me);
    9191    end
    9292    % Delete the intermediate file
     
    9797    options = [options ' -f "' source '"'];
    9898    % Convert to pdf using ghostscript
    99     [status message] = ghostscript(options);
     99    [status, message] = ghostscript(options);
    100100end
    101101% Check for error
     
    108108    end
    109109end
    110 return
     110end
    111111
    112112% Function to return (and create, where necessary) the font path
     
    132132end
    133133user_string('gs_font_path', fp);
    134 return
     134end
  • issm/trunk-jpl/externalpackages/export_fig/export_fig.m

    r14174 r18904  
    1313%   export_fig ... -a<val>
    1414%   export_fig ... -q<val>
     15%   export_fig ... -p<val>
    1516%   export_fig ... -<renderer>
    1617%   export_fig ... -<colorspace>
     
    8586%                  made transparent (png, pdf and eps output only).
    8687%   -m<val> - option where val indicates the factor to magnify the
    87 %             on-screen figure dimensions by when generating bitmap
     88%             on-screen figure pixel dimensions by when generating bitmap
    8889%             outputs. Default: '-m1'.
    8990%   -r<val> - option val indicates the resolution (in pixels per inch) to
    90 %             export bitmap outputs at, keeping the dimensions of the
    91 %             on-screen figure. Default: sprintf('-r%g', get(0,
    92 %             'ScreenPixelsPerInch')). Note that the -m and -r options
    93 %             change the same property.
     91%             export bitmap and vector outputs at, keeping the dimensions
     92%             of the on-screen figure. Default: '-r864' (for vector output
     93%             only). Note that the -m option overides the -r option for
     94%             bitmap outputs only.
    9495%   -native - option indicating that the output resolution (when outputting
    9596%             a bitmap format) should be such that the vertical resolution
     
    118119%             sometimes give a smaller file size than the default lossy
    119120%             compression, depending on the type of images.
     121%   -p<val> - option to add a border of width val to eps and pdf files,
     122%             where val is in units of the intermediate eps file. Default:
     123%             0 (i.e. no padding).
    120124%   -append - option indicating that if the file (pdfs only) already
    121125%             exists, the figure is to be appended as a new page, instead
     
    133137%
    134138%   Some helpful examples and tips can be found at:
    135 %      http://sites.google.com/site/oliverwoodford/software/export_fig
     139%      https://github.com/ojwoodford/export_fig
    136140%
    137141%   See also PRINT, SAVEAS.
    138142
    139 % Copyright (C) Oliver Woodford 2008-2012
     143% Copyright (C) Oliver Woodford 2008-2014
    140144
    141145% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
     
    168172% 12/12/12: Add support for isolating uipanels. Thanks to michael for
    169173%           suggesting it.
     174% 25/09/13: Add support for changing resolution in vector formats. Thanks
     175%           to Jan Jaap Meijer for suggesting it.
     176% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
     177%           for suggesting it.
    170178
    171179function [im, alpha] = export_fig(varargin)
     
    217225end
    218226% Set all axes limit and tick modes to manual, so the limits and ticks can't change
    219 set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
     227set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
     228set_tick_mode(Hlims, 'X');
     229set_tick_mode(Hlims, 'Y');
     230set_tick_mode(Hlims, 'Z');
    220231% Set to print exactly what is there
    221232set(fig, 'InvertHardcopy', 'off');
     
    289300        % Crop the background
    290301        if options.crop
    291             [alpha, v] = crop_background(alpha, 0);
     302            [alpha, v] = crop_borders(alpha, 0, 1);
    292303            A = A(v(1):v(2),v(3):v(4),:);
    293304        end
     
    336347        % Crop the background
    337348        if options.crop
    338             A = crop_background(A, tcol);
     349            A = crop_borders(A, tcol, 1);
    339350        end
    340351        % Downscale the image
     
    406417    end
    407418    % Generate the options for print
    408     p2eArgs = {renderer};
     419    p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
    409420    if options.colourspace == 1
    410421        p2eArgs = [p2eArgs {'-cmyk'}];
     
    415426    try
    416427        % Generate an eps
    417         print2eps(tmp_nam, fig, p2eArgs{:});
     428        print2eps(tmp_nam, fig, options.bb_padding, p2eArgs{:});
    418429        % Remove the background, if desired
    419430        if options.transparent && ~isequal(get(fig, 'Color'), 'none')
    420             eps_remove_background(tmp_nam);
     431            eps_remove_background(tmp_nam, 1 + using_hg2(fig));
    421432        end
    422433        % Add a bookmark to the PDF if desired
     
    465476    end
    466477end
    467 return
     478end
    468479
    469480function [fig, options] = parse_args(nout, varargin)
     
    485496                 'im', nout == 1, ...
    486497                 'alpha', nout == 2, ...
    487                  'aa_factor', 3, ...
    488                  'magnify', 1, ...
     498                 'aa_factor', 0, ...
     499                 'bb_padding', 0, ...
     500                 'magnify', [], ...
     501                 'resolution', [], ...
    489502                 'bookmark', false, ...
    490503                 'quality', []);
     
    535548                    native = true;
    536549                otherwise
    537                     val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
     550                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
    538551                    if ~isscalar(val)
    539552                        error('option %s not recognised', varargin{a});
     
    543556                            options.magnify = val;
    544557                        case 'r'
    545                             options.magnify = val ./ get(0, 'ScreenPixelsPerInch');
     558                            options.resolution = val;
    546559                        case 'q'
    547560                            options.quality = max(val, 0);
     561                        case 'p'
     562                            options.bb_padding = val;
    548563                    end
    549564            end
     
    573588end
    574589
     590% Set default anti-aliasing now we know the renderer
     591if options.aa_factor == 0
     592    options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on')) | (options.renderer == 3));
     593end
     594
     595% Convert user dir '~' to full path
     596if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
     597    options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
     598end
     599
     600% Compute the magnification and resolution
     601if isempty(options.magnify)
     602    if isempty(options.resolution)
     603        options.magnify = 1;
     604        options.resolution = 864;
     605    else
     606        options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
     607    end
     608elseif isempty(options.resolution)
     609    options.resolution = 864;
     610end 
     611
    575612% Check we have a figure handle
    576613if isempty(fig)
     
    584621
    585622% Check whether transparent background is wanted (old way)
    586 if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none')
     623if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
    587624    options.transparent = true;
    588625end
     
    632669    end
    633670end
    634 return
     671end
    635672
    636673function A = downsize(A, factor)
     
    659696    A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
    660697end
    661 return
     698end
    662699
    663700function A = rgb2grey(A)
    664701A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
    665 return
     702end
    666703
    667704function A = check_greyscale(A)
     
    672709    A = A(:,:,1); % Save only one channel for 8-bit output
    673710end
    674 return
    675 
    676 function [A, v] = crop_background(A, bcol)
    677 % Map the foreground pixels
    678 [h, w, c] = size(A);
    679 if isscalar(bcol) && c > 1
    680     bcol = bcol(ones(1, c));
    681 end
    682 bail = false;
    683 for l = 1:w
    684     for a = 1:c
    685         if ~all(A(:,l,a) == bcol(a))
    686             bail = true;
    687             break;
    688         end
    689     end
    690     if bail
    691         break;
    692     end
    693 end
    694 bail = false;
    695 for r = w:-1:l
    696     for a = 1:c
    697         if ~all(A(:,r,a) == bcol(a))
    698             bail = true;
    699             break;
    700         end
    701     end
    702     if bail
    703         break;
    704     end
    705 end
    706 bail = false;
    707 for t = 1:h
    708     for a = 1:c
    709         if ~all(A(t,:,a) == bcol(a))
    710             bail = true;
    711             break;
    712         end
    713     end
    714     if bail
    715         break;
    716     end
    717 end
    718 bail = false;
    719 for b = h:-1:t
    720     for a = 1:c
    721         if ~all(A(b,:,a) == bcol(a))
    722             bail = true;
    723             break;
    724         end
    725     end
    726     if bail
    727         break;
    728     end
    729 end
    730 % Crop the background, leaving one boundary pixel to avoid bleeding on
    731 % resize
    732 v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
    733 A = A(v(1):v(2),v(3):v(4),:);
    734 return
    735 
    736 function eps_remove_background(fname)
     711end
     712
     713function eps_remove_background(fname, count)
    737714% Remove the background of an eps file
    738715% Open the file
     
    742719end
    743720% Read the file line by line
    744 while true
     721while count
    745722    % Get the next line
    746723    l = fgets(fh);
     
    749726    end
    750727    % Check if the line contains the background rectangle
    751     if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1)
     728    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
    752729        % Set the line to whitespace and quit
    753730        l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
    754731        fseek(fh, -numel(l), 0);
    755732        fprintf(fh, l);
    756         break;
     733        % Reduce the count
     734        count = count - 1;
    757735    end
    758736end
    759737% Close the file
    760738fclose(fh);
    761 return
     739end
    762740
    763741function b = isvector(options)
    764742b = options.pdf || options.eps;
    765 return
     743end
    766744
    767745function b = isbitmap(options)
    768746b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
    769 return
     747end
    770748
    771749% Helper function
     
    774752    A = {A};
    775753end
    776 return
     754end
    777755
    778756function add_bookmark(fname, bookmark_text)
     
    808786end
    809787fclose(fh);
    810 return
     788end
     789
     790function set_tick_mode(Hlims, ax)
     791% Set the tick mode of linear axes to manual
     792% Leave log axes alone as these are tricky
     793M = get(Hlims, [ax 'Scale']);
     794if ~iscell(M)
     795    M = {M};
     796end
     797M = cellfun(@(c) strcmp(c, 'linear'), M);
     798set(Hlims(M), [ax 'TickMode'], 'manual');
     799end
  • issm/trunk-jpl/externalpackages/export_fig/fix_lines.m

    r10635 r18904  
    1 function fix_lines(fname, fname2)
    21%FIX_LINES  Improves the line style of eps files generated by print
    32%
     
    54%   fix_lines fname
    65%   fix_lines fname fname2
     6%   fstrm_out = fixlines(fstrm_in)
    77%
    88% This function improves the style of lines in eps files generated by
     
    1616% information.
    1717%
    18 % IN:
     18%IN:
    1919%   fname - Name or path of source eps file.
    2020%   fname2 - Name or path of destination eps file. Default: same as fname.
     21%   fstrm_in - File contents of a MATLAB-generated eps file.
     22%
     23%OUT:
     24%   fstrm_out - Contents of the eps file with line styles fixed.
    2125
    22 % Copyright: (C) Oliver Woodford, 2008-2010
     26% Copyright: (C) Oliver Woodford, 2008-2014
    2327
    2428% The idea of editing the EPS file to change line styles comes from Jiro
     
    3438% opened.
    3539
    36 % Read in the file
    37 fh = fopen(fname, 'r');
    38 if fh == -1
    39     error('File %s not found.', fname);
     40function fstrm = fix_lines(fstrm, fname2)
     41
     42if nargout == 0 || nargin > 1
     43    if nargin < 2
     44        % Overwrite the input file
     45        fname2 = fstrm;
     46    end
     47    % Read in the file
     48    fstrm = read_write_entire_textfile(fstrm);
    4049end
    41 try
    42     fstrm = fread(fh, '*char')';
    43 catch ex
    44     fclose(fh);
    45     rethrow(ex);
    46 end
    47 fclose(fh);
    4850
    4951% Move any embedded fonts after the postscript header
     
    5153    % Find the start and end of the header
    5254    ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
    53     [ind2 ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
     55    [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
    5456    % Put the header first
    5557    if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
     
    6769ind = sort(ind);
    6870% Find line width commands
    69 [ind2 ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
     71[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
    7072% Go through each line style section and swap with any line width commands
    7173% near by
     
    114116% Isolate line style definition section
    115117first_sec = strfind(fstrm, '% line types:');
    116 [second_sec remaining] = strtok(fstrm(first_sec+1:end), '/');
    117 [remaining remaining] = strtok(remaining, '%');
     118[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
     119[remaining, remaining] = strtok(remaining, '%');
    118120
    119121% Define the new styles, including the new GR format
     
    132134             '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
    133135
    134 if nargin < 2
    135     % Overwrite the input file
    136     fname2 = fname;
     136% Construct the output
     137fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
     138
     139% Write the output file
     140if nargout == 0 || nargin > 1
     141    read_write_entire_textfile(fname2, fstrm);
    137142end
    138 
    139 % Save the file with the section replaced
    140 fh = fopen(fname2, 'w');
    141 if fh == -1
    142     error('Unable to open %s for writing.', fname2);
    143143end
    144 try
    145     fwrite(fh, fstrm(1:first_sec), 'char*1');
    146     fwrite(fh, second_sec, 'char*1');
    147     fprintf(fh, '%s\r', new_style{:});
    148     fwrite(fh, remaining, 'char*1');
    149 catch ex
    150     fclose(fh);
    151     rethrow(ex);
    152 end
    153 fclose(fh);
    154 return
  • issm/trunk-jpl/externalpackages/export_fig/ghostscript.m

    r14174 r18904  
    2020%   result - Output from ghostscript.
    2121
    22 % Copyright: Oliver Woodford, 2009-2010
     22% Copyright: Oliver Woodford, 2009-2013
    2323
    2424% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
     
    3232% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
    3333% Punnoose for highlighting the issue.
     34% 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
     35% Steinbring for proposing the fix.
     36% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
     37% for the fix.
     38% 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen
     39% Vermeer for raising the issue.
    3440
    3541function varargout = ghostscript(cmd)
     42% Initialize any required system calls before calling ghostscript
     43shell_cmd = '';
     44if isunix
     45    shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
     46end
     47if ismac
     48    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
     49end
    3650% Call ghostscript
    37 [varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd));
    38 return
     51[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
     52end
    3953
    4054function path_ = gs_path
     
    8599    end
    86100else
    87     bin = {'/usr/bin/gs', '/usr/local/bin/gs'};
    88     for a = 1:numel(bin)
    89         path_ = bin{a};
     101    executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
     102    for a = 1:numel(executable)
     103        path_ = executable{a};
    90104        if check_store_gs_path(path_)
    91105            return
     
    119133end
    120134error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
     135end
    121136
    122137function good = check_store_gs_path(path_)
     
    128143% Update the current default path to the path found
    129144if ~user_string('ghostscript', path_)
    130     warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.');
     145    warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'));
    131146    return
    132147end
    133 return
     148end
    134149
    135150function good = check_gs_path(path_)
    136151% Check the path is valid
    137 [good, message] = system(sprintf('"%s" -h', path_));
     152shell_cmd = '';
     153if ismac
     154    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
     155end
     156[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
    138157good = good == 0;
    139 return
     158end
  • issm/trunk-jpl/externalpackages/export_fig/isolate_axes.m

    r14174 r18904  
    1919%    fh - The handle of the created figure.
    2020
    21 % Copyright (C) Oliver Woodford 2011-2012
     21% Copyright (C) Oliver Woodford 2011-2013
    2222
    2323% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
     
    2626% 12/12/12 - Add support for isolating uipanels. Thanks to michael for
    2727% suggesting it.
     28% 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!).
     29% 05/12/13 - Bug fix to axes having different units. Thanks to Remington
     30% Reid for reporting the issue.
    2831
    2932function fh = isolate_axes(ah, vis)
     
    7275nLeg = numel(lh);
    7376if nLeg > 0
     77    set([ah(:); lh(:)], 'Units', 'normalized');
    7478    ax_pos = get(ah, 'OuterPosition');
    7579    if nAx > 1
     
    8286    end
    8387    leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
    84     for a = 1:nAx
    85             % Overlap test
    86             ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &...
    87                          leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))];
    88     end
     88    ax_pos = shiftdim(ax_pos, -1);
     89    % Overlap test
     90    M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
     91        bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
     92        bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
     93        bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
     94    ah = [ah; lh(any(M, 2))];
    8995end
    9096% Get all the objects in the figure
     
    9298% Delete everything except for the input objects and associated items
    9399delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
    94 return
     100end
    95101
    96102function ah = allchildren(ah)
    97 ah = allchild(ah);
     103ah = findall(ah);
    98104if iscell(ah)
    99105    ah = cell2mat(ah);
    100106end
    101107ah = ah(:);
    102 return
     108end
    103109
    104110function ph = allancestors(ah)
     
    111117    end
    112118end
    113 return
     119end
  • issm/trunk-jpl/externalpackages/export_fig/pdf2eps.m

    r7182 r18904  
    2525options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
    2626% Convert to eps using pdftops
    27 [status message] = pdftops(options);
     27[status, message] = pdftops(options);
    2828% Check for error
    2929if status
     
    4848end
    4949fclose(fid);
    50 return
     50end
    5151
  • issm/trunk-jpl/externalpackages/export_fig/pdftops.m

    r14174 r18904  
    2828% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
    2929% under linux.
     30% 23/01/2014 - Add full path to pdftops.txt in warning.
    3031
    3132% Call pdftops
    3233[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
    33 return
     34end
    3435
    3536function path_ = xpdf_path
     
    8586end
    8687error('pdftops executable not found.');
     88end
    8789
    8890function good = check_store_xpdf_path(path_)
     
    9496% Update the current default path to the path found
    9597if ~user_string('pdftops', path_)
    96     warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.');
     98    warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
    9799    return
    98100end
    99 return
     101end
    100102
    101103function good = check_xpdf_path(path_)
    102104% Check the path is valid
    103 [good message] = system(sprintf('"%s" -h', path_));
     105[good, message] = system(sprintf('"%s" -h', path_));
    104106% system returns good = 1 even when the command runs
    105107% Look for something distinct in the help text
    106108good = ~isempty(strfind(message, 'PostScript'));
    107 return
     109end
  • issm/trunk-jpl/externalpackages/export_fig/print2array.m

    r14174 r18904  
    7171    % Print to eps file
    7272    tmp_eps = [tempname '.eps'];
    73     print2eps(tmp_eps, fig, renderer, '-loose');
     73    print2eps(tmp_eps, fig, 0, renderer, '-loose');
    7474    try
    7575        % Initialize the command to export to tiff using ghostscript
     
    172172    end
    173173end
    174 return
     174end
    175175
    176176% Function to return (and create, where necessary) the font path
     
    196196end
    197197user_string('gs_font_path', fp);
    198 return
     198end
  • issm/trunk-jpl/externalpackages/export_fig/print2eps.m

    r15310 r18904  
    44%   print2eps filename
    55%   print2eps(filename, fig_handle)
    6 %   print2eps(filename, fig_handle, options)
     6%   print2eps(filename, fig_handle, bb_padding)
     7%   print2eps(filename, fig_handle, bb_padding, options)
    78%
    89% This function saves a figure as an eps file, with two improvements over
     
    1819%              ".eps" extension is added if not there already. If a path is
    1920%              not specified, the figure is saved in the current directory.
    20 %   fig_handle - The handle of the figure to be saved. Default: gcf.
     21%   fig_handle - The handle of the figure to be saved. Default: gcf().
     22%   bb_padding - Scalar value of amount of padding to add to border around
     23%                the figure, in points. Can be negative as well as
     24%                positive. Default: 0.
    2125%   options - Additional parameter strings to be passed to print.
    2226
    23 % Copyright (C) Oliver Woodford 2008-2013
     27% Copyright (C) Oliver Woodford 2008-2014
    2428
    2529% The idea of editing the EPS file to change line styles comes from Jiro
     
    5054% 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
    5155%           for reporting the issue.
    52 
    53 function print2eps(name, fig, varargin)
     56% 23/07/13: Bug fix to font swapping. Thanks to George for reporting the
     57%           issue.
     58% 13/08/13: Fix MATLAB feature of not exporting white lines correctly.
     59%           Thanks to Sebastian Heßlinger for reporting it.
     60
     61function print2eps(name, fig, bb_padding, varargin)
    5462options = {'-depsc2'};
    55 if nargin < 2
    56     fig = gcf;
    57 elseif nargin > 2
     63if nargin > 3
    5864    options = [options varargin];
     65elseif nargin < 3
     66    bb_padding = 0;
     67    if nargin < 2
     68        fig = gcf();
     69    end
    5970end
    6071% Construct the filename
     
    6273    name = [name '.eps']; % Add the missing extension
    6374end
     75% Set paper size
     76old_pos_mode = get(fig, 'PaperPositionMode');
     77old_orientation = get(fig, 'PaperOrientation');
     78set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
    6479% Find all the used fonts in the figure
    6580font_handles = findall(fig, '-property', 'FontName');
     
    95110    font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
    96111    font_swap{2,a} = matlab_fonts{unused_fonts(a)};
    97     font_swap{3,a} = fonts{font_swap{1,end}(1)};
     112    font_swap{3,a} = fonts{font_swap{1,a}(1)};
    98113    fonts_new(font_swap{1,a}) = {font_swap{2,a}};
    99114end
     
    126141    update = reshape(update(M), 1, []);
    127142end
    128 % Set paper size
    129 old_pos_mode = get(fig, 'PaperPositionMode');
    130 old_orientation = get(fig, 'PaperOrientation');
    131 set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
    132143% MATLAB bug fix - black and white text can come out inverted sometimes
    133144% Find the white and black text
     
    143154set(black_text_handles, 'Color', [0 0 0] + eps);
    144155set(white_text_handles, 'Color', [1 1 1] - eps);
     156% MATLAB bug fix - white lines can come out funny sometimes
     157% Find the white lines
     158white_line_handles = findobj(fig, 'Type', 'line');
     159M = get(white_line_handles, 'Color');
     160if iscell(M)
     161    M = cell2mat(M);
     162end
     163white_line_handles = white_line_handles(sum(M, 2) == 3);
     164% Set the line color slightly off white
     165set(white_line_handles, 'Color', [1 1 1] - 0.00001);
    145166% Print to eps file
    146167print(fig, options{:}, name);
    147 % Reset the font colors
     168% Reset the font and line colors
    148169set(black_text_handles, 'Color', [0 0 0]);
    149170set(white_text_handles, 'Color', [1 1 1]);
     171set(white_line_handles, 'Color', [1 1 1]);
    150172% Reset paper size
    151173set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
    152 % Correct the fonts
     174% Reset the font names in the figure
    153175if ~isempty(font_swap)
    154     % Reset the font names in the figure
    155176    for a = update
    156177        set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
    157178    end
    158     % Replace the font names in the eps file
    159     font_swap = font_swap(2:3,:);
    160     try
    161         swap_fonts(name, font_swap{:});
    162     catch
    163         warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
    164         return
    165     end
    166 end
    167 % Fix the line styles
     179end
     180% Do post-processing on the eps file
    168181try
    169     fix_lines(name);
     182    fstrm = read_write_entire_textfile(name);
    170183catch
    171     warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
    172 end
    173 return
    174 
    175 function swap_fonts(fname, varargin)
    176 % Read in the file
    177 fh = fopen(fname, 'r');
    178 if fh == -1
    179     error('File %s not found.', fname);
    180 end
    181 try
    182     fstrm = fread(fh, '*char')';
    183 catch ex
    184     fclose(fh);
    185     rethrow(ex);
    186 end
    187 fclose(fh);
    188 
     184    warning('Loading EPS file failed, so unable to perform post-processing. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
     185    return
     186end
    189187% Replace the font names
    190 for a = 1:2:numel(varargin)
    191     fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1})));
    192 end
    193 
    194 % Write out the updated file
    195 fh = fopen(fname, 'w');
    196 if fh == -1
    197     error('Unable to open %s for writing.', fname2);
    198 end
    199 try
    200     fwrite(fh, fstrm, 'char*1');
    201 catch ex
    202     fclose(fh);
    203     rethrow(ex);
    204 end
    205 fclose(fh);
    206 return
     188if ~isempty(font_swap)
     189    for a = 1:size(font_swap, 2)
     190        %fstrm = regexprep(fstrm, [font_swap{1,a} '-?[a-zA-Z]*\>'], font_swap{3,a}(~isspace(font_swap{3,a})));
     191        fstrm = regexprep(fstrm, font_swap{2,a}, font_swap{3,a}(~isspace(font_swap{3,a})));
     192    end
     193end
     194if using_hg2(fig)
     195    % Convert miter joins to line joins
     196    fstrm = regexprep(fstrm, '10.0 ML\n', '1 LJ\n');
     197    % Move the bounding box to the top of the file
     198    [s, e] = regexp(fstrm, '%%BoundingBox: [\w\s()]*%%');
     199    if numel(s) == 2
     200        fstrm = fstrm([1:s(1)-1 s(2):e(2)-2 e(1)-1:s(2)-1 e(2)-1:end]);
     201    end
     202else
     203    % Fix the line styles
     204    fstrm = fix_lines(fstrm);
     205end
     206% Apply the bounding box padding
     207if bb_padding
     208    add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + [-bb_padding -bb_padding bb_padding bb_padding]);
     209    fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
     210end
     211% Write out the fixed eps file
     212read_write_entire_textfile(name, fstrm);
     213end
  • issm/trunk-jpl/externalpackages/export_fig/user_string.m

    r15310 r18904  
    8585    fclose(fid);
    8686end
    87 return
     87end
Note: See TracChangeset for help on using the changeset viewer.