Search in sources :

Example 1 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class AboutDialog method donateBitcoin.

private void donateBitcoin() {
    try {
        DesktopUtils.copyToClipboard("1NK8PFYFetTiWReujPsQXDcarXKJuYtqgF");
        if (DesktopUtils.open(new URL("bitcoin:1NK8PFYFetTiWReujPsQXDcarXKJuYtqgF?label=pepsoft.org&message=WorldPainter%20donation"))) {
            JOptionPane.showMessageDialog(this, "The bitcoin address for donations has been copied to your clipboard. In addition,\n" + "if you have a Bitcoin client installed, it may have been opened with the required information filled in.\n" + "Thank you very much for donating!", strings.getString("thank.you"), JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "The bitcoin address for donations has been copied to your clipboard.\n" + "Thank you very much for donating!", strings.getString("thank.you"), JOptionPane.INFORMATION_MESSAGE);
        }
        Configuration config = Configuration.getInstance();
        config.setDonationStatus(Configuration.DonationStatus.DONATED);
        config.logEvent(new EventVO(Constants.EVENT_KEY_DONATION_DONATE_BITCOIN).addTimestamp());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 2 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class App method ping.

private void ping() {
    final UsageVO usageVO = new UsageVO();
    Configuration config = Configuration.getInstance();
    usageVO.setInstall(config.getUuid());
    usageVO.setLaunchCount(config.getLaunchCount());
    List<EventVO> eventLog = config.getEventLog();
    if ((eventLog != null) && (!eventLog.isEmpty())) {
        usageVO.setEvents(eventLog);
    }
    usageVO.setWPVersion(Version.VERSION);
    Main.privateContext.submitUsageData(usageVO);
}
Also used : UsageVO(org.pepsoft.worldpainter.vo.UsageVO) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 3 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class Main method main.

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    // Force language to English for now. TODO: remove this once the first
    // translations are implemented
    Locale.setDefault(Locale.US);
    System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
    // Configure logging
    String logLevel;
    if ("true".equalsIgnoreCase(System.getProperty("org.pepsoft.worldpainter.debugLogging"))) {
        logLevel = "DEBUG";
    } else if ("extra".equalsIgnoreCase(System.getProperty("org.pepsoft.worldpainter.debugLogging"))) {
        logLevel = "TRACE";
    } else {
        logLevel = "INFO";
    }
    File configDir = Configuration.getConfigDir();
    if (!configDir.isDirectory()) {
        configDir.mkdirs();
    }
    LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(logContext);
        logContext.reset();
        System.setProperty("org.pepsoft.worldpainter.configDir", configDir.getAbsolutePath());
        System.setProperty("org.pepsoft.worldpainter.logLevel", logLevel);
        configurator.doConfigure(ClassLoader.getSystemResourceAsStream("logback-main.xml"));
    } catch (JoranException e) {
    // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(logContext);
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    logger.info("Starting WorldPainter " + Version.VERSION + " (" + Version.BUILD + ")");
    // Parse the command line
    File myFile = null;
    boolean mySafeMode = false;
    for (String arg : args) {
        if (arg.trim().toLowerCase().equals("--safe")) {
            mySafeMode = true;
            logger.info("WorldPainter running in safe mode");
        } else if (new File(arg).isFile()) {
            myFile = new File(args[0]);
        }
    }
    final File file = myFile;
    boolean safeMode = mySafeMode;
    // Set the acceleration mode. For some reason we don't fully understand,
    // loading the Configuration from disk initialises Java2D, so we have to
    // do this *before* then.
    // But only do this if a config file exists. If it does not, someone may
    // be trying to reset the configuration, so make sure that the
    // acceleration type setting is reset too in that case.
    AccelerationType accelerationType;
    if (Configuration.getConfigFile().isFile()) {
        String accelTypeName = Preferences.userNodeForPackage(Main.class).get("accelerationType", null);
        if (accelTypeName != null) {
            accelerationType = AccelerationType.valueOf(accelTypeName);
        } else {
            accelerationType = AccelerationType.DEFAULT;
        // TODO: Experiment with which ones work well and use them by default!
        }
        if (!safeMode) {
            switch(accelerationType) {
                case UNACCELERATED:
                    // Try to disable all accelerated pipelines we know of:
                    System.setProperty("sun.java2d.d3d", "false");
                    System.setProperty("sun.java2d.opengl", "false");
                    System.setProperty("sun.java2d.xrender", "false");
                    System.setProperty("apple.awt.graphics.UseQuartz", "false");
                    logger.info("Hardware acceleration method: unaccelerated");
                    break;
                case DIRECT3D:
                    // Direct3D should already be the default on Windows, but
                    // enable a few things which are off by default:
                    System.setProperty("sun.java2d.translaccel", "true");
                    System.setProperty("sun.java2d.ddscale", "true");
                    logger.info("Hardware acceleration method: Direct3D");
                    break;
                case OPENGL:
                    System.setProperty("sun.java2d.opengl", "True");
                    logger.info("Hardware acceleration method: OpenGL");
                    break;
                case XRENDER:
                    System.setProperty("sun.java2d.xrender", "True");
                    logger.info("Hardware acceleration method: XRender");
                    break;
                case QUARTZ:
                    System.setProperty("apple.awt.graphics.UseQuartz", "true");
                    logger.info("Hardware acceleration method: Quartz");
                    break;
                default:
                    logger.info("Hardware acceleration method: default");
                    break;
            }
        }
    } else {
        accelerationType = AccelerationType.DEFAULT;
        if (!safeMode) {
            logger.info("Hardware acceleration method: default");
        }
    }
    if (safeMode) {
        logger.info("[SAFE MODE] Hardware acceleration method: default");
    }
    // Load or initialise configuration
    Configuration config = null;
    try {
        // This will migrate the configuration directory if necessary
        config = Configuration.load();
    } catch (IOException | Error | RuntimeException | ClassNotFoundException e) {
        configError(e);
    }
    if (config == null) {
        if (!logger.isDebugEnabled()) {
            // If debug logging is on, the Configuration constructor will
            // already log this
            logger.info("Creating new configuration");
        }
        config = new Configuration();
    }
    Configuration.setInstance(config);
    logger.info("Installation ID: " + config.getUuid());
    // Store the acceleration type in the config object so the Preferences
    // dialog can edit it
    config.setAccelerationType(accelerationType);
    // Start background scan for Minecraft jars
    BiomeSchemeManager.initialiseInBackground();
    // Load and install trusted WorldPainter root certificate
    X509Certificate trustedCert = null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        trustedCert = (X509Certificate) certificateFactory.generateCertificate(Main.class.getResourceAsStream("/wproot.pem"));
        WPTrustManager trustManager = new WPTrustManager(trustedCert);
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException e) {
        logger.error("Certificate exception while loading trusted root certificate", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm exception while loading trusted root certificate", e);
    } catch (KeyManagementException e) {
        logger.error("Key management exception while loading trusted root certificate", e);
    }
    // Load the plugins
    if (!safeMode) {
        if (trustedCert != null) {
            PluginManager.loadPlugins(new File(configDir, "plugins"), trustedCert.getPublicKey());
        } else {
            logger.error("Trusted root certificate not available; not loading plugins");
        }
    } else {
        logger.info("[SAFE MODE] Not loading plugins");
    }
    WPPluginManager.initialise(config.getUuid());
    String httpAgent = "WorldPainter " + Version.VERSION + "; " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + ";";
    System.setProperty("http.agent", httpAgent);
    // WorldPainter to perform, such as check for updates and submit usage data
    for (PrivateContext aPrivateContextLoader : ServiceLoader.load(PrivateContext.class)) {
        if (privateContext == null) {
            privateContext = aPrivateContextLoader;
        } else {
            throw new IllegalStateException("More than one private context found on classpath");
        }
    }
    if (privateContext == null) {
        logger.debug("No private context found on classpath; update checks and usage data submission disabled");
        config.setPingAllowed(false);
    }
    // Check for updates (if update checker is available)
    if (privateContext != null) {
        privateContext.checkForUpdates();
    }
    final long start = System.currentTimeMillis();
    config.setLaunchCount(config.getLaunchCount() + 1);
    Runtime.getRuntime().addShutdownHook(new Thread("Configuration Saver") {

        @Override
        public void run() {
            try {
                Configuration config = Configuration.getInstance();
                MouseOrTabletOperation.flushEvents(config);
                BetterAction.flushEvents(config);
                EventVO sessionEvent = new EventVO("worldpainter.session").setAttribute(EventVO.ATTRIBUTE_TIMESTAMP, new Date(start)).duration(System.currentTimeMillis() - start);
                StringBuilder sb = new StringBuilder();
                List<Plugin> plugins = WPPluginManager.getInstance().getAllPlugins();
                plugins.stream().filter(plugin -> !(plugin.getName().equals("Default") || plugin.getName().equals("DefaultPlatforms") || plugin.getName().equals("DefaultCustomObjects") || plugin.getName().equals("DefaultLayerEditorProvider"))).forEach(plugin -> {
                    if (sb.length() > 0) {
                        sb.append(',');
                    }
                    sb.append("{name=");
                    sb.append(plugin.getName().replaceAll("[ \\t\\n\\x0B\\f\\r\\.]", ""));
                    sb.append(",version=");
                    sb.append(plugin.getVersion());
                    sb.append('}');
                });
                if (sb.length() > 0) {
                    sessionEvent.setAttribute(ATTRIBUTE_KEY_PLUGINS, sb.toString());
                }
                sessionEvent.setAttribute(ATTRIBUTE_KEY_SAFE_MODE, safeMode);
                config.logEvent(sessionEvent);
                config.save();
                // Store the acceleration type separately, because we need
                // it before we can load the config:
                Preferences prefs = Preferences.userNodeForPackage(Main.class);
                prefs.put("accelerationType", config.getAccelerationType().name());
                prefs.flush();
            } catch (IOException e) {
                logger.error("I/O error saving configuration", e);
            } catch (BackingStoreException e) {
                logger.error("Backing store exception saving acceleration type", e);
            }
            logger.info("Shutting down WorldPainter");
        }
    });
    // Make the "action:" and "bitcoin:" URLs used in various places work:
    URL.setURLStreamHandlerFactory(protocol -> {
        switch(protocol) {
            case "action":
                return new URLStreamHandler() {

                    @Override
                    protected URLConnection openConnection(URL u) throws IOException {
                        throw new UnsupportedOperationException("Not supported");
                    }
                };
            case "bitcoin":
                return new URLStreamHandler() {

                    @Override
                    protected URLConnection openConnection(URL u) throws IOException {
                        throw new UnsupportedOperationException("Not supported");
                    }
                };
            default:
                return null;
        }
    });
    final World2 world;
    if (file == null) {
        world = WorldFactory.createDefaultWorld(config, new Random().nextLong());
    // world = WorldFactory.createFancyWorld(config, new Random().nextLong());
    } else {
        world = null;
    }
    // Install JIDE licence, if present
    InputStream in = ClassLoader.getSystemResourceAsStream("jide_licence.properties");
    if (in != null) {
        try {
            Properties jideLicenceProps = new Properties();
            jideLicenceProps.load(in);
            Lm.verifyLicense(jideLicenceProps.getProperty("companyName"), jideLicenceProps.getProperty("projectName"), jideLicenceProps.getProperty("licenceKey"));
        } finally {
            in.close();
        }
    }
    final Configuration.LookAndFeel lookAndFeel = (config.getLookAndFeel() != null) ? config.getLookAndFeel() : Configuration.LookAndFeel.SYSTEM;
    SwingUtilities.invokeLater(() -> {
        // Install configured look and feel
        try {
            String laf;
            if ((GUIUtils.UI_SCALE > 1) || safeMode) {
                laf = UIManager.getSystemLookAndFeelClassName();
            } else {
                switch(lookAndFeel) {
                    case SYSTEM:
                        laf = UIManager.getSystemLookAndFeelClassName();
                        break;
                    case METAL:
                        laf = "javax.swing.plaf.metal.MetalLookAndFeel";
                        break;
                    case NIMBUS:
                        laf = "javax.swing.plaf.nimbus.NimbusLookAndFeel";
                        break;
                    case DARK_METAL:
                        laf = "org.netbeans.swing.laf.dark.DarkMetalLookAndFeel";
                        break;
                    case DARK_NIMBUS:
                        laf = "org.netbeans.swing.laf.dark.DarkNimbusLookAndFeel";
                        break;
                    default:
                        throw new InternalError();
                }
            }
            if (safeMode) {
                logger.info("[SAFE MODE] Installing system visual theme");
            }
            logger.debug("Installing look and feel: " + laf);
            UIManager.setLookAndFeel(laf);
            LookAndFeelFactory.installJideExtension();
            if ((GUIUtils.UI_SCALE == 1) && ((lookAndFeel == Configuration.LookAndFeel.DARK_METAL) || (lookAndFeel == Configuration.LookAndFeel.DARK_NIMBUS)) && (!safeMode)) {
                // Patch some things to make dark themes look better
                VoidRenderer.setColour(UIManager.getColor("Panel.background").getRGB());
                if (lookAndFeel == Configuration.LookAndFeel.DARK_METAL) {
                    UIManager.put("ContentContainer.background", UIManager.getColor("desktop"));
                    UIManager.put("JideTabbedPane.foreground", new Color(222, 222, 222));
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            logger.warn("Could not install selected look and feel", e);
        }
        // Don't paint values above sliders in GTK look and feel
        UIManager.put("Slider.paintValue", Boolean.FALSE);
        final App app = App.getInstance();
        app.setVisible(true);
        // Swing quirk:
        if (Configuration.getInstance().isMaximised() && (System.getProperty("org.pepsoft.worldpainter.size") == null)) {
            app.setExtendedState(Frame.MAXIMIZED_BOTH);
        }
        // Do this later to give the app the chance to properly set
        // itself up
        SwingUtilities.invokeLater(() -> {
            if (world != null) {
                // On a Mac we may be doing this unnecessarily because we
                // may be opening a .world file, but it has proven difficult
                // to detect that. TODO
                app.setWorld(world);
            } else {
                app.open(file);
            }
            DonationDialog.maybeShowDonationDialog(app);
        });
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) java.util(java.util) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) PluginManager(org.pepsoft.util.PluginManager) CertificateFactory(java.security.cert.CertificateFactory) URL(java.net.URL) EventVO(org.pepsoft.worldpainter.vo.EventVO) LoggerFactory(org.slf4j.LoggerFactory) TrustManager(javax.net.ssl.TrustManager) BackingStoreException(java.util.prefs.BackingStoreException) LoggerContext(ch.qos.logback.classic.LoggerContext) SLF4JBridgeHandler(org.slf4j.bridge.SLF4JBridgeHandler) Lm(com.jidesoft.utils.Lm) VoidRenderer(org.pepsoft.worldpainter.layers.renderers.VoidRenderer) SecureRandom(java.security.SecureRandom) URLConnection(java.net.URLConnection) GUIUtils(org.pepsoft.util.GUIUtils) ATTRIBUTE_KEY_PLUGINS(org.pepsoft.worldpainter.Constants.ATTRIBUTE_KEY_PLUGINS) BetterAction(org.pepsoft.worldpainter.util.BetterAction) BiomeSchemeManager(org.pepsoft.worldpainter.biomeschemes.BiomeSchemeManager) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ATTRIBUTE_KEY_SAFE_MODE(org.pepsoft.worldpainter.Constants.ATTRIBUTE_KEY_SAFE_MODE) WPTrustManager(org.pepsoft.worldpainter.browser.WPTrustManager) MouseOrTabletOperation(org.pepsoft.worldpainter.operations.MouseOrTabletOperation) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) StatusPrinter(ch.qos.logback.core.util.StatusPrinter) File(java.io.File) Preferences(java.util.prefs.Preferences) java.awt(java.awt) LookAndFeelFactory(com.jidesoft.plaf.LookAndFeelFactory) URLStreamHandler(java.net.URLStreamHandler) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JoranException(ch.qos.logback.core.joran.spi.JoranException) Plugin(org.pepsoft.worldpainter.plugins.Plugin) WPPluginManager(org.pepsoft.worldpainter.plugins.WPPluginManager) javax.swing(javax.swing) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecureRandom(java.security.SecureRandom) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) List(java.util.List) EventVO(org.pepsoft.worldpainter.vo.EventVO) SecureRandom(java.security.SecureRandom) X509Certificate(java.security.cert.X509Certificate) URLStreamHandler(java.net.URLStreamHandler) File(java.io.File) CertificateFactory(java.security.cert.CertificateFactory) KeyManagementException(java.security.KeyManagementException) URL(java.net.URL) JoranException(ch.qos.logback.core.joran.spi.JoranException) Preferences(java.util.prefs.Preferences) WPTrustManager(org.pepsoft.worldpainter.browser.WPTrustManager) InputStream(java.io.InputStream) BackingStoreException(java.util.prefs.BackingStoreException) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 4 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class JavaMapImporter method doImport.

public World2 doImport(ProgressReceiver progressReceiver) throws IOException, ProgressReceiver.OperationCancelled {
    long start = System.currentTimeMillis();
    logger.info("Importing map from " + levelDatFile.getAbsolutePath());
    Level level = Level.load(levelDatFile);
    int version = level.getVersion();
    if ((version != SUPPORTED_VERSION_1) && (version != SUPPORTED_VERSION_2)) {
        throw new UnsupportedOperationException("Level format version " + version + " not supported");
    }
    String name = level.getName().trim();
    int maxHeight = level.getMaxHeight();
    World2 world = new World2((version == SUPPORTED_VERSION_1) ? JAVA_MCREGION : JAVA_ANVIL, maxHeight);
    world.addHistoryEntry(HistoryEntry.WORLD_IMPORTED_FROM_MINECRAFT_MAP, level.getName(), levelDatFile.getParentFile());
    world.setCreateGoodiesChest(false);
    world.setName(name);
    world.setSpawnPoint(new Point(level.getSpawnX(), level.getSpawnZ()));
    world.setImportedFrom(levelDatFile);
    world.setMapFeatures(level.isMapFeatures());
    if (level.isHardcore()) {
        world.setGameType(GameType.HARDCORE);
    } else {
        world.setGameType(GameType.values()[level.getGameType()]);
    }
    world.setGenerator(level.getGenerator());
    world.setGeneratorOptions(level.getGeneratorOptions());
    world.setDifficulty(level.getDifficulty());
    if ((version == SUPPORTED_VERSION_2) && (level.getBorderSize() > 0.0)) {
        // If the world is version 0x4abd and actually has border settings,
        // load them
        world.getBorderSettings().setCentreX((int) (level.getBorderCenterX() + 0.5));
        world.getBorderSettings().setCentreY((int) (level.getBorderCenterZ() + 0.5));
        world.getBorderSettings().setSize((int) (level.getBorderSize() + 0.5));
        world.getBorderSettings().setSafeZone((int) (level.getBorderSafeZone() + 0.5));
        world.getBorderSettings().setWarningBlocks((int) (level.getBorderWarningBlocks() + 0.5));
        world.getBorderSettings().setWarningTime((int) (level.getBorderWarningTime() + 0.5));
        world.getBorderSettings().setSizeLerpTarget((int) (level.getBorderSizeLerpTarget() + 0.5));
        world.getBorderSettings().setSizeLerpTime((int) level.getBorderSizeLerpTime());
        world.getBorderSettings().setDamagePerBlock((int) (level.getBorderDamagePerBlock() + 0.5));
    }
    File worldDir = levelDatFile.getParentFile();
    File regionDir = new File(worldDir, "region");
    File netherDir = new File(worldDir, "DIM-1/region");
    File endDir = new File(worldDir, "DIM1/region");
    int dimCount = 1;
    if (netherDir.isDirectory() && dimensionsToImport.contains(DIM_NETHER)) {
        dimCount++;
    }
    if (endDir.isDirectory() && dimensionsToImport.contains(DIM_END)) {
        dimCount++;
    }
    long minecraftSeed = level.getSeed();
    tileFactory.setSeed(minecraftSeed);
    Dimension dimension = new Dimension(minecraftSeed, tileFactory, DIM_NORMAL, maxHeight);
    dimension.setEventsInhibited(true);
    try {
        dimension.setCoverSteepTerrain(false);
        dimension.setSubsurfaceMaterial(Terrain.STONE);
        dimension.setBorderLevel(62);
        // Turn off smooth snow
        FrostSettings frostSettings = new FrostSettings();
        frostSettings.setMode(FrostSettings.MODE_FLAT);
        dimension.setLayerSettings(Frost.INSTANCE, frostSettings);
        ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) dimension.getLayerSettings(Resources.INSTANCE);
        resourcesSettings.setMinimumLevel(0);
        if (version == SUPPORTED_VERSION_1) {
            resourcesSettings.setChance(BLK_EMERALD_ORE, 0);
        }
        Configuration config = Configuration.getInstance();
        dimension.setGridEnabled(config.isDefaultGridEnabled());
        dimension.setGridSize(config.getDefaultGridSize());
        dimension.setContoursEnabled(config.isDefaultContoursEnabled());
        dimension.setContourSeparation(config.getDefaultContourSeparation());
        String dimWarnings = importDimension(regionDir, dimension, version, (progressReceiver != null) ? new SubProgressReceiver(progressReceiver, 0.0f, 1.0f / dimCount) : null);
        if (dimWarnings != null) {
            if (warnings == null) {
                warnings = dimWarnings;
            } else {
                warnings = warnings + dimWarnings;
            }
        }
    } finally {
        dimension.setEventsInhibited(false);
    }
    world.addDimension(dimension);
    int dimNo = 1;
    if (netherDir.isDirectory() && dimensionsToImport.contains(DIM_NETHER)) {
        HeightMapTileFactory netherTileFactory = TileFactoryFactory.createNoiseTileFactory(minecraftSeed + 1, Terrain.NETHERRACK, maxHeight, 188, 192, true, false, 20f, 1.0);
        SimpleTheme theme = (SimpleTheme) netherTileFactory.getTheme();
        SortedMap<Integer, Terrain> terrainRanges = theme.getTerrainRanges();
        terrainRanges.clear();
        terrainRanges.put(-1, Terrain.NETHERRACK);
        theme.setTerrainRanges(terrainRanges);
        theme.setLayerMap(null);
        dimension = new Dimension(minecraftSeed + 1, netherTileFactory, DIM_NETHER, maxHeight);
        dimension.setEventsInhibited(true);
        try {
            dimension.setCoverSteepTerrain(false);
            dimension.setSubsurfaceMaterial(Terrain.NETHERRACK);
            ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) dimension.getLayerSettings(Resources.INSTANCE);
            resourcesSettings.setMinimumLevel(0);
            if (version == SUPPORTED_VERSION_1) {
                resourcesSettings.setChance(BLK_QUARTZ_ORE, 0);
            }
            String dimWarnings = importDimension(netherDir, dimension, version, (progressReceiver != null) ? new SubProgressReceiver(progressReceiver, (float) dimNo++ / dimCount, 1.0f / dimCount) : null);
            if (dimWarnings != null) {
                if (warnings == null) {
                    warnings = dimWarnings;
                } else {
                    warnings = warnings + dimWarnings;
                }
            }
        } finally {
            dimension.setEventsInhibited(false);
        }
        world.addDimension(dimension);
    }
    if (endDir.isDirectory() && dimensionsToImport.contains(DIM_END)) {
        HeightMapTileFactory endTileFactory = TileFactoryFactory.createNoiseTileFactory(minecraftSeed + 2, Terrain.END_STONE, maxHeight, 32, 0, false, false, 20f, 1.0);
        SimpleTheme theme = (SimpleTheme) endTileFactory.getTheme();
        SortedMap<Integer, Terrain> terrainRanges = theme.getTerrainRanges();
        terrainRanges.clear();
        terrainRanges.put(-1, Terrain.END_STONE);
        theme.setTerrainRanges(terrainRanges);
        theme.setLayerMap(Collections.emptyMap());
        dimension = new Dimension(minecraftSeed + 2, endTileFactory, DIM_END, maxHeight);
        dimension.setEventsInhibited(true);
        try {
            dimension.setCoverSteepTerrain(false);
            dimension.setSubsurfaceMaterial(Terrain.END_STONE);
            String dimWarnings = importDimension(endDir, dimension, version, (progressReceiver != null) ? new SubProgressReceiver(progressReceiver, (float) dimNo / dimCount, 1.0f / dimCount) : null);
            if (dimWarnings != null) {
                if (warnings == null) {
                    warnings = dimWarnings;
                } else {
                    warnings = warnings + dimWarnings;
                }
            }
        } finally {
            dimension.setEventsInhibited(false);
        }
        world.addDimension(dimension);
    }
    // Log an event
    Configuration config = Configuration.getInstance();
    if (config != null) {
        EventVO event = new EventVO(EVENT_KEY_ACTION_IMPORT_MAP).duration(System.currentTimeMillis() - start);
        event.setAttribute(EventVO.ATTRIBUTE_TIMESTAMP, new Date(start));
        event.setAttribute(ATTRIBUTE_KEY_MAX_HEIGHT, world.getMaxHeight());
        event.setAttribute(ATTRIBUTE_KEY_PLATFORM, world.getPlatform().displayName);
        event.setAttribute(ATTRIBUTE_KEY_MAP_FEATURES, world.isMapFeatures());
        event.setAttribute(ATTRIBUTE_KEY_GAME_TYPE_NAME, world.getGameType().name());
        event.setAttribute(ATTRIBUTE_KEY_ALLOW_CHEATS, world.isAllowCheats());
        event.setAttribute(ATTRIBUTE_KEY_GENERATOR, world.getGenerator().name());
        if (world.getPlatform().equals(JAVA_ANVIL) && (world.getGenerator() == Generator.FLAT)) {
            event.setAttribute(ATTRIBUTE_KEY_GENERATOR_OPTIONS, world.getGeneratorOptions());
        }
        event.setAttribute(ATTRIBUTE_KEY_TILES, dimension.getTiles().size());
        config.logEvent(event);
    }
    return world;
}
Also used : SimpleTheme(org.pepsoft.worldpainter.themes.SimpleTheme) SubProgressReceiver(org.pepsoft.util.SubProgressReceiver) ResourcesExporterSettings(org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings) Dimension(org.pepsoft.worldpainter.Dimension) FrostSettings(org.pepsoft.worldpainter.layers.exporters.FrostExporter.FrostSettings) File(java.io.File) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 5 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class ScriptRunner method run.

private void run() {
    jComboBox1.setEnabled(false);
    jButton1.setEnabled(false);
    jTextArea1.setEnabled(false);
    jButton2.setEnabled(false);
    jButton3.setEnabled(false);
    jTextArea2.setText(null);
    File scriptFile = (File) jComboBox1.getSelectedItem();
    String scriptFileName = scriptFile.getName(), scriptName;
    Map<String, Object> params;
    if (scriptDescriptor != null) {
        params = scriptDescriptor.getValues();
        if (scriptDescriptor.name != null) {
            scriptName = scriptDescriptor.name;
        } else {
            scriptName = scriptFileName;
        }
    } else {
        params = null;
        scriptName = scriptFileName;
    }
    new Thread(scriptFileName) {

        @Override
        public void run() {
            try {
                Configuration config = Configuration.getInstance();
                int p = scriptFileName.lastIndexOf('.');
                String extension = scriptFileName.substring(p + 1);
                ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension(extension);
                scriptEngine.put(ScriptEngine.FILENAME, scriptFileName);
                config.setRecentScriptFiles(new ArrayList<>(recentScriptFiles));
                // Initialise script context
                ScriptingContext context = new ScriptingContext(false);
                Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
                bindings.put("wp", context);
                String[] parameters = jTextArea1.getText().split("\\R");
                bindings.put("argc", parameters.length + 1);
                String[] argv = new String[parameters.length + 1];
                argv[0] = scriptFileName;
                System.arraycopy(parameters, 0, argv, 1, parameters.length);
                bindings.put("argv", argv);
                bindings.put("arguments", parameters);
                if (params != null) {
                    bindings.put("params", params);
                }
                if (world != null) {
                    bindings.put("world", world);
                }
                if (dimension != null) {
                    bindings.put("dimension", dimension);
                }
                Map<String, Layer.DataSize> dataSizes = new HashMap<>();
                for (Layer.DataSize dataSize : Layer.DataSize.values()) {
                    dataSizes.put(dataSize.name(), dataSize);
                }
                bindings.put("DataSize", dataSizes);
                // Capture output
                List<String> textQueue = new LinkedList<>();
                boolean[] textUpdateScheduled = new boolean[] { false };
                Writer writer = new Writer() {

                    @Override
                    public void write(@NotNull char[] cbuf, int off, int len) throws IOException {
                        synchronized (textQueue) {
                            textQueue.add(new String(cbuf, off, len));
                            if (!textUpdateScheduled[0]) {
                                SwingUtilities.invokeLater(() -> {
                                    synchronized (textQueue) {
                                        // Join the fragments first so that
                                        // only one string need be appended
                                        // to the text area's document
                                        jTextArea2.append(textQueue.stream().collect(joining()));
                                        textQueue.clear();
                                        textUpdateScheduled[0] = false;
                                    }
                                });
                                textUpdateScheduled[0] = true;
                            }
                        }
                    }

                    @Override
                    public void flush() throws IOException {
                    }

                    @Override
                    public void close() throws IOException {
                    }
                };
                scriptEngine.getContext().setWriter(writer);
                scriptEngine.getContext().setErrorWriter(writer);
                // Log the execution
                config.logEvent(new EventVO("script.execute").addTimestamp().setAttribute(ATTRIBUTE_KEY_SCRIPT_NAME, scriptName).setAttribute(ATTRIBUTE_KEY_SCRIPT_FILENAME, scriptFileName));
                // Execute script
                if (dimension != null) {
                    dimension.setEventsInhibited(true);
                }
                try {
                    scriptEngine.eval(new FileReader(scriptFile));
                    // Check that go() was invoked on the last operation:
                    context.checkGoCalled(null);
                } catch (RuntimeException e) {
                    logger.error(e.getClass().getSimpleName() + " occurred while executing " + scriptFileName, e);
                    SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(ScriptRunner.this, e.getClass().getSimpleName() + " occurred (message: " + e.getMessage() + ")", "Error", JOptionPane.ERROR_MESSAGE));
                } catch (javax.script.ScriptException e) {
                    logger.error("ScriptException occurred while executing " + scriptFileName, e);
                    StringBuilder sb = new StringBuilder();
                    sb.append(e.getMessage());
                    if (e.getLineNumber() != -1) {
                        sb.append(" (");
                        sb.append(e.getLineNumber());
                        if (e.getColumnNumber() != -1) {
                            sb.append(':');
                            sb.append(e.getColumnNumber());
                        }
                        sb.append(')');
                    }
                    SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(ScriptRunner.this, sb.toString(), "Error", JOptionPane.ERROR_MESSAGE));
                } catch (FileNotFoundException e) {
                    logger.error("FileNotFoundException occurred while executing " + scriptFileName, e);
                    SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(ScriptRunner.this, "File not found while executing " + scriptFileName, "Error", JOptionPane.ERROR_MESSAGE));
                } finally {
                    if (dimension != null) {
                        dimension.setEventsInhibited(false);
                    }
                    if (undoManagers != null) {
                        undoManagers.forEach(UndoManager::armSavePoint);
                    }
                }
            } finally {
                SwingUtilities.invokeLater(() -> {
                    jComboBox1.setEnabled(true);
                    jButton1.setEnabled(true);
                    jTextArea1.setEnabled(true);
                    jButton2.setEnabled(true);
                    jButton3.setText("Close");
                    jButton3.setEnabled(true);
                });
            }
        }
    }.start();
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) Bindings(javax.script.Bindings) List(java.util.List) EventVO(org.pepsoft.worldpainter.vo.EventVO) Layer(org.pepsoft.worldpainter.layers.Layer) ScriptEngine(javax.script.ScriptEngine)

Aggregations

EventVO (org.pepsoft.worldpainter.vo.EventVO)12 URL (java.net.URL)5 MalformedURLException (java.net.MalformedURLException)4 File (java.io.File)3 List (java.util.List)3 OperationCancelled (org.pepsoft.util.ProgressReceiver.OperationCancelled)3 Dimension (org.pepsoft.worldpainter.Dimension)3 java.awt (java.awt)2 Void (java.lang.Void)2 java.util (java.util)2 SubProgressReceiver (org.pepsoft.util.SubProgressReceiver)2 HistoryEntry (org.pepsoft.worldpainter.history.HistoryEntry)2 Paint (org.pepsoft.worldpainter.painting.Paint)2 FileInUseException (org.pepsoft.worldpainter.util.FileInUseException)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)1 JoranException (ch.qos.logback.core.joran.spi.JoranException)1 StatusPrinter (ch.qos.logback.core.util.StatusPrinter)1 LookAndFeelFactory (com.jidesoft.plaf.LookAndFeelFactory)1 Lm (com.jidesoft.utils.Lm)1