Skip to content
Snippets Groups Projects
Controller.java 11.4 KiB
Newer Older
package mp.Controller;
import mp.Model.*;
Porrmann, Maik's avatar
Porrmann, Maik committed

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
Porrmann, Maik's avatar
Porrmann, Maik committed
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.apache.commons.io.FileUtils;


public class Controller implements ActionListener, FocusListener{
    private Model model;
    private PathSettings pathSettings;
    public Controller(Model m){
        model = m;
        pathSettings = null;
    }

    public void loadSettings(File f){
        pathSettings = PathSettings.readFromJSON(f);
    }

    public void loadSettings(String path) throws IOException{
        File f = new File(path);
        if (! f.exists())
            throw new IOException();
        loadSettings(f);
    }

Porrmann, Maik's avatar
Porrmann, Maik committed
    public PathSettings getSettings(){return pathSettings;}

    public void setPathSettings(PathSettings newSettings){
        if(newSettings != null){
            throw new NullPointerException();
        }

        pathSettings = newSettings;
    }

    public String getPathToExecutable(){
        if (pathSettings == null)
            throw new NullPointerException();
        return pathSettings.pathToExecutable;
    }

    public void setPathToExecutable(String path){
        if (pathSettings == null)
            throw new NullPointerException();
        pathSettings.pathToExecutable = path;
    }

    public String getPathToInitFile(){
        if (pathSettings == null)
            throw new NullPointerException();

        return pathSettings.pathToInitFile;
    }

    public void setPathToInitFile(String path){
        if (pathSettings == null)
            throw new NullPointerException();
        pathSettings.pathToInitFile = path;
    }

    public String getPathToMergeFile(){
        if (pathSettings == null)
            throw new NullPointerException();
        return pathSettings.pathToMergeFile;
    }

    public void setPathToMergeFile(String path){
        if (pathSettings == null)
            throw new NullPointerException();
        pathSettings.pathToMergeFile = path;
    }

    public void setPathToConvertFile(String path){
        if (pathSettings == null)
            throw new NullPointerException();
        pathSettings.pathToConvertFile = path;
    }

    public String getPathToConvertFile(){
        if (pathSettings == null)
            throw new NullPointerException();
        return pathSettings.pathToConvertFile;
    }

    public String getPathToPython(){
        if(pathSettings == null)
            throw new NullPointerException();
        return pathSettings.pathToPython;
    }

    public void setPathToPython(String path){
        if (pathSettings == null)
            throw new NullPointerException();
        pathSettings.pathToPython = path;
    }


    @Override
    public void actionPerformed(ActionEvent act) {
        String action = act.getActionCommand();
        System.out.println("Command: "+action);
        if(action.equals("RUN"))
            if (act.getSource() instanceof JComponent)
                runProgramms((JFrame)SwingUtilities.getRoot((JComponent) act.getSource()));
            else 
                throw new UnsupportedOperationException();
        else if (action.equals("VIEW"))
            viewSurface();
        else{
            Parameter p = model.searchForKey(action);
            if(p instanceof BooleanParameter){
                Object s = act.getSource();
                if (s instanceof JCheckBox){
                    ((BooleanParameter) p).setValue(((JCheckBox )s).isSelected());
                }
                else 
                    throw new UnsupportedOperationException();
            }
            else if (p instanceof StringParameter){
                Object s = act.getSource();
                if (s instanceof JTextField) {
                    ((StringParameter) p).setValue(((JTextField) s).getText());
                } else
                    throw new UnsupportedOperationException();
            }
            else if (p instanceof NumericParameter<?>){
                Object s = act.getSource();
                if (s instanceof JTextField) {
Porrmann, Maik's avatar
Porrmann, Maik committed
                    ((NumericParameter<?>) p).setValueFromString(((JTextField) s).getText());
                } else
                    throw new UnsupportedOperationException();

            }
            else if (p instanceof OptionParameter){
                Object s = act.getSource();
                if (s instanceof JComboBox){
Porrmann, Maik's avatar
Porrmann, Maik committed
                    ((OptionParameter)p).choose(((JComboBox<?>)s).getSelectedIndex());
                } else
                    throw new UnsupportedOperationException();

            }
            else
                throw new IllegalArgumentException("Parameter is not of known subclass!");
        }
    }

