Ignore:
Timestamp:
2017-10-09T14:13:54+02:00 (7 years ago)
Author:
bastiK
Message:

see #15273 - extract rendering code to new class

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/gui/mappaint/RenderingCLI.java

    r12936 r12963  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
    6 import java.awt.Graphics2D;
    7 import java.awt.Point;
    8 import java.awt.image.BufferedImage;
    9 import java.io.File;
     6import java.awt.Dimension;
    107import java.io.FileInputStream;
    118import java.io.FileNotFoundException;
    129import java.io.IOException;
    1310import java.util.ArrayList;
    14 import java.util.HashMap;
    1511import java.util.List;
    1612import java.util.Locale;
    17 import java.util.Map;
    1813import java.util.Optional;
    1914import java.util.function.Supplier;
    2015import java.util.logging.Level;
    21 
    22 import javax.imageio.ImageIO;
    2316
    2417import org.openstreetmap.gui.jmapviewer.OsmMercator;
     
    3326import org.openstreetmap.josm.data.coor.conversion.LatLonParser;
    3427import org.openstreetmap.josm.data.osm.DataSet;
    35 import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
    36 import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
    37 import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
    38 import org.openstreetmap.josm.data.preferences.sources.SourceType;
    3928import org.openstreetmap.josm.data.projection.Projection;
    4029import org.openstreetmap.josm.data.projection.Projections;
    41 import org.openstreetmap.josm.gui.NavigatableComponent;
    42 import org.openstreetmap.josm.gui.mappaint.StyleSetting.BooleanStyleSetting;
    43 import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
     30import org.openstreetmap.josm.gui.mappaint.RenderingHelper.StyleData;
    4431import org.openstreetmap.josm.io.IllegalDataException;
    4532import org.openstreetmap.josm.io.OsmReader;
     
    142129
    143130    /**
    144      * Data class to save style settings along with the corresponding style url.
    145      */
    146     private static class StyleData {
    147         public String styleUrl;
    148         public Map<String, String> settings = new HashMap<>();
    149     }
    150 
    151     /**
    152131     * Data class to hold return values for {@link #determineRenderingArea(DataSet)}.
    153132     *
     
    156135    static class RenderingArea {
    157136        public Bounds bounds;
    158         public ProjectionBounds projBounds;
    159137        public double scale; // in east-north units per pixel (unlike the --scale option, which is in meter per meter)
    160138    }
     
    174152            parseArguments(argArray);
    175153            initialize();
    176             run();
     154            DataSet ds = loadDataset();
     155            RenderingArea area = determineRenderingArea(ds);
     156            RenderingHelper rh = new RenderingHelper(ds, area.bounds, area.scale, argStyles);
     157            rh.setOutputFile(argOutput);
     158            checkPreconditions(rh);
     159            rh.render();
    177160        } catch (FileNotFoundException e) {
    178161            if (Logging.isDebugEnabled()) {
     
    551534        RenderingArea ra = new RenderingArea();
    552535        ra.bounds = bounds;
    553         ra.projBounds = pb;
    554536        ra.scale = scale;
    555537        return ra;
    556538    }
    557539
    558     private void run() throws FileNotFoundException, IllegalDataException, IOException {
    559 
     540    private DataSet loadDataset() throws FileNotFoundException, IllegalDataException {
    560541        if (argInput == null) {
    561542            throw new IllegalArgumentException(tr("Missing argument - input data file ({0})", "--input|-i"));
    562543        }
    563         DataSet ds;
    564544        try {
    565             ds = OsmReader.parseDataSet(new FileInputStream(argInput), null);
     545            return OsmReader.parseDataSet(new FileInputStream(argInput), null);
    566546        } catch (IllegalDataException e) {
    567547            throw new IllegalDataException(tr("In .osm data file ''{0}'' - ", argInput) + e.getMessage());
    568548        }
    569 
    570         RenderingArea area = determineRenderingArea(ds);
    571         double widthEn = area.projBounds.maxEast - area.projBounds.minEast;
    572         double heightEn = area.projBounds.maxNorth - area.projBounds.minNorth;
    573         int widthPx = (int) Math.round(widthEn / area.scale);
    574         int heightPx = (int) Math.round(heightEn / area.scale);
    575         Logging.debug("image size (px): {0}x{1}", widthPx, heightPx);
    576 
     549    }
     550
     551    private void checkPreconditions(RenderingHelper rh) {
     552        if (argStyles.isEmpty())
     553            throw new IllegalArgumentException(tr("Missing argument - at least one style expected ({0})", "--style"));
     554
     555        Dimension imgSize = rh.getImageSize();
     556        Logging.debug("image size (px): {0}x{1}", imgSize.width, imgSize.height);
    577557        int maxSize = Optional.ofNullable(argMaxImageSize).orElse(DEFAULT_MAX_IMAGE_SIZE);
    578         if (maxSize != 0 && (widthPx > maxSize || heightPx > maxSize)) {
     558        if (maxSize != 0 && (imgSize.width > maxSize || imgSize.height > maxSize)) {
    579559            throw new IllegalArgumentException(
    580560                    tr("Image dimensions ({0}x{1}) exceeds maximum image size {2} (use option {3} to change limit)",
    581                             widthPx, heightPx, maxSize, "--max-image-size"));
    582         }
    583 
    584         // load the styles
    585         MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().lock();
    586         try {
    587             MapPaintStyles.getStyles().clear();
    588             if (argStyles.isEmpty())
    589                 throw new IllegalArgumentException(tr("Missing argument - at least one style expected ({0})", "--style"));
    590             for (StyleData sd : argStyles) {
    591                 SourceEntry se = new SourceEntry(SourceType.MAP_PAINT_STYLE, sd.styleUrl,
    592                             "cliRenderingStyle", "cli rendering style '" + sd.styleUrl + "'", true /* active */);
    593                 StyleSource source = MapPaintStyles.addStyle(se);
    594                 if (!source.getErrors().isEmpty()) {
    595                     throw new IllegalDataException("Failed to load style file. Errors: " + source.getErrors());
    596                 }
    597                 for (String key : sd.settings.keySet()) {
    598                     BooleanStyleSetting match = source.settings.stream()
    599                             .filter(s -> s instanceof BooleanStyleSetting)
    600                             .map(s -> (BooleanStyleSetting) s)
    601                             .filter(bs -> bs.prefKey.endsWith(":" + key))
    602                             .findFirst().orElse(null);
    603                     if (match == null) {
    604                         Logging.warn(tr("Style setting not found: ''{0}''", key));
    605                     } else {
    606                         boolean value = Boolean.parseBoolean(sd.settings.get(key));
    607                         Logging.trace("setting applied: ''{0}:{1}''", key, value);
    608                         match.setValue(value);
    609                     }
    610                 }
    611                 if (!sd.settings.isEmpty()) {
    612                     source.loadStyleSource(); // reload to apply settings
    613                 }
    614             }
    615         } finally {
    616             MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().unlock();
    617         }
    618 
    619         NavigatableComponent nc = new NavigatableComponent() {
    620             {
    621                 setBounds(0, 0, widthPx, heightPx);
    622                 updateLocationState();
    623             }
    624 
    625             @Override
    626             protected boolean isVisibleOnScreen() {
    627                 return true;
    628             }
    629 
    630             @Override
    631             public Point getLocationOnScreen() {
    632                 return new Point(0, 0);
    633             }
    634         };
    635         nc.zoomTo(area.projBounds.getCenter(), area.scale);
    636 
    637         // render the data
    638         BufferedImage image = new BufferedImage(widthPx, heightPx, BufferedImage.TYPE_INT_ARGB);
    639         Graphics2D g = image.createGraphics();
    640         g.setColor(PaintColors.getBackgroundColor());
    641         g.fillRect(0, 0, widthPx, heightPx);
    642         new StyledMapRenderer(g, nc, false).render(ds, false, area.bounds);
    643 
    644         // write to file
    645         String output = Optional.ofNullable(argOutput).orElse("out.png");
    646         ImageIO.write(image, "png", new File(output));
    647     }
    648 
     561                            imgSize.width, imgSize.height, maxSize, "--max-image-size"));
     562        }
     563    }
    649564}
Note: See TracChangeset for help on using the changeset viewer.