123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880 |
- package ui.controller;
- import java.awt.Point;
- import java.awt.datatransfer.UnsupportedFlavorException;
- import java.io.File;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.stream.Collectors;
- import javax.swing.JFrame;
- import org.apache.commons.compress.archivers.ArchiveException;
- import com.google.gson.JsonParseException;
- import classes.AbstractCanvasObject;
- import classes.Category;
- import classes.Edge;
- import classes.GroupNode;
- import classes.HolonElement;
- import classes.HolonObject;
- import classes.Node;
- import ui.model.Model;
- import ui.model.Model.FairnessModel;
- import ui.view.CreateTemplatePopUp;
- import ui.view.GUI;
- import utility.Event;
- /**
- * The Class represents the controller in the model, controller view Pattern.
- *
- * @author Gruppe14
- */
- public class Control {
- private final MultiPurposeController multiPurposeController;
- private final CategoryController categoryController;
- private final ObjectController objectController;
- private final CanvasController canvasController;
- private final GlobalController globalController;
- private final SaveController saveController;
- private final LoadController loadController;
- private final AutoSaveController autoSaveController;
- private final NodeController nodeController;
- private final ClipboardController clipboardController;
- private final HolonCanvasController holonCanvasController;
- private Model model;
- private SimulationManager simulationManager;
- private String autosaveDir = "";
- private String categoryDir = "";
- private String otherDir = "";
- private String dimensionsFileName = "dimensions";
- private int rand;
-
- public Event OnCategoryChanged = new Event();
- /**
- * Constructor.
- *
- * @param model the Model
- */
- public Control(Model model) {
- this.model = model;
- this.multiPurposeController = new MultiPurposeController(model);
- this.categoryController = new CategoryController(model, multiPurposeController, this);
- this.objectController = new ObjectController(model, multiPurposeController);
- this.canvasController = new CanvasController(model, multiPurposeController);
- this.globalController = new GlobalController(model);
- this.saveController = new SaveController(model);
- this.nodeController = new NodeController(model, canvasController, multiPurposeController);
- this.loadController = new LoadController(model, categoryController, canvasController, objectController,
- nodeController, multiPurposeController);
- this.simulationManager = new SimulationManager(model);
- this.autoSaveController = new AutoSaveController(model);
- this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
- objectController, nodeController, this.simulationManager);
- this.holonCanvasController = new HolonCanvasController(model);
- autosaveDir = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
- categoryDir = System.getProperty("user.home") + "/.config/HolonGUI/Category/";
- otherDir = System.getProperty("user.home") + "/.config/HolonGUI/Other/";
- File autoSave = new File(autosaveDir);
- File category = new File(categoryDir);
- File other = new File(otherDir);
- // deleteDirectory(dest);
- autoSave.mkdirs();
- category.mkdirs();
- other.mkdirs();
- createAutoRandom();
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Generate random number, so that every instance of the program has unique
- * save files
- */
- private void createAutoRandom() {
- rand = (int) (Math.random() * 1000);
- while (new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
- rand = (int) Math.random() * 1000;
- }
- }
- /**
- * Delete a Directory.
- *
- * @param path to delete
- */
- public void deleteDirectory(File path) {
- if (path.exists()) {
- File[] files = path.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
- deleteDirectory(file);
- } else {
- if (file.getName().contains("" + rand))
- file.delete();
- }
- }
- // path.delete();
- }
- }
- /* Operations for searching */
- /**
- * Search for Object by ID.
- *
- * @param id the id of the Object
- * @return the CpsObject
- */
- public AbstractCanvasObject searchByID(int id) {
- return multiPurposeController.searchByID(id);
- }
- /**
- * Search for Object by ID in upperNode
- *
- * @param id the id of the Object
- * @return the CpsObject
- */
- public AbstractCanvasObject searchByIDUpperNode(int id, GroupNode upperNode) {
- return multiPurposeController.searchByIDUpperNode(id, upperNode);
- }
- public AbstractCanvasObject searchTracked(int id) {
- return multiPurposeController.searchByID(id);
- }
- /**
- * Search for Object in a Category.
- *
- * @param category name of the Category
- * @param object Name of the Object
- * @return The Object
- */
- public AbstractCanvasObject searchCategoryObject(String category, String object) {
- return multiPurposeController.searchCatObj(multiPurposeController.searchCat(category), object);
- }
- /**
- * search for category.
- *
- * @param cat name of the Category
- * @return the Category
- */
- public Category searchCategory(String cat) {
- return multiPurposeController.searchCat(cat);
- }
- /* Operations for Categories and Objects */
- /**
- * init default category and objects.
- *
- * @throws IOException
- */
- public void resetCategorys() throws IOException {
- categoryController.initCategories();
- objectController.initHolonElements();
- saveCategory();
- }
- /**
- * Adds New Category into Model.
- *
- * @param cat name of the new Category
- * @throws IOException
- */
- public void addCategory(String cat) throws IOException {
- categoryController.addNewCategory(cat);
- saveCategory();
- }
- /**
- * Gives all Category as String
- * @return a array of strings from all Categorys
- */
- public String[] getCategoriesStrings()
- {
- return ((ArrayList<String>) categoryController.getCategories().stream().map(c -> c.getName()).collect(Collectors.toList())).toArray(new String[categoryController.getCategories().size()]);
- }
- /**
- * Add new Holon Object to a Category.
- *
- * @param cat Category
- * @param obj New Object Name
- * @param list Array of Elements
- * @param img the image Path
- * @throws IOException
- */
- public void addObject(Category cat, String obj, List<HolonElement> list, String img) throws IOException {
- categoryController.addNewHolonObject(cat, obj, list, img);
- saveCategory();
- }
- /**
- * Add new Holon Switch to a Category.
- *
- * @param cat Category
- * @param obj New Object Name
- * @throws IOException
- */
- public void addSwitch(Category cat, String obj) throws IOException {
- categoryController.addNewHolonSwitch(cat, obj, "/Images/switch-on.png");
- saveCategory();
- }
-
-
- /**
- * delete a given Category.
- *
- * @param cat the Category
- * @throws IOException
- */
- public void deleteCategory(String cat) throws IOException {
- categoryController.deleteCategory(cat);
- saveCategory();
- }
- /**
- * Delete an Object from a Category.
- *
- * @param cat the Category
- * @param obj the Object
- * @throws IOException
- */
- public void delObjectCategory(String cat, String obj) throws IOException {
- categoryController.deleteObject(cat, obj);
- saveCategory();
- }
- /**
- * deletes a selectedObject.
- *
- * @param obj Cpsobject
- */
- public void deleteSelectedObject(AbstractCanvasObject obj) {
- objectController.deleteSelectedObject(obj);
- }
- /**
- * add an Object to selectedObject.
- *
- * @param obj AbstractCpsobject
- */
- public void addSelectedObject(AbstractCanvasObject obj) {
- objectController.addSelectedObject(obj);
- }
- /* Operations for Canvas */
- /**
- * Add a new Object.
- *
- * @param object the Object
- */
- public void addObjectCanvas(AbstractCanvasObject object) {
- canvasController.addNewObject(object);
- calculateStateAndVisualForTimeStep(model.getCurIteration());
- if (!(object instanceof Node)) {
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Deletes an CpsObject on the Canvas and its connections.
- *
- * @param obj AbstractCpsObject
- * @param save
- */
- public void delCanvasObject(AbstractCanvasObject obj, boolean save) {
- canvasController.deleteObjectOnCanvas(obj);
- if (obj instanceof GroupNode) {
- canvasController.bfsNodeCleaner((GroupNode) obj);
- }
- calculateStateAndVisualForCurrentTimeStep();
- if (save)
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Replaces {@code toBeReplaced} by {@code by} on the canvas
- * @param toBeReplaced the object that will be replaced
- * @param by the object that will replace it
- */
- public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
- canvasController.replaceObjectOnCanvas(toBeReplaced, by);
- try {
- autoSave();
- } catch (IOException e) {
- System.out.println("Error by Replacing "+toBeReplaced.toString() + " by " + by.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * Add an edge to the Canvas.
- *
- * @param edge the edge
- */
- public void addEdgeOnCanvas(Edge edge) {
- canvasController.addEdgeOnCanvas(edge);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Removes an Edge from the Canvas.
- *
- * @param edge the edge to remove
- */
- public void removeEdgesOnCanvas(Edge edge) {
- canvasController.removeEdgesOnCanvas(edge);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Set the selected Edge.
- *
- * @param edge that is selected
- */
- public void setSelecteEdge(Edge edge) {
- model.setSelectedEdge(edge);
- }
- /**
- * Returns the ID of the selected Object 0 = no Object is selected.
- *
- * @param id the ID of the selected Object
- */
- public void setSelectedObjectID(int id) {
- objectController.setSelectedObjectID(id);
- }
-
- /* Operations for Objects and Elements */
- /**
- * Add a new Element into a Object on the Canvas.
- *
- * @param objectId the Object ID
- * @param ele the Name of the Element
- * @param amount the Amount
- * @param energy the Energy
- * @param elementId the Element ID
- */
- public void addElementCanvasObject(int objectId, String ele, int amount, float energy, int elementId) {
- objectController.addNewElementIntoCanvasObject(objectId, ele, amount, energy, elementId);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Add a new Element into a Object in Category.
- *
- * @param catName the Category
- * @param objName the Object
- * @param eleName the Element Name
- * @param amount the amount
- * @param energy the Energy
- */
- public void addElementCategoryObject(String catName, String objName, String eleName, int amount, float energy) {
- objectController.addNewElementIntoCategoryObject(catName, objName, eleName, amount, energy);
- }
- /**
- * deletes a Element from a given Canvas Object.
- *
- * @param id the ID
- * @param elementid the Element ID
- */
- public void deleteElementCanvas(int id, int elementid) {
- objectController.deleteElementInCanvas(id, elementid);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Returns SCALE.
- *
- * @return SCALE
- */
- public int getScale() {
- return globalController.getScale();
- }
- /**
- * Changes the value of SCALE and SCALEDIV2.
- *
- * @param s Scale
- */
- public void setScale(int s) {
- globalController.setScale(s);
- }
- /**
- * Returns SCALE Divided by 2.
- *
- * @return SCALE Divided by 2
- */
- public int getScaleDiv2() {
- return globalController.getScaleDiv2();
- }
- /**
- * sets the current Iteration.
- *
- * @param curit the current Iteration
- */
- public void setCurIteration(int curit) {
- globalController.setCurIteration(curit);
- //getGui().getTimePanel().getTimeSlider().setValue(curit);
- }
- /**
- * Writes the current State of the Modelling into a JSON File which can be
- * loaded.
- *
- * @param path the Path
- * @throws IOException exception
- */
- public void saveFile(String path) throws IOException, ArchiveException {
- saveController.writeSave(path);
- }
- /**
- * Reads the the Save File and load the state into the Model.
- *
- * @param path the Path
- * @throws IOException exception
- * @throws ArchiveException
- */
- public void loadFile(String path) throws IOException, ArchiveException {
- loadController.readSave(path);
- saveCategory();
- autoSave();
- }
- /**
- * Reads the Json File from Autosave
- *
- * @param path
- * @throws IOException
- */
- public void loadAutoSave(String path) throws IOException {
- loadController.readJson(path);
- }
- public ArrayList<Integer> loadSavedWindowDimensionsIfExistent() {
- try {
- return loadController.readWindowDimensions(otherDir + dimensionsFileName);
- } catch (Exception e) {
- return new ArrayList<>();
- }
- }
- /**
- * calculates the flow of the edges and the supply for objects for the
- * current Timestep.
- */
- public void calculateStateAndVisualForCurrentTimeStep() {
- calculateStateAndVisualForTimeStep(model.getCurIteration());
- }
- public void calculateStateOnlyForCurrentTimeStep() {
- simulationManager.calculateStateForTimeStep(model.getCurIteration(), false);
- }
- /**
- * calculates the flow of the edges and the supply for objects.
- *
- * @param x current Iteration
- */
- public void calculateStateAndVisualForTimeStep(int x) {
- simulationManager.calculateStateForTimeStep(x, true);
- updateOutliner();
- updateFlexWindow();
- this.updateCanvas();
- }
- /**
- * resets the whole State of the simulation including a reset of all Edges
- * to the default "is working" state
- */
- public void resetSimulation() {
- simulationManager.resetFlexManager();
- }
- /**
- * make an autosave.
- *
- * @throws IOException Exception
- */
- public void autoSave() throws IOException {
- autoSaveController.increaseAutoSaveNr();
- saveController.writeAutosave(autosaveDir + rand + autoSaveController.getAutoSaveNr());
- if (autoSaveController.allowed()) {
- new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr() - globalController.getNumbersOfSaves()))
- .delete();
- }
- }
- /**
- * find all old auto save files (with a file-name, that does not contain the current rand)
- *
- * @return a list of files, that are not from the current run
- */
- public ArrayList<File> filterOldAutoSaveFiles() {
- File[] files = new File(autosaveDir).listFiles();
- ArrayList<File> oldAutoSaves = new ArrayList<>();
- for (File file : files) {
- if (!file.getName().contains(String.valueOf(rand)))
- oldAutoSaves.add(file);
- }
- return oldAutoSaves;
- }
- /**
- * deletes the old autosave files
- */
- public void deleteObsoleteAutoSaveFiles() {
- for (File file : filterOldAutoSaveFiles()) {
- file.delete();
- }
- }
- public void saveCategory() throws IOException {
- saveController.writeCategory(categoryDir + "Category.json");
- }
- public void savePosAndSizeOfWindow(int x, int y, int width, int height) throws IOException, ArchiveException {
- saveController.writeWindowStatus(otherDir + dimensionsFileName, x, y, width, height);
- }
- /**
- * Returns the undo save.
- *
- * @return the undo save
- */
- public String getUndoSave() {
- autoSaveController.decreaseAutoSaveNr();
- if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
- autoSaveController.increaseAutoSaveNr();
- }
- return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
- }
- /**
- * Returns the redo save.
- *
- * @return the redo save
- */
- public String getRedoSave() {
- autoSaveController.increaseAutoSaveNr();
- if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
- autoSaveController.decreaseAutoSaveNr();
- // if it still does not exist, try old autosaves
- if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
- ArrayList<File> oldAutoSaves = filterOldAutoSaveFiles();
- if (oldAutoSaves.size() > 0) {
- return autosaveDir + oldAutoSaves.get(oldAutoSaves.size() - 1).getName();
- }
- }
- }
- return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
- }
- /**
- * Getter for Model.
- *
- * @return the Model
- */
- public Model getModel() {
- return model;
- }
- /**
- * get the Simulation Manager.
- *
- * @return the Simulation Manager
- */
- public SimulationManager getSimManager() {
- return simulationManager;
- }
-
- /**
- * Set the timerSpeed.
- *
- * @param t interval in ms
- */
- public void setTimerSpeed(int t) {
- globalController.setTimerSpeed(t);
- }
- /**
- * Set the Canvas X Size.
- *
- * @param canvasX the cANVAS_X to set
- */
- public void setCanvasX(int canvasX) {
- globalController.setCanvasX(canvasX);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Set the Canvas Y Size.
- *
- * @param canvasY the cANVAS_Y to set
- */
- public void setCanvasY(int canvasY) {
- globalController.setCanvasY(canvasY);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void setMaxCapacity(float cap) {
- globalController.setMaxCapacity(cap);
- }
-
- // ========================== MANAGING TRACKED OBJECTS END ================
- /**
- * Controlling Nodes of Nodes
- */
- public void addUpperNode(String nodeName, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
- nodeController.doUpperNode(nodeName, upperNode, toGroup);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void ungroupGroupNode(GroupNode node, GroupNode upperNode) {
- nodeController.undoUpperNode(node, upperNode);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void addObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
- nodeController.addObjectInUpperNode(object, upperNode, true);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void delObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
- nodeController.deleteObjectInUpperNode(object, upperNode);
- if (object instanceof GroupNode)
- canvasController.bfsNodeCleaner((GroupNode) object);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Replaces {@code toBePlaced} by {@code by} in {@code upperNode}
- * @param toBeReplaced
- * @param by
- * @param upperNode
- */
- public void replaceObjUpperNode(AbstractCanvasObject toBeReplaced,
- AbstractCanvasObject by, GroupNode upperNode) {
- nodeController.replaceObjectInUpperNode(toBeReplaced, by, upperNode);
- try {
- autoSave();
- } catch (IOException e) {
- System.out.println("Error by Replacing "+toBeReplaced.toString()
- + " by " + by.toString() + " in UpperNode " + upperNode.toString());
- e.printStackTrace();
- }
- }
-
- /**
- * Get the number of HolonObjects in the given List
- *
- * @param list
- */
- public int getNumberHolonObjects(ArrayList<AbstractCanvasObject> list) {
- return objectController.getNumberHolonObjects(list);
- }
-
- /**
- * Get the number of HolonObjects in the given List
- *
- * @param list
- */
- public ArrayList<HolonObject> getAllHolonObjects(ArrayList<AbstractCanvasObject> list) {
- return objectController.getAllHolonObjects(list);
- }
- /**
- * Copy all Selected Objects.
- */
- public void copy(GroupNode upperNode) {
- clipboardController.copy(upperNode);
- }
- public void paste(GroupNode upperNode, Point point)
- throws JsonParseException, UnsupportedFlavorException, IOException {
- clipboardController.paste(upperNode, point);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void cut(GroupNode upperNode) {
- clipboardController.cut(upperNode);
- try {
- autoSave();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * creates a new Template for the given cps Object
- * @param cps Object, which should become a template
- * @param parentFrame
- */
- public void createTemplate(HolonObject cps, JFrame parentFrame) {
- CreateTemplatePopUp t = new CreateTemplatePopUp(cps,model,parentFrame,this);
- t.setVisible(true);
- }
- public void getObjectsInDepth() {
- clipboardController.getObjectsInDepth();
- }
- public float getTotalProduction(ArrayList<AbstractCanvasObject> arrayList) {
- return holonCanvasController.getTotalProduction(arrayList);
- }
- public float getTotalConsumption(ArrayList<AbstractCanvasObject> arrayList) {
- return holonCanvasController.getTotalConsumption(arrayList);
- }
- public int getTotalElements(ArrayList<AbstractCanvasObject> arrayList) {
- return holonCanvasController.getTotalElements(arrayList);
- }
- public int getTotalProducers(ArrayList<AbstractCanvasObject> arrayList) {
- return holonCanvasController.getTotalProducers(arrayList);
- }
- public int getActiveElements(ArrayList<AbstractCanvasObject> arrayList) {
- return holonCanvasController.getActiveElements(arrayList);
- }
- /**
- * Set the Background Image;
- *
- * @param imagePath Image Path
- * @param mode Image Mode
- * @param width Image custom width
- * @param height Image custom height
- */
- public void setBackgroundImage(String imagePath, int mode, int width, int height) {
- canvasController.setBackgroundImage(imagePath, mode, width, height);
- }
- /**
- * Sets show
- * @param showSupplyBars wether the bars should be shown
- */
- public void setShowSupplyBars(boolean showSupplyBars) {
- globalController.setShowSupplyBars(showSupplyBars);
- }
-
- /**
- * Sets fairness Model
- * @param fairnessModel that should be used.
- */
- public void setFairnessModel(FairnessModel fairnessModel) {
- globalController.setFairnessModel(fairnessModel);
- }
-
- public void updateOutliner() {
- this.canvasController.updateOutliner(simulationManager);
- }
-
- public void updateFlexWindow() {
- canvasController.updateFlexWindow();
- }
-
-
- public void updateCanvas() {
- canvasController.updateCanvas();
- }
- public GUI getGui() {
- return canvasController.getGui();
- }
- public void guiDisable(boolean state) {
- canvasController.guiDisable(state);
- }
-
- public void setGui(GUI gui) {
- canvasController.setGui(gui);
- }
-
- }
|