    public void runProgramms(JFrame frame){
        String userDir = model.searchForKey("General->UserDirectory").getValue();
        setPathToInitFile(userDir+"/parameter.dat");
        
        model.writeFile(getPathToInitFile());
        File initFile = new File(getPathToInitFile());
Porrmann, Maik's avatar
Porrmann, Maik committed

        Object[] options = { "Create Surface", "Cancel!" };
        int n = JOptionPane.showOptionDialog(frame, "Create Surface with this parameterset? This might take a while", "Confirm surface creation",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a custom Icon
                options, // the titles of buttons
                options[0]); // default button title
        if (n == 1)
            return;
        // call elasticSurface
        try{
            File curveDir = new File(userDir+"/curves");
            if (!curveDir.exists())
                curveDir.mkdirs();
            else{
                if (curveDir.isDirectory()){
                    FileUtils.deleteDirectory(curveDir);
                    curveDir.mkdir();
                }
                else
                    throw new RuntimeException("Curve directory is not a directory: "+curveDir.getAbsolutePath());
                
                // Process p = Runtime.getRuntime().exec("rm -r "+ userDir + "/curves/*");
                // p.waitFor();
            }
            String command = getPathToExecutable() + " " + initFile.getAbsolutePath();
            System.out.println(command);
            Process p = Runtime.getRuntime().exec(command, null, curveDir);
            watchProcess(p);

            p.waitFor();
        }
        catch (IOException | InterruptedException e){
            e.printStackTrace();
        }

        // converting vtp file
        try {


            String command = getPathToPython() + " " + getPathToConvertFile() + " -d " + userDir+"/curves/";
            System.out.println(command);
            Process p = Runtime.getRuntime().exec(command);
            watchProcess(p);

            p.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }



        // call mergeFiles
        try {
            String surfaceName =userDir + "/surfaces/"
                                + model.searchForKey("General->SurfaceName").getValue();
            File surfaceFile = new File(surfaceName);
            if (!surfaceFile.exists())
                surfaceFile.mkdirs();
            else{
                if (surfaceFile.isDirectory()){
                    FileUtils.deleteDirectory(surfaceFile);
                    surfaceFile.mkdir();
                }
                else
                    throw new RuntimeException("Surface directory is not a directory: " + surfaceFile.getAbsolutePath());
            }
            // if (!surfaceFile.exists()){
            //     JFileChooser fileChooser = new JFileChooser();
                
            //     fileChooser.setCurrentDirectory(new File("."));
            //     fileChooser.setDialogTitle("Choose destination directory");
            //     fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            //     fileChooser.setAcceptAllFileFilterUsed(false);
            //     int option = fileChooser.showOpenDialog(frame);
            //     if (option == JFileChooser.APPROVE_OPTION){
            //         surfaceFile = fileChooser.getSelectedFile();
            //         if (!surfaceFile.exists())
            //             surfaceFile.createNewFile();
            //     }
            //     else{
            //         label.setText("Surface Creation aborted!");
            //         return;
            //     }
            // }
            
            String command = getPathToPython() + " " + getPathToMergeFile() + "  -o "+ surfaceFile.getAbsolutePath() + " " 
                            + getCurvePaths();
            System.out.println(command);
            Process p = Runtime.getRuntime().exec(command);
            watchProcess(p);
            p.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
Porrmann, Maik's avatar
Porrmann, Maik committed
        
        int n2 = JOptionPane.showConfirmDialog(frame, "Finished creation of surface. View it in paraview?",
                "Finished!", JOptionPane.YES_NO_OPTION);
        if (n2 == 0)
            viewSurface();
        
    }

    public void viewSurface(){
        try{
            String command = "paraview "+ model.searchForKey("General->UserDirectory").getValue() + "/surfaces/"
                                + model.searchForKey("General->SurfaceName").getValue()+"/Timesteps.pvd" + " &";
            System.out.println(command);
            Process p = Runtime.getRuntime().exec(command);
            watchProcess(p);
            p.waitFor();
        }
        catch(IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void focusGained(FocusEvent fevent) {}

    @Override
    public void focusLost(FocusEvent fevent) {
        Object s = fevent.getSource();
        if (s instanceof JTextField){
            ((JTextField)s).postActionEvent();
        }
    }

    private void watchProcess(final Process p){
        watchProcess(p,true);
        watchProcess(p,false);
    }

    private void watchProcess(final Process p, final boolean stderr){
        new Thread(new Runnable() {
            public void run() {
                BufferedReader input;
                if (stderr)
                     input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                else
                    input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;

                try {
                    while ((line = input.readLine()) != null)
                        System.out.println(line);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String getCurvePaths(){
        File userDir = new File( model.searchForKey("General->UserDirectory").getValue());
        String curveDir = userDir.getAbsolutePath()+"/curves/";
        String res = "";
        for (String name : model.curveNames.getValue().split(" ")){
            res+=curveDir+name+".pvd ";
        }
        return res;
    }
}