Search in sources :

Example 1 with Configuration

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

the class MapExplorer method main.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Load or initialise configuration
    File configDir = Configuration.getConfigDir();
    if (!configDir.isDirectory()) {
        configDir.mkdirs();
    }
    // This will migrate the configuration directory if necessary
    Configuration config = Configuration.load();
    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());
    // 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 (trustedCert != null) {
        PluginManager.loadPlugins(new File(configDir, "plugins"), trustedCert.getPublicKey());
    } else {
        logger.error("Trusted root certificate not available; not loading plugins");
    }
    WPPluginManager.initialise(config.getUuid());
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame("Minecraft Map Explorer");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        MapTreeModel treeModel = new MapTreeModel();
        // File minecraftDir = MinecraftUtil.findMinecraftDir();
        // File defaultDir;
        // if (minecraftDir != null) {
        // defaultDir = new File(minecraftDir, "saves");
        // } else {
        // defaultDir = new File(System.getProperty("user.home"));
        // }
        JTree tree = new JTree(treeModel);
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        tree.setCellRenderer(new MapTreeCellRenderer());
        JScrollPane scrollPane = new JScrollPane(tree);
        // tree.expandPath(treeModel.getPath(defaultDir));
        // tree.scrollPathToVisible(treeModel.getPath(defaultDir));
        // Automatically expand any nodes if they only have one child
        tree.addTreeExpansionListener(new TreeExpansionListener() {

            @Override
            public void treeExpanded(TreeExpansionEvent event) {
                Object node = event.getPath().getLastPathComponent();
                if ((!treeModel.isLeaf(node)) && (treeModel.getChildCount(node) == 1)) {
                    tree.expandPath(event.getPath().pathByAddingChild(treeModel.getChild(node, 0)));
                }
            }

            @Override
            public void treeCollapsed(TreeExpansionEvent event) {
            }
        });
        tree.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                    if (path != null) {
                        ((Node) path.getLastPathComponent()).doubleClicked();
                    }
                }
            }
        });
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.setSize(1024, 768);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    });
}
Also used : TreeExpansionListener(javax.swing.event.TreeExpansionListener) MouseEvent(java.awt.event.MouseEvent) Configuration(org.pepsoft.worldpainter.Configuration) WPTrustManager(org.pepsoft.worldpainter.browser.WPTrustManager) MouseAdapter(org.pepsoft.worldpainter.MouseAdapter) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) TreePath(javax.swing.tree.TreePath) File(java.io.File) Main(org.pepsoft.worldpainter.Main) TreeExpansionEvent(javax.swing.event.TreeExpansionEvent)

Example 2 with Configuration

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

the class BiomeSchemeManager method doInitialisation.

