Added a listener system to project specific machine context
authorChristian Femers <femers@in.tum.de>
Thu, 19 Sep 2019 16:11:15 +0000 (18:11 +0200)
committerChristian Femers <femers@in.tum.de>
Thu, 19 Sep 2019 16:11:15 +0000 (18:11 +0200)
plugins/net.mograsim.plugin.core/src/net/mograsim/plugin/nature/MachineContext.java

index b434ec9..b170848 100644 (file)
@@ -1,8 +1,10 @@
 package net.mograsim.plugin.nature;
 
 import java.io.IOException;
+import java.util.HashSet;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.Set;
 
 import org.eclipse.core.resources.IProject;
 import org.eclipse.jface.util.PropertyChangeEvent;
@@ -20,6 +22,8 @@ public class MachineContext
        Optional<MachineDefinition> machineDefinition;
        Optional<Machine> activeMachine;
 
+       private final Set<ActiveMachineListener> observers = new HashSet<>();
+
        public MachineContext(IProject owner)
        {
                this.owner = Objects.requireNonNull(owner);
@@ -87,6 +91,7 @@ public class MachineContext
        public final void setActiveMachine(Machine machine)
        {
                activeMachine = Optional.ofNullable(machine);
+               notifyObservers();
        }
 
        public final Optional<String> getMachineId()
@@ -117,4 +122,26 @@ public class MachineContext
                        updateDefinition();
                }
        }
+
+       public void registerObserver(ActiveMachineListener ob)
+       {
+               observers.add(ob);
+               ob.setMachine(activeMachine);
+       }
+
+       public void deregisterObserver(ActiveMachineListener ob)
+       {
+               observers.remove(ob);
+       }
+
+       private void notifyObservers()
+       {
+               observers.forEach(ob -> ob.setMachine(activeMachine));
+       }
+
+       @FunctionalInterface
+       public static interface ActiveMachineListener
+       {
+               void setMachine(Optional<Machine> machine);
+       }
 }
\ No newline at end of file