private static void doInitialisation() {
    synchronized (initialisationLock) {
        if (logger.isDebugEnabled()) {
            logger.debug("Performing initialisation on thread {}", Thread.currentThread().getName());
        }
        try {
            // Scan the Minecraft directory for supported jars
            minecraftDir = MinecraftUtil.findMinecraftDir();
            if (minecraftDir != null) {
                scanDir(new File(minecraftDir, "bin"));
                scanDir(new File(minecraftDir, "versions"));
            }
            // Collect the names of the files we already looked at so we can skip
            // them below
            Set<File> processedFiles = new HashSet<>();
            for (Map.Entry<Integer, SortedMap<Version, BiomeJar>> entry : BIOME_JARS.entrySet()) {
                processedFiles.addAll(entry.getValue().values().stream().map(biomeJar -> biomeJar.file).collect(Collectors.toList()));
            }
            // Check the jars stored in the configuration (if we haven't
            // encountered them above)
            Configuration config = Configuration.getInstance();
            Map<Integer, File> minecraftJars = config.getMinecraftJars();
            for (Iterator<Map.Entry<Integer, File>> i = minecraftJars.entrySet().iterator(); i.hasNext(); ) {
                Map.Entry<Integer, File> entry = i.next();
                File file = entry.getValue();
                if (file.getAbsolutePath().toLowerCase().contains("optifine")) {
                    // OptiFine-created files create problems, so filter
                    // them out if the configuration somehow got polluted
                    // with them
                    i.remove();
                    continue;
                } else if (processedFiles.contains(file)) {
                    continue;
                } else if ((!file.isFile()) || (!file.canRead())) {
                    // The file is no longer there, or it's not accessible;
                    // remove it from the configuration
                    i.remove();
                    continue;
                }
                try {
                    Checksum checksum = FileUtils.getMD5(file);
                    if (DESCRIPTORS.containsKey(checksum)) {
                        for (BiomeSchemeDescriptor descriptor : DESCRIPTORS.get(checksum)) {
                            SortedMap<Version, BiomeJar> jars = BIOME_JARS.computeIfAbsent(descriptor.biomeScheme, key -> new TreeMap<>());
                            jars.put(descriptor.minecraftVersion, new BiomeJar(file, checksum, descriptor));
                            // Also store it as a resources jar
                            ALL_JARS.put(descriptor.minecraftVersion, file);
                        }
                    } else {
                        // resources
                        try {
                            Version version = Version.parse(file.getName().substring(0, file.getName().length() - 4));
                            ALL_JARS.put(version, file);
                        } catch (NumberFormatException e) {
                            // We don't recognize this jar. Perhaps it has been
                            // replaced with an unsupported version. In any
                            // case, remove it from the configuration
                            i.remove();
                        }
                    }
                } catch (IOException e) {
                    logger.error("I/O error while scanning Minecraft jar " + file.getAbsolutePath() + "; skipping file", e);
                }
            }
        } finally {
            // Done
            initialised = true;
            initialising = false;
            initialisationLock.notifyAll();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Thread {} finished initialisation", Thread.currentThread().getName());
        }
    }
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) IOException(java.io.IOException) Version(org.pepsoft.util.Version) Checksum(org.pepsoft.util.Checksum) File(java.io.File)

Example 3 with Configuration

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

the class RespawnPlayerDialog method selectFile.

private void selectFile() {
    File mySavesDir;
    Configuration config = Configuration.getInstance();
    if ((config != null) && (config.getSavesDirectory() != null)) {
        mySavesDir = config.getSavesDirectory();
    } else {
        mySavesDir = DesktopUtils.getDocumentsFolder();
    }
    File levelDatFile = FileUtils.selectFileForOpen(this, "Select Minecraft map level.dat file", mySavesDir, new FileFilter() {

        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().equalsIgnoreCase("level.dat");
        }

        @Override
        public String getDescription() {
            return "Minecraft level.dat files";
        }
    });
    if (levelDatFile != null) {
        jTextField1.setText(levelDatFile.getAbsolutePath());
    }
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File)

Example 4 with Configuration

use of org.pepsoft.worldpainter.Configuration 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)

Example 5 with Configuration

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

the class BiomesViewerMain method main.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e) {
    // Oh well
    }
    Configuration config = Configuration.load();
    if (config == null) {
        config = new Configuration();
    }
    Configuration.setInstance(config);
    BiomesViewerFrame frame = new BiomesViewerFrame(new Random().nextLong(), Constants.BIOME_ALGORITHM_1_7_DEFAULT, new DynMapColourScheme("default", true), null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
Also used : UnsupportedLookAndFeelException(javax.swing.UnsupportedLookAndFeelException) Configuration(org.pepsoft.worldpainter.Configuration) Random(java.util.Random) DynMapColourScheme(org.pepsoft.worldpainter.colourschemes.DynMapColourScheme)

Aggregations

Configuration (org.pepsoft.worldpainter.Configuration)12 File (java.io.File)7 IOException (java.io.IOException)4 CertificateException (java.security.cert.CertificateException)2 CertificateFactory (java.security.cert.CertificateFactory)2 X509Certificate (java.security.cert.X509Certificate)2 TreeSet (java.util.TreeSet)2 BiomeScheme (org.pepsoft.worldpainter.BiomeScheme)2 Minecraft1_7BiomeScheme (org.pepsoft.worldpainter.biomeschemes.Minecraft1_7BiomeScheme)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 MouseEvent (java.awt.event.MouseEvent)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1