file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
DavizTheme.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/DavizTheme.java
package com.aexiz.daviz; import javax.swing.plaf.metal.*; public class DavizTheme extends OceanTheme { public String getName() { return "DaViz"; } }
156
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Algorithm.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Algorithm.java
package com.aexiz.daviz.glue; import com.aexiz.daviz.sim.Process.TProcessDescription; public abstract class Algorithm { public interface MaxRounds { int maxRounds(Network network); } protected Assumption assumption; // General property before simulation public Assumption getAssumption() { return assumption; } public MaxRounds getMaxRounds() { return null; } // Unloading information from simulation protected abstract Information.Message makeAndUnloadMessage(GlueHelper helper, Object o); protected abstract Information.State makeAndUnloadState(GlueHelper helper, Object o); protected abstract Information.Result makeAndUnloadResult(GlueHelper helper, Object o); // Loading information into simulation protected abstract TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper); }
900
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Event.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Event.java
package com.aexiz.daviz.glue; import java.util.HashMap; import java.util.List; import com.aexiz.daviz.glue.Viewpoint.Node; import com.aexiz.daviz.sim.Event.TEvent; import com.aexiz.daviz.sim.Event.TEvent.DEInternal; import com.aexiz.daviz.sim.Event.TEvent.DEReceive; import com.aexiz.daviz.sim.Event.TEvent.DEResult; import com.aexiz.daviz.sim.Event.TEvent.DESend; public abstract class Event extends Locus implements Cloneable { // Property Simulation simulation; Execution execution; // Haskell dependency transient TEvent<Object,Object,Object> hEvent; transient int hId; // Computed properties transient Viewpoint.Node happensAt; // Computed properties, unique to instance (not cloned) transient Event matchingEvent; transient Event previousEvent; static void matchAndLinkEvents(List<Event> events) { // First we clear the state of all events for (int i = 0, size = events.size(); i < size; i++) { Event old = events.get(i); old.matchingEvent = null; old.previousEvent = null; } // Match send and receive events for (int i = 0, size = events.size(); i < size; i++) { Event event = events.get(i); if (event instanceof Event.ReceiveEvent) { Event.ReceiveEvent receive = (Event.ReceiveEvent) event; Information.Message rMsg = receive.getMessage(); boolean matched = false; for (int j = 0; j < i; j++) { Event other = events.get(j); if (other instanceof Event.SendEvent) { Event.SendEvent sender = (Event.SendEvent) other; Information.Message sMsg = sender.getMessage(); if (sender.getReceiver() != receive.getHappensAt()) continue; if (receive.getSender() != sender.getHappensAt()) continue; if (sender.hasMatchingEvent()) continue; if (!rMsg.equals(sMsg)) continue; sender.matchingEvent = receive; receive.matchingEvent = sender; matched = true; break; } } if (!matched) throw new Error("Unmatched Haskell receive event"); } } // Build a linked list of events and their predecessor within the same process HashMap<Node,Event> map = new HashMap<Node,Event>(); for (Event event : events) { Node happens = event.getHappensAt(); event.previousEvent = map.get(happens); map.put(happens, event); } } Event() { } public Simulation getSimulation() { invariant(); return simulation; } public Execution getExecution() { invariant(); return execution; } public boolean hasMatchingEvent() { return false; } public Event getMatchingEvent() { throw new Error("Only defined for Send or Receive"); } void invariant() { if (simulation == null) throw new Error("Invalid simulation"); if (execution == null) throw new Error("Invalid execution"); if (hEvent == null) throw new Error("Invalid Haskell event"); } void unload() { invariant(); hId = TEvent.proc(hEvent); happensAt = simulation.getNetwork().getNodeById(hId); } static Event makeAndUnload(TEvent<Object,Object, Object> e, Execution ex) { Event result; if (e.asEReceive() != null) { result = new ReceiveEvent(); } else if (e.asEInternal() != null) { result = new InternalEvent(); } else if (e.asESend() != null) { result = new SendEvent(); } else if (e.asEResult() != null) { result = new ResultEvent(); } else { throw new Error("Unknown Haskell event"); } result.simulation = ex.simulation; result.execution = ex; result.hEvent = e; result.unload(); return result; } public abstract Event clone(); protected Event clone(Event to) { to.simulation = this.simulation; to.execution = this.execution; to.hEvent = this.hEvent; to.hId = this.hId; to.happensAt = this.happensAt; return to; } public Event getPreviousEvent() { return previousEvent; } // Computed properties public boolean hasHappensAt() { return true; } public Viewpoint.Node getHappensAt() { return happensAt; } public boolean hasNextState() { return false; } public Information.State getNextState() { throw new Error(); } public boolean hasMessage() { return false; } public Information.Message getMessage() { throw new Error(); } public boolean hasResult() { return false; } public Information.Result getResult() { throw new Error(); } public boolean hasSender() { return false; } public Viewpoint.Node getSender() { throw new Error(); } public boolean hasReceiver() { return false; } public Viewpoint.Node getReceiver() { throw new Error(); } // Subclasses public static class ResultEvent extends Event { // Haksell dependencies transient DEResult<Object,Object,Object> hEvent; // Computed properties transient Information.Result result; ResultEvent() { } void unload() { super.unload(); hEvent = super.hEvent.asEResult(); GlueHelper helper = new GlueHelper(simulation); result = simulation.getAlgorithm().makeAndUnloadResult(helper, hEvent.mem$val.call()); } protected ResultEvent clone(Event to) { super.clone(to); ResultEvent tor = (ResultEvent) to; tor.hEvent = this.hEvent; tor.result = this.result; return tor; } public boolean hasResult() { return true; } public Information.Result getResult() { return result; } public ResultEvent clone() { return clone(new ResultEvent()); } public String toString() { return "Process " + happensAt.getLabel() + " results: " + result; } } public static class ReceiveEvent extends Event { // Haskell dependencies transient DEReceive<Object,Object,Object> hEvent; // Computed properties transient Information.Message message; transient Information.State nextState; transient Viewpoint.Node sender; ReceiveEvent() { } void unload() { super.unload(); hEvent = super.hEvent.asEReceive(); GlueHelper helper = new GlueHelper(simulation); message = simulation.getAlgorithm().makeAndUnloadMessage(helper, hEvent.mem$msg.call()); nextState = simulation.getAlgorithm().makeAndUnloadState(helper, hEvent.mem$next.call()); sender = simulation.getNetwork().getNodeById(hEvent.mem$send.call()); } protected ReceiveEvent clone(Event to) { super.clone(to); ReceiveEvent tor = (ReceiveEvent) to; tor.hEvent = this.hEvent; tor.message = this.message; tor.nextState = this.nextState; tor.sender = this.sender; return tor; } public ReceiveEvent clone() { return clone(new ReceiveEvent()); } public boolean hasMessage() { return true; } public Information.Message getMessage() { return message; } public boolean hasNextState() { return true; } public Information.State getNextState() { return nextState; } public boolean hasSender() { return true; } public Viewpoint.Node getSender() { return sender; } public boolean hasMatchingEvent() { return true; } public SendEvent getMatchingEvent() { if (matchingEvent == null) throw new Error("Unmatched receive event"); return (SendEvent) matchingEvent; } public String toString() { return "Process " + happensAt.getLabel() + " receives " + message + " from " + sender; } } public static class SendEvent extends Event { // Haskell dependencies transient DESend<Object,Object,Object> hEvent; // Computed properties transient Information.Message message; transient Information.State nextState; transient Viewpoint.Node receiver; SendEvent() { } void unload() { super.unload(); hEvent = super.hEvent.asESend(); GlueHelper helper = new GlueHelper(simulation); message = simulation.getAlgorithm().makeAndUnloadMessage(helper, hEvent.mem$msg.call()); nextState = simulation.getAlgorithm().makeAndUnloadState(helper, hEvent.mem$next.call()); receiver = simulation.getNetwork().getNodeById(hEvent.mem$recv.call()); } protected SendEvent clone(Event to) { super.clone(to); SendEvent tor = (SendEvent) to; tor.hEvent = this.hEvent; tor.message = this.message; tor.nextState = this.nextState; tor.receiver = this.receiver; return tor; } public SendEvent clone() { return clone(new SendEvent()); } public boolean hasMessage() { return true; } public Information.Message getMessage() { return message; } public boolean hasNextState() { return true; } public Information.State getNextState() { return nextState; } public boolean hasReceiver() { return true; } public Viewpoint.Node getReceiver() { return receiver; } public boolean hasMatchingEvent() { return matchingEvent != null; } public ReceiveEvent getMatchingEvent() { return (ReceiveEvent) matchingEvent; } public String toString() { return "Process " + happensAt.getLabel() + " sends " + message + " to " + receiver; } } public static class InternalEvent extends Event { // Haskell dependencies transient DEInternal<Object,Object,Object> hEvent; // Computed properties transient Information.State nextState; InternalEvent() { } void unload() { super.unload(); hEvent = super.hEvent.asEInternal(); GlueHelper helper = new GlueHelper(simulation); nextState = simulation.getAlgorithm().makeAndUnloadState(helper, hEvent.mem$next.call()); } protected InternalEvent clone(Event to) { super.clone(to); InternalEvent tor = (InternalEvent) to; tor.hEvent = this.hEvent; tor.nextState = this.nextState; return tor; } public InternalEvent clone() { return clone(new InternalEvent()); } public boolean hasNextState() { return true; } public Information.State getNextState() { return nextState; } public String toString() { return "Process " + happensAt.getLabel() + " takes an internal action"; } } }
10,053
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Viewpoint.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Viewpoint.java
package com.aexiz.daviz.glue; public abstract class Viewpoint extends Locus { public static class Channel extends Viewpoint { public static final String CLIENT_PROPERTY_EDGEMODEL = "edgemodel"; public static final String CLIENT_PROPERTY_FIRST_DIRECTED = "first_directed"; public final Node from; public final Node to; float weight = Float.NaN; transient Network network; public Channel(Node from, Node to) { if (from == null || to == null) throw null; this.from = from; this.to = to; } public void clearWeight() { this.weight = Float.NaN; } public void setWeight(float weight) { this.weight = weight; } public boolean hasWeight() { return weight == weight; } public float getWeight() { return weight; } public boolean equals(Object obj) { if (obj instanceof Channel) { return equals((Channel) obj); } return false; } public boolean equals(Channel other) { if (other == null) return false; return other.from.equals(from) && other.to.equals(to); } public int hashCode() { return 31 * from.hashCode() + to.hashCode(); } @Override public String toString() { return from.getLabel() + "-" + to.getLabel(); } } // This class should actually be "process", but because Java already has a // built-in class called Process, we can not name it so. Next time: prefix // model classes with a letter, like they do in Swing. public static class Node extends Viewpoint { public static final String CLIENT_PROPERTY_POSITION_X = "node_pos_x"; public static final String CLIENT_PROPERTY_POSITION_Y = "node_pos_y"; public static final String CLIENT_PROPERTY_NODEMODEL = "nodemodel"; private String label; // Transient fields transient Network network; // Haskell dependencies transient int hId; // Temporary fields transient boolean marked; public Node() { } public Node(String label) { setLabel(label); } public void setLabel(String label) { this.label = label; } public String getLabel() { return this.label == null ? "" : this.label; } @Override public String toString() { return this.label != null ? getLabel() : super.toString(); } } }
2,365
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Locus.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Locus.java
package com.aexiz.daviz.glue; import java.util.HashMap; public abstract class Locus { private HashMap<String,Object> clientProperties = new HashMap<String,Object>(); public void putClientProperty(String key, Object value) { if (value == null) { clientProperties.remove(key); } else { clientProperties.put(key, value); } } public boolean hasClientProperty(String key) { return clientProperties.containsKey(key); } public boolean hasClientProperty(String key, Class<?> type) { if (!clientProperties.containsKey(key)) return false; Object value = clientProperties.get(key); return type.isInstance(value); } public Object getClientProperty(String key) { return clientProperties.get(key); } }
764
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Execution.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Execution.java
package com.aexiz.daviz.glue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.aexiz.daviz.glue.Configuration.InitialConfiguration; import com.aexiz.daviz.sim.Event.TEvent; import com.aexiz.daviz.sim.Simulation.TSimulation; import frege.prelude.PreludeBase.TList; import frege.prelude.PreludeBase.TList.DCons; import frege.prelude.PreludeBase.TTuple2; public class Execution { // Properties Simulation simulation; Execution parent; // may be null for root Event lastEvent; // may be null for root // Transient fields transient Configuration configuration; transient List<Execution> successors; // Haskell dependencies transient TSimulation<Object,Object,Object> hSimulation; Execution() { } void loadFirst() { if (simulation == null) throw new Error("Invalid simulation"); if (!(configuration instanceof InitialConfiguration)) throw new Error("Invalid initial configuration"); GlueHelper helper = new GlueHelper(simulation); hSimulation = com.aexiz.daviz.sim.Simulation.simulation( configuration.hConfiguration, simulation.getAlgorithm().getProcessDescription(helper)); parent = null; lastEvent = null; // Reload configuration from Haskell configuration = null; unloadConfiguration(); } private void invariant() { if (simulation == null) throw new Error("Invalid simulation"); if (hSimulation == null) throw new Error("No Haskell simulation"); } private void unloadConfiguration() { invariant(); if (configuration != null) return; // 1. Set configuration, translated back from Haskell configuration = new Configuration(); configuration.simulation = simulation; configuration.hConfiguration = hSimulation.mem$config.call(); configuration.unload(); } private void unloadSuccessors() { invariant(); if (successors != null) return; successors = new ArrayList<>(); // 2. Check if there are any successors TList<TTuple2<TEvent<Object,Object,Object>,TSimulation<Object,Object,Object>>> succ = hSimulation.mem$successors.call(); while (succ.asCons() != null) { DCons<TTuple2<TEvent<Object,Object,Object>,TSimulation<Object,Object,Object>>> head = succ.asCons(); TTuple2<TEvent<Object,Object,Object>,TSimulation<Object,Object,Object>> tup = head.mem1.call(); Execution result = new Execution(); result.parent = this; result.simulation = simulation; result.hSimulation = tup.mem2.call(); result.lastEvent = Event.makeAndUnload(tup.mem1.call(), result); // Not unloading configuration // Not unloading successors successors.add(result); succ = succ.asCons().mem2.call(); } } // Traversal methods public boolean hasParent() { invariant(); return parent != null; } public Execution getParent() { invariant(); return parent; } public boolean hasNext() { unloadSuccessors(); return successors.size() != 0; } public int getNextCount() { unloadSuccessors(); return successors.size(); } public Execution getNext() { // Always choose first successor return getNext(0); } public Execution getNext(int index) { unloadSuccessors(); return successors.get(index); } public Execution[] getSuccessors() { Execution[] result = new Execution[getNextCount()]; for (int i = 0; i < result.length; i++) { result[i] = getNext(i); } return result; } public boolean hasEvents() { return hasParent(); } public Event[] getLinkedEvents() { ArrayList<Event> events = new ArrayList<Event>(); // Traverse and collect Execution elem = this; while (elem.parent != null) { events.add(elem.lastEvent); elem = elem.parent; } // Reverse Collections.reverse(events); // Match and link Event.matchAndLinkEvents(events); return events.toArray(new Event[events.size()]); } public List<Execution> getExecutionPath() { ArrayList<Execution> result = new ArrayList<>(); // Traverse and collect Execution elem = this; while (elem != null) { result.add(elem); elem = elem.parent; } // Reverse Collections.reverse(result); return result; } public Event getLastEvent() { Event[] linkedEvents = getLinkedEvents(); return linkedEvents[linkedEvents.length - 1]; } // Property methods public Configuration getConfiguration() { unloadConfiguration(); return configuration; } }
4,506
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Configuration.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Configuration.java
package com.aexiz.daviz.glue; import java.io.PrintStream; import java.util.ArrayList; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Set.TSet; import com.aexiz.daviz.sim.Simulation.TConfiguration; import frege.prelude.PreludeBase.TEither; import frege.prelude.PreludeBase.TEither.DLeft; import frege.prelude.PreludeBase.TList; import frege.prelude.PreludeBase.TList.DCons; import frege.prelude.PreludeBase.TTuple2; import frege.run8.Thunk; public class Configuration { // Properties Simulation simulation; // Haskell dependencies transient TConfiguration<Object,Object,Object> hConfiguration; // Computed properties transient Viewpoint.Node[] processes; transient boolean[] processAlive; transient Information.State[] processState; transient Viewpoint.Channel[] channels; transient ArrayList<Information.Message>[] channelState; Configuration() { } void unload() { if (simulation == null) throw new Error("Invalid simulation"); if (hConfiguration == null) throw new Error("Invalid Haskell configuration"); // Assume network remains unchanged Algorithm alg = simulation.getAlgorithm(); GlueHelper helper = new GlueHelper(simulation); // 1. Read out state of each process processes = simulation.getNetwork().getNodes(); processAlive = new boolean[processes.length]; processState = new Information.State[processes.length]; for (int i = 0; i < processes.length; i++) { TEither<Object,Object> m = hConfiguration.mem2.call().apply(Thunk.lazy(processes[i].hId)).call(); DLeft<Object,Object> j = m.asLeft(); if (j == null) { processAlive[i] = false; processState[i] = null; // TODO unload result space } else { processAlive[i] = true; processState[i] = alg.makeAndUnloadState(helper, j.mem1.call()); } } // 2. Read out channel state channels = simulation.getNetwork().getChannels(); @SuppressWarnings("unchecked") ArrayList<Information.Message>[] o = (ArrayList<Information.Message>[]) new ArrayList<?>[channels.length]; channelState = o; for (int i = 0; i < channels.length; i++) { channelState[i] = new ArrayList<Information.Message>(); } TList<TTuple2<TTuple2<Integer, Integer>, Object>> l = hConfiguration.mem3.call(); while (l.asCons() != null) { DCons<TTuple2<TTuple2<Integer, Integer>, Object>> c = l.asCons(); TTuple2<TTuple2<Integer, Integer>, Object> cm = c.mem1.call(); int f = cm.mem1.call().mem1.call().intValue(); int t = cm.mem1.call().mem2.call().intValue(); Object msg = cm.mem2.call(); boolean found = false; for (int i = 0; i < channels.length; i++) { if (channels[i].from.hId == f && channels[i].to.hId == t) { channelState[i].add(alg.makeAndUnloadMessage(helper, msg)); found = true; break; } } if (!found) throw new Error("Network and simulation out-of-sync"); l = c.mem2.call(); } } public void printSummary(PrintStream out) { if (simulation == null) throw new Error("Invalid simulation"); if (processes == null) throw new Error("Configuration not unloaded"); for(int i = 0; i < processes.length; i++) { out.print("Process "); out.print(processes[i].getLabel()); out.print(": "); if (processAlive[i]) { out.print(processState[i]); } else { out.print("*terminated*"); } out.println(); } out.println(); for (int i = 0; i < channels.length; i++) { if (channelState[i].size() == 0) continue; out.print("Channel "); out.print(channels[i]); out.print(": "); for (Information.Message m : channelState[i]) { out.print(m); } out.println(); } out.println(); } public void loadProcessState(StateVisitor visitor) { for (int i = 0; i < processes.length; i++) { visitor.setState(processes[i], processState[i]); } } public interface StateVisitor { void setState(Viewpoint.Node process, Information.State state); } public static class InitialConfiguration extends Configuration { void load() { TSet<TTuple2<Integer, Integer>> network = simulation.getNetwork().hNetwork; GlueHelper helper = new GlueHelper(simulation); TProcessDescription<Object,Object,Object,Object> o = simulation.getAlgorithm().getProcessDescription(helper); hConfiguration = com.aexiz.daviz.sim.Simulation.<Object,Object,Object>initialConfiguration(network, o.simsalabim()); } } }
4,502
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Information.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Information.java
package com.aexiz.daviz.glue; public abstract class Information { Information() { } public static abstract class Message extends Information { public Message() { } public abstract String toString(); public abstract boolean equals(Object obj); } public static abstract class State extends Information { public State() { } public abstract String toString(); } public static abstract class Result extends Information { public Result() { } public abstract String toString(); } public interface PropertyBuilder { void simpleProperty(String name, String value); void compoundProperty(String name, PropertyVisitor visitor); } public interface PropertyVisitor { void buildProperties(PropertyBuilder builder); } public abstract void buildProperties(PropertyBuilder builder); }
878
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Assumption.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Assumption.java
package com.aexiz.daviz.glue; import java.util.List; import com.aexiz.daviz.glue.Viewpoint.Node; public class Assumption { // Configured by subclass protected boolean infiniteGraph; protected boolean directedGraph; protected boolean acylcicGraph; protected boolean dynamicGraph; protected boolean fifo_channels; // True if first-in-first-out channels protected boolean ooo_channels; // True if out-of-order channels protected boolean centralized_user; // User-input required Node initiator; // Given by user or undefined protected boolean decentralized_user; // User-input required List<Node> initiators; // Given by user or undefined protected boolean decentralized_computed; // No user-input, algorithm decides initiators protected boolean centralized_computed; // No user-input, algorithm decides initiator public void setInitiator(Node node) { if (!centralized_user) throw new Error("Algorithm is not centralized and not user-defined"); initiator = node; } public Node getInitiator() { if (initiator == null) throw new Error("Initiator is not set"); return initiator; } public boolean isDirectedGraph() { return directedGraph; } public boolean isAcyclicGraph() { return acylcicGraph; } public boolean isCentralized() { return centralized_user || centralized_computed; } public boolean isDecentralized() { return decentralized_user || decentralized_computed; } public boolean isInitiatorUser() { return centralized_user || decentralized_user; } }
1,581
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Simulation.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Simulation.java
package com.aexiz.daviz.glue; public class Simulation { // Properties private Algorithm algorithm; private Assumption assumption; private Network network; // Transient fields private transient Execution execution; public Simulation() { } public Simulation(Algorithm alg) { setAlgorithm(alg); } public void setAlgorithm(Algorithm alg) { algorithm = alg; assumption = alg.getAssumption(); if (assumption == null) throw new Error("Invalid algorithm assumptions"); } public Algorithm getAlgorithm() { if (algorithm == null) throw new Error("Algorithm is not set"); return algorithm; } public Assumption getAssumption() { if (assumption == null) throw new Error("Assumption is not set"); return assumption; } public void setNetwork(Network net) { if (net.simulation != null) throw new Error("Network owned by other simulation"); network = net; network.simulation = this; } public Network getNetwork() { if (network == null) throw new Error("Network is not set"); return network; } public void setInitiator(Viewpoint.Node proc) { if (assumption == null) throw new Error("No algorithm"); if (!assumption.centralized_user) throw new Error("Algorithm is not centralized by user-input"); if (network == null) throw new Error("Network is not set"); if (proc.network != network) throw new Error("Process not owned by simulation"); assumption.initiator = proc; } public boolean hasInitiator() { if (assumption == null) throw new Error("No algorithm"); return assumption.centralized_user; } public Viewpoint.Node getInitiator() { if (assumption == null) throw new Error("No algorithm"); if (!assumption.centralized_user) throw new Error("Algorithm is not centralized by user-input"); if (network == null) throw new Error("Network is not set"); return assumption.initiator; } public void load() { network.load(); Configuration.InitialConfiguration ic = new Configuration.InitialConfiguration(); ic.simulation = this; ic.load(); execution = new Execution(); execution.simulation = this; execution.configuration = ic; execution.loadFirst(); } public Execution getExecution() { return execution; } }
2,285
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Network.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/Network.java
package com.aexiz.daviz.glue; import java.util.ArrayList; import com.aexiz.daviz.sim.Set; import com.aexiz.daviz.sim.Set.TSet; import frege.prelude.PreludeBase.TTuple2; import frege.run8.Lazy; import frege.run8.Thunk; public class Network { private ArrayList<Viewpoint.Node> processes = new ArrayList<Viewpoint.Node>(); private ArrayList<Viewpoint.Channel> channels = new ArrayList<Viewpoint.Channel>(); // Simulation ownership transient Simulation simulation; // Haskell dependence transient TSet<TTuple2<Integer, Integer>> hNetwork; public Viewpoint.Node addNode(Viewpoint.Node p) { if (p.network != null) throw new Error("Process already owned by other network"); p.network = this; if (processes.contains(p)) return p; processes.add(p); return p; } public Viewpoint.Channel addChannel(Viewpoint.Channel c) { if (c.network != null) throw new Error("Channel already owned by other network"); c.network = this; int i = channels.indexOf(c); if (i == -1) { channels.add(c); return c; } else { return channels.get(i); } } public boolean hasChannel(Viewpoint.Node from, Viewpoint.Node to) { for (Viewpoint.Channel c : channels) { if (c.from == from && c.to == to) return true; } return false; } public Viewpoint.Node[] getNodes() { return processes.toArray(new Viewpoint.Node[processes.size()]); } public Viewpoint.Channel[] getChannels() { return channels.toArray(new Viewpoint.Channel[channels.size()]); } public void makeUndirected() { // Symmetric closure, loop over copy to prevent CME for (Viewpoint.Channel c : getChannels()) { addChannel(new Viewpoint.Channel(c.to, c.from)); } } public boolean isWeighted() { for (Viewpoint.Channel c : channels) { if (!c.hasWeight()) return false; } return true; } public boolean isStronglyConnected() { for (Viewpoint.Node n : processes) { n.marked = false; } if (processes.size() > 0) { Viewpoint.Node start = processes.get(0); floodFill(start); } for (Viewpoint.Node n : processes) { if (!n.marked) return false; } return true; } private void floodFill(Viewpoint.Node node) { if (node.marked) return; node.marked = true; for (Viewpoint.Channel c : channels) { if (c.from == node) floodFill(c.to); } } void load() { // 1. Construct unique Integers for processes int last = 1; for (Viewpoint.Node p : processes) { p.hId = last++; } // 2. Construct set of edge tuples // 2.1. Empty set hNetwork = Set.<TTuple2<Integer, Integer>>emptyS().call(); for (Viewpoint.Channel c : channels) { // 2.2. Construct one element Lazy<Integer> from = Thunk.lazy(c.from.hId); Lazy<Integer> to = Thunk.lazy(c.to.hId); TTuple2<Integer, Integer> ch = TTuple2.<Integer,Integer>mk(from, to); // 2.3. Add one element to set hNetwork = Set.addS(hNetwork, ch); } } Viewpoint.Node getNodeById(int hId) { for (Viewpoint.Node p : processes) { if (p.hId == hId) return p; } throw new Error("Haskell processes out-of-sync"); } }
3,176
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
GlueHelper.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/GlueHelper.java
package com.aexiz.daviz.glue; import java.util.ArrayList; import com.aexiz.daviz.sim.Set.TSet; import static com.aexiz.daviz.sim.Set.glueTuple2IntNormalS; import static com.aexiz.daviz.sim.Set.glueIntNormalS; import frege.prelude.PreludeBase.TList; import frege.prelude.PreludeBase.TList.DCons; import frege.prelude.PreludeBase.TTuple2; public class GlueHelper { private Simulation simulation; GlueHelper(Simulation sim) { simulation = sim; } public int getIdByNode(Viewpoint.Node node) { return node.hId; } public Viewpoint.Node getNodeById(int id) { for (Viewpoint.Node p : simulation.getNetwork().getNodes()) { if (p.hId == id) return p; } throw new Error("Network and Haskell out-of-sync"); } public Viewpoint.Channel getChannelByIds(int from, int to) { for (Viewpoint.Channel c : simulation.getNetwork().getChannels()) { if (c.from.hId == from && c.to.hId == to) return c; } throw new Error("Network and Haskell out-of-sync"); } public Viewpoint.Channel getChannelByTuple(TTuple2<Integer, Integer> tuple) { int from = tuple.mem1.call().intValue(); int to = tuple.mem2.call().intValue(); return getChannelByIds(from, to); } public ArrayList<Viewpoint.Channel> forEdgeSet(TSet<TTuple2<Integer, Integer>> set) { ArrayList<Viewpoint.Channel> result = new OrderedSetList<Viewpoint.Channel>(); TList<TTuple2<Integer,Integer>> l = glueTuple2IntNormalS(set); while (l.asCons() != null) { DCons<TTuple2<Integer,Integer>> c = l.asCons(); TTuple2<Integer,Integer> t = c.mem1.call(); result.add(getChannelByTuple(t)); l = c.mem2.call(); } return result; } public ArrayList<Viewpoint.Node> forVertexSet(TSet<Integer> set) { ArrayList<Viewpoint.Node> result = new OrderedSetList<Viewpoint.Node>(); TList<Integer> l = glueIntNormalS(set); while (l.asCons() != null) { DCons<Integer> c = l.asCons(); result.add(getNodeById(c.mem1.call())); l = c.mem2.call(); } return result; } } class OrderedSetList<T> extends ArrayList<T> { private static final long serialVersionUID = -7310476084643000609L; public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (T c : this) { if (first) first = false; else sb.append(','); sb.append(c); } sb.append('}'); return sb.toString(); } }
2,446
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Awerbuch.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Awerbuch.java
package com.aexiz.daviz.glue.alg; import java.util.List; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.sim.Awerbuch.TMS; import com.aexiz.daviz.sim.Awerbuch.TPS; import com.aexiz.daviz.sim.Awerbuch.TRRRUII; import static com.aexiz.daviz.sim.Awerbuch.procDesc; import com.aexiz.daviz.sim.Process.TProcessDescription; import frege.prelude.PreludeBase.TMaybe.DJust; import frege.prelude.PreludeBase.TTuple2; import frege.run8.Thunk; public class Awerbuch extends Algorithm { public Awerbuch() { assumption = new Assumption() { { centralized_user = true; } }; } protected Information.Message makeAndUnloadMessage(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class AwerbuchMessage extends Information.Message { } class AwerbuchToken extends AwerbuchMessage { public String toString() { return "*token*"; } public boolean equals(Object obj) { if (obj instanceof AwerbuchToken) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Token"); } } class AwerbuchInfo extends AwerbuchMessage { public String toString() { return "*info*"; } public boolean equals(Object obj) { if (obj instanceof AwerbuchInfo) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Info"); } } class AwerbuchAck extends AwerbuchMessage { public String toString() { return "*ack*"; } public boolean equals(Object obj) { if (obj instanceof AwerbuchAck) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Ack"); } } Short t = (Short) o; if (t == TMS.Token) { return new AwerbuchToken(); } else if (t == TMS.Inf) { return new AwerbuchInfo(); } else if (t == TMS.Ack) { return new AwerbuchAck(); } else throw new Error("Unknown message"); } protected Information.State makeAndUnloadState(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class AwerbuchRRRUII implements PropertyVisitor { } class AwerbuchState extends Information.State { boolean hasToken; AwerbuchRRRUII rrruii; List<Channel> inform; List<Channel> acked; Channel intended; List<Channel> forward; List<Channel> info; Channel last; Channel toAck; public String toString() { return "(" + hasToken + "," + rrruii + "," + inform + "," + acked + "," + intended + "," + forward + "," + info + "," + last + "," + toAck + ")"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Has token?", String.valueOf(hasToken)); builder.compoundProperty("State", rrruii); builder.compoundProperty("Informing", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", inform.size() + " elements"); for (int i = 0, size = inform.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", inform.get(i).to.getLabel()); } } }); builder.compoundProperty("Waiting for", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", acked.size() + " elements"); for (int i = 0, size = acked.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", acked.get(i).to.getLabel()); } } }); builder.simpleProperty("Token to:", intended == null ? "None" : intended.to.getLabel()); builder.compoundProperty("Candidates", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", forward.size() + " elements"); for (int i = 0, size = forward.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", forward.get(i).to.getLabel()); } } }); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", info.size() + " elements"); for (int i = 0, size = info.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", info.get(i).to.getLabel()); } } }); builder.simpleProperty("Reply to:", last == null ? "None" : last.to.getLabel()); builder.simpleProperty("Ack:", toAck == null ? "None" : toAck.to.getLabel()); } } class AwerbuchReceivedSeen extends AwerbuchRRRUII { private Channel c; public String toString() { return "ReceivedSeen<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("Seen token?", "true"); builder.simpleProperty("From:", c.to.getLabel()); } } class AwerbuchReceivedUnseen extends AwerbuchRRRUII { private Channel c; public String toString() { return "ReceivedUnseen<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("Seen token?", "false"); builder.simpleProperty("From:", c.to.getLabel()); } } class AwerbuchReplied extends AwerbuchRRRUII { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Replied"); builder.simpleProperty("To:", c.to.getLabel()); } } class AwerbuchUndefined extends AwerbuchRRRUII { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class AwerbuchInitiatorSeen extends AwerbuchRRRUII { public String toString() { return "InitiatorSeen"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); builder.simpleProperty("Seen token?", "true"); } } class AwerbuchInitiatorUnseen extends AwerbuchRRRUII { public String toString() { return "InitiatorUnseen"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); builder.simpleProperty("Seen token?", "false"); } } TPS st = (TPS) o; AwerbuchState result = new AwerbuchState(); result.hasToken = st.mem$hasToken.call(); TRRRUII rrruii = st.mem$state.call(); if (rrruii.asReceivedSeen() != null) { AwerbuchReceivedSeen r = new AwerbuchReceivedSeen(); r.c = help.getChannelByTuple(rrruii.asReceivedSeen().mem1.call()); result.rrruii = r; } else if (rrruii.asReceivedUnseen() != null) { AwerbuchReceivedUnseen r = new AwerbuchReceivedUnseen(); r.c = help.getChannelByTuple(rrruii.asReceivedUnseen().mem1.call()); result.rrruii = r; } else if (rrruii.asReplied() != null) { AwerbuchReplied r = new AwerbuchReplied(); r.c = help.getChannelByTuple(rrruii.asReplied().mem1.call()); result.rrruii = r; } else if (rrruii.asUndefined() != null) { result.rrruii = new AwerbuchUndefined(); } else if (rrruii.asInitiatorSeen() != null) { result.rrruii = new AwerbuchInitiatorSeen(); } else if (rrruii.asInitiatorUnseen() != null) { result.rrruii = new AwerbuchInitiatorUnseen(); } else { throw new Error("Invalid RRRUII value"); } DJust<TTuple2<Integer, Integer>> in; result.inform = help.forEdgeSet(st.mem$inform.call()); result.acked = help.forEdgeSet(st.mem$acked.call()); in = st.mem$intended.call().asJust(); result.intended = in == null ? null : help.getChannelByTuple(in.mem1.call()); result.forward = help.forEdgeSet(st.mem$forward.call()); result.info = help.forEdgeSet(st.mem$info.call()); in = st.mem$last.call().asJust(); result.last = in == null ? null : help.getChannelByTuple(in.mem1.call()); in = st.mem$toAck.call().asJust(); result.toAck = in == null ? null : help.getChannelByTuple(in.mem1.call()); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class AwerbuchTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Terminated"); } } class AwerbuchDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Decided"); } } boolean result = (Boolean) o; if (result) { return new AwerbuchTerminated(); } else { return new AwerbuchDecided(); } } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
9,464
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Visited.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Visited.java
package com.aexiz.daviz.glue.alg; import java.util.List; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.sim.Visited.TRRUI; import static com.aexiz.daviz.sim.Visited.procDesc; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Set.TSet; import frege.prelude.PreludeBase.TMaybe; import frege.prelude.PreludeBase.TMaybe.DJust; import frege.prelude.PreludeBase.TTuple2; import frege.prelude.PreludeBase.TTuple3; import frege.run8.Thunk; public class Visited extends Algorithm { public Visited() { assumption = new Assumption() { { centralized_user = true; } }; } protected Information.Message makeAndUnloadMessage(GlueHelper help, Object o) { if (help == null || o == null) throw null; class VisitedMessage extends Information.Message { List<Node> visited; public String toString() { return "*token* " + visited; } public boolean equals(Object obj) { if (obj instanceof VisitedMessage) { VisitedMessage other = (VisitedMessage) obj; return other.visited.equals(visited); } return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Token"); builder.compoundProperty("Visited", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", visited.size() + " elements"); for (int i = 0, size = visited.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", visited.get(i).getLabel()); } } }); } } @SuppressWarnings("unchecked") TSet<Integer> t = (TSet<Integer>) o; VisitedMessage result = new VisitedMessage(); result.visited = help.forVertexSet(t); return result; } protected Information.State makeAndUnloadState(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class VisitedRRUI implements PropertyVisitor { } class VisitedState extends Information.State { List<Node> hasToken; VisitedRRUI rrui; List<Channel> neighbors; public String toString() { return "(" + hasToken + "," + rrui + "," + neighbors + ")"; } @Override public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Has token?", hasToken == null ? "false" : hasToken.toString()); builder.compoundProperty("State", rrui); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neighbors.size() + " elements"); for (int i = 0, size = neighbors.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neighbors.get(i).to.getLabel()); } } }); } } class VisitedReceived extends VisitedRRUI { private Channel c; public String toString() { return "Received<" + c + ">"; } @Override public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("From:", c.to.getLabel()); } } class VisitedReplied extends VisitedRRUI { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Replied"); builder.simpleProperty("To:", c.to.getLabel()); } } class VisitedUndefined extends VisitedRRUI { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class VisitedInitiator extends VisitedRRUI { public String toString() { return "Initiator"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); } } @SuppressWarnings("unchecked") TTuple3<TMaybe<TSet<Integer>>, TRRUI, TSet<TTuple2<Integer, Integer>>> st = (TTuple3<TMaybe<TSet<Integer>>, TRRUI, TSet<TTuple2<Integer, Integer>>>) o; VisitedState result = new VisitedState(); DJust<TSet<Integer>> tok = st.mem1.call().asJust(); result.hasToken = tok == null ? null : help.forVertexSet(tok.mem1.call()); TRRUI rrui = st.mem2.call(); if (rrui.asReceived() != null) { VisitedReceived r = new VisitedReceived(); r.c = help.getChannelByTuple(rrui.asReceived().mem1.call()); result.rrui = r; } else if (rrui.asReplied() != null) { VisitedReplied r = new VisitedReplied(); r.c = help.getChannelByTuple(rrui.asReplied().mem1.call()); result.rrui = r; } else if (rrui.asUndefined() != null) { result.rrui = new VisitedUndefined(); } else if (rrui.asInitiator() != null) { result.rrui = new VisitedInitiator(); } else { throw new Error("Invalid RRUI value"); } result.neighbors = help.forEdgeSet(st.mem3.call()); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class VisitedTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Terminated"); } } class VisitedDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Decided"); } } boolean result = (Boolean) o; if (result) { return new VisitedTerminated(); } else { return new VisitedDecided(); } } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
6,166
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Tarry.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Tarry.java
package com.aexiz.daviz.glue.alg; import java.util.List; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Set.TSet; import com.aexiz.daviz.sim.Tarry.TDUI; import static com.aexiz.daviz.sim.Tarry.procDesc; import frege.prelude.PreludeBase.TTuple2; import frege.prelude.PreludeBase.TTuple3; import frege.run8.Thunk; public class Tarry extends Algorithm { public Tarry() { assumption = new Assumption() { { centralized_user = true; } }; } protected Information.Message makeAndUnloadMessage(GlueHelper help, Object o) { if (help == null || o == null) throw null; class TarryMessage extends Information.Message { public String toString() { return "*token*"; } public boolean equals(Object obj) { if (obj instanceof TarryMessage) return true; return false; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Token"); } } Short t = (Short) o; if (t != 0) throw new Error("Invalid Haskell unit"); return new TarryMessage(); } protected Information.State makeAndUnloadState(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class TarryDUI implements PropertyVisitor { } class TarryState extends Information.State { boolean hasToken; TarryDUI dui; List<Channel> neighbors; public String toString() { return "(" + hasToken + "," + dui + "," + neighbors + ")"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Has token?", String.valueOf(hasToken)); builder.compoundProperty("State", dui); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neighbors.size() + " elements"); for (int i = 0, size = neighbors.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neighbors.get(i).to.getLabel()); } } }); } } class TarryReceived extends TarryDUI { private Channel c; public String toString() { return "Received<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("From:", c.to.getLabel()); } } class TarryReplied extends TarryDUI { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Replied"); builder.simpleProperty("To:", c.to.getLabel()); } } class TarryUndefined extends TarryDUI { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class TarryInitiator extends TarryDUI { public String toString() { return "Initiator"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); } } @SuppressWarnings("unchecked") TTuple3<Boolean, TDUI, TSet<TTuple2<Integer, Integer>>> st = (TTuple3<Boolean, TDUI, TSet<TTuple2<Integer, Integer>>>) o; TarryState result = new TarryState(); result.hasToken = st.mem1.call(); TDUI dui = st.mem2.call(); if (dui.asReceived() != null) { TarryReceived r = new TarryReceived(); r.c = help.getChannelByTuple(dui.asReceived().mem1.call()); result.dui = r; } else if (dui.asReplied() != null) { TarryReplied r = new TarryReplied(); r.c = help.getChannelByTuple(dui.asReplied().mem1.call()); result.dui = r; } else if (dui.asUndefined() != null) { result.dui = new TarryUndefined(); } else if (dui.asInitiator() != null) { result.dui = new TarryInitiator(); } else { throw new Error("Invalid DUI value"); } result.neighbors = help.forEdgeSet(st.mem3.call()); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class TarryTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Terminated"); } } class TarryDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Decided"); } } boolean result = (Boolean) o; if (result) { return new TarryDecided(); } else { return new TarryTerminated(); } } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
5,247
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
TreeAck.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/TreeAck.java
package com.aexiz.daviz.glue.alg; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.Message; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.glue.Information.State; import com.aexiz.daviz.glue.Viewpoint.Channel; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.TreeAck.TPS; import com.aexiz.daviz.sim.TreeAck.TMS; import com.aexiz.daviz.sim.TreeAck.TUPDS; import static com.aexiz.daviz.sim.TreeAck.procDesc; import java.util.List; public class TreeAck extends Algorithm { public TreeAck() { assumption = new Assumption() { { acylcicGraph = true; decentralized_computed = true; } }; } protected Message makeAndUnloadMessage(GlueHelper helper, Object o) { abstract class TreeAckMessage extends Information.Message { } class TreeAckInfoMessage extends TreeAckMessage { public String toString() { return "*info*"; } public boolean equals(Object obj) { if (obj instanceof TreeAckInfoMessage) return true; return false; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Info"); } } class TreeAckAckMessage extends TreeAckMessage { public String toString() { return "*ack*"; } public boolean equals(Object obj) { if (obj instanceof TreeAckAckMessage) return true; return false; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Ack"); } } Short t = (Short) o; if (t == TMS.Info) return new TreeAckInfoMessage(); if (t == TMS.Ack) return new TreeAckAckMessage(); throw new Error("Invalid message"); } protected State makeAndUnloadState(GlueHelper helper, Object o) { abstract class TreeAckUPDS implements PropertyVisitor { } class TreeAckState extends Information.State { List<Channel> neighbors; List<Channel> children; TreeAckUPDS state; public String toString() { return "(" + neighbors + "," + children + "," + state + ")"; } public void buildProperties(PropertyBuilder builder) { builder.compoundProperty("State", state); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neighbors.size() + " elements"); for (int i = 0, size = neighbors.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neighbors.get(i).to.getLabel()); } } }); builder.compoundProperty("Children", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", children.size() + " elements"); for (int i = 0, size = children.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", children.get(i).to.getLabel()); } } }); } } class TreeAckUndefined extends TreeAckUPDS { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class TreeAckParent extends TreeAckUPDS { private Channel c; public String toString() { return "Parent<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Parent:", c.to.getLabel()); } } class TreeAckDecider extends TreeAckUPDS { private Channel c; public String toString() { return "Decider<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Decider:", c.to.getLabel()); } } class TreeAckSpreader extends TreeAckUPDS { private Channel c; public String toString() { return "Spreader<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Spreader:", c.to.getLabel()); } } TPS st = (TPS) o; TreeAckState result = new TreeAckState(); result.neighbors = helper.forEdgeSet(st.mem$neighbors.call()); result.children = helper.forEdgeSet(st.mem$children.call()); TUPDS up = st.mem$state.call(); if (up.asUndefined() != null) { TreeAckUndefined r = new TreeAckUndefined(); result.state = r; } else if (up.asParent() != null) { TreeAckParent r = new TreeAckParent(); r.c = helper.getChannelByTuple(up.asParent().mem1.call()); result.state = r; } else if (up.asDecider() != null) { TreeAckDecider r = new TreeAckDecider(); r.c = helper.getChannelByTuple(up.asDecider().mem1.call()); result.state = r; } else if (up.asSpreader() != null) { TreeAckSpreader r = new TreeAckSpreader(); r.c = helper.getChannelByTuple(up.asSpreader().mem1.call()); result.state = r; } else throw new Error(); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class TreeAckDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Decided"); } } class TreeAckTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Terminated"); } } boolean t = (Boolean) o; if (t) return new TreeAckDecided(); else return new TreeAckTerminated(); } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc.call().simsalabim(); } }
5,902
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Echo.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Echo.java
package com.aexiz.daviz.glue.alg; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.Message; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.glue.Information.State; import com.aexiz.daviz.glue.Viewpoint.Channel; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Echo.TPS; import com.aexiz.daviz.sim.Echo.TMS; import com.aexiz.daviz.sim.Echo.TRRUI; import static com.aexiz.daviz.sim.Echo.procDesc; import frege.run8.Thunk; import java.util.List; public class Echo extends Algorithm { public Echo() { assumption = new Assumption() { { centralized_user = true; } }; } protected Message makeAndUnloadMessage(GlueHelper helper, Object o) { class EchoMessage extends Information.Message { public String toString() { return "*broadcast*"; } public boolean equals(Object obj) { if (obj instanceof EchoMessage) return true; return false; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Broadcast"); } } Short t = (Short) o; if (t == TMS.Broadcast) return new EchoMessage(); throw new Error("Invalid message"); } protected State makeAndUnloadState(GlueHelper helper, Object o) { abstract class EchoRRUI implements PropertyVisitor { } class EchoState extends Information.State { List<Channel> neighbors; List<Channel> children; EchoRRUI state; public String toString() { return "(" + neighbors + "," + children + "," + state + ")"; } public void buildProperties(PropertyBuilder builder) { builder.compoundProperty("State", state); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neighbors.size() + " elements"); for (int i = 0, size = neighbors.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neighbors.get(i).to.getLabel()); } } }); builder.compoundProperty("Children", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", children.size() + " elements"); for (int i = 0, size = children.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", children.get(i).to.getLabel()); } } }); } } class EchoUndefined extends EchoRRUI { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class EchoInitiator extends EchoRRUI { public String toString() { return "Initiator"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); } } class EchoReceived extends EchoRRUI { private Channel c; public String toString() { return "Received<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Received:", c.to.getLabel()); } } class EchoReplied extends EchoRRUI { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Replied:", c.to.getLabel()); } } TPS st = (TPS) o; EchoState result = new EchoState(); result.neighbors = helper.forEdgeSet(st.mem$neighbors.call()); result.children = helper.forEdgeSet(st.mem$children.call()); TRRUI up = st.mem$state.call(); if (up.asUndefined() != null) { EchoUndefined r = new EchoUndefined(); result.state = r; } else if (up.asInitiator() != null) { EchoInitiator r = new EchoInitiator(); result.state = r; } else if (up.asReceived() != null) { EchoReceived r = new EchoReceived(); r.c = helper.getChannelByTuple(up.asReceived().mem1.call()); result.state = r; } else if (up.asReplied() != null) { EchoReplied r = new EchoReplied(); r.c = helper.getChannelByTuple(up.asReplied().mem1.call()); result.state = r; } else throw new Error(); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class TreeAckDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Decided"); } } class TreeAckTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Terminated"); } } boolean t = (Boolean) o; if (t) return new TreeAckDecided(); else return new TreeAckTerminated(); } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
5,313
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DFS.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/DFS.java
package com.aexiz.daviz.glue.alg; import java.util.List; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.sim.DFS.TRRUI; import static com.aexiz.daviz.sim.DFS.procDesc; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Set.TSet; import frege.prelude.PreludeBase.TMaybe; import frege.prelude.PreludeBase.TMaybe.DJust; import frege.prelude.PreludeBase.TTuple2; import frege.prelude.PreludeBase.TTuple4; import frege.run8.Thunk; public class DFS extends Algorithm { public DFS() { assumption = new Assumption() { { centralized_user = true; } }; } protected Information.Message makeAndUnloadMessage(GlueHelper help, Object o) { if (help == null || o == null) throw null; class DFS_Message extends Information.Message { public String toString() { return "*token*"; } public boolean equals(Object obj) { if (obj instanceof DFS_Message) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Token"); } } Short t = (Short) o; if (t != 0) throw new Error("Invalid Haskell unit"); return new DFS_Message(); } protected Information.State makeAndUnloadState(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class DFS_RRUI implements PropertyVisitor { } class DFS_State extends Information.State { boolean hasToken; DFS_RRUI rrui; List<Channel> neighbors; Channel incoming; public String toString() { return "(" + hasToken + "," + rrui + "," + neighbors + "," + incoming + ")"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Has token?", String.valueOf(hasToken)); builder.compoundProperty("State", rrui); builder.simpleProperty("Reply to:", incoming == null ? "None" : incoming.to.getLabel()); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neighbors.size() + " elements"); for (int i = 0, size = neighbors.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neighbors.get(i).to.getLabel()); } } }); } } class DFS_Received extends DFS_RRUI { private Channel c; public String toString() { return "Received<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("From:", c.to.getLabel()); } } class DFS_Replied extends DFS_RRUI { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Replied"); builder.simpleProperty("To:", c.to.getLabel()); } } class DFS_Undefined extends DFS_RRUI { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class DFS_Initiator extends DFS_RRUI { public String toString() { return "Initiator"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); } } @SuppressWarnings("unchecked") TTuple4<Boolean, TRRUI, TSet<TTuple2<Integer, Integer>>, TMaybe<TTuple2<Integer, Integer>>> st = (TTuple4<Boolean, TRRUI, TSet<TTuple2<Integer, Integer>>, TMaybe<TTuple2<Integer, Integer>>>) o; DFS_State result = new DFS_State(); result.hasToken = st.mem1.call(); TRRUI rrui = st.mem2.call(); if (rrui.asReceived() != null) { DFS_Received r = new DFS_Received(); r.c = help.getChannelByTuple(rrui.asReceived().mem1.call()); result.rrui = r; } else if (rrui.asReplied() != null) { DFS_Replied r = new DFS_Replied(); r.c = help.getChannelByTuple(rrui.asReplied().mem1.call()); result.rrui = r; } else if (rrui.asUndefined() != null) { result.rrui = new DFS_Undefined(); } else if (rrui.asInitiator() != null) { result.rrui = new DFS_Initiator(); } else { throw new Error("Invalid RRUI value"); } result.neighbors = help.forEdgeSet(st.mem3.call()); DJust<TTuple2<Integer, Integer>> in = st.mem4.call().asJust(); result.incoming = in == null ? null : help.getChannelByTuple(in.mem1.call()); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class DFSTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Terminated"); } } class DFSDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Decided"); } } boolean result = (Boolean) o; if (result) { return new DFSTerminated(); } else { return new DFSDecided(); } } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
5,676
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Tree.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Tree.java
package com.aexiz.daviz.glue.alg; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Information.Message; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.glue.Information.State; import com.aexiz.daviz.glue.Viewpoint.Channel; import com.aexiz.daviz.sim.Process.TProcessDescription; import com.aexiz.daviz.sim.Tree.TPS; import com.aexiz.daviz.sim.Tree.TUP; import static com.aexiz.daviz.sim.Tree.procDesc; import java.util.List; public class Tree extends Algorithm { public Tree() { assumption = new Assumption() { { acylcicGraph = true; decentralized_computed = true; } }; } protected Message makeAndUnloadMessage(GlueHelper helper, Object o) { class TreeMessage extends Information.Message { public String toString() { return "*info*"; } public boolean equals(Object obj) { if (obj instanceof TreeMessage) return true; return false; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Info"); } } Short t = (Short) o; if (t != 0) throw new Error("Invalid Haskell unit"); return new TreeMessage(); } protected State makeAndUnloadState(GlueHelper helper, Object o) { abstract class TreeUP implements PropertyVisitor { } class TreeState extends Information.State { List<Channel> neigh; TreeUP state; public String toString() { return "(" + neigh + "," + state + ")"; } public void buildProperties(PropertyBuilder builder) { builder.compoundProperty("State", state); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", neigh.size() + " elements"); for (int i = 0, size = neigh.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", neigh.get(i).to.getLabel()); } } }); } } class TreeUndefined extends TreeUP { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class TreeParent extends TreeUP { private Channel c; public String toString() { return "Parent<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Parent:", c.to.getLabel()); } } TPS st = (TPS) o; TreeState result = new TreeState(); result.neigh = helper.forEdgeSet(st.mem$neigh.call()); TUP up = st.mem$state.call(); if (up.asUndefined() != null) { TreeUndefined r = new TreeUndefined(); result.state = r; } else if (up.asParent() != null) { TreeParent r = new TreeParent(); r.c = helper.getChannelByTuple(up.asParent().mem1.call()); result.state = r; } else throw new Error(); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class TreeResult extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder visitor) { visitor.simpleProperty("", "Decided"); } } Short t = (Short) o; if (t != 0) throw new Error("Invalid Haskell unit"); return new TreeResult(); } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc.call().simsalabim(); } }
3,692
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Cidon.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/glue/alg/Cidon.java
package com.aexiz.daviz.glue.alg; import java.util.List; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Assumption; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.GlueHelper; import com.aexiz.daviz.glue.Information; import com.aexiz.daviz.glue.Network; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.sim.Cidon.TMS; import com.aexiz.daviz.sim.Cidon.TPS; import com.aexiz.daviz.sim.Cidon.TRRUI; import static com.aexiz.daviz.sim.Cidon.procDesc; import com.aexiz.daviz.sim.Process.TProcessDescription; import frege.prelude.PreludeBase.TMaybe.DJust; import frege.prelude.PreludeBase.TTuple2; import frege.run8.Thunk; public class Cidon extends Algorithm { public Cidon() { assumption = new Assumption() { { centralized_user = true; } }; } private static MaxRounds MAX_ROUNDS = new MaxRounds() { public int maxRounds(Network network) { return (network.getNodes().length + network.getChannels().length) * 15; } }; public MaxRounds getMaxRounds() { return MAX_ROUNDS; } protected Information.Message makeAndUnloadMessage(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class CidonMessage extends Information.Message { } class CidonToken extends CidonMessage { public String toString() { return "*token*"; } public boolean equals(Object obj) { if (obj instanceof CidonToken) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Token"); } } class CidonInfo extends CidonMessage { public String toString() { return "*info*"; } public boolean equals(Object obj) { if (obj instanceof CidonInfo) return true; return false; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Info"); } } Short t = (Short) o; if (t == TMS.Token) { return new CidonToken(); } else if (t == TMS.Inf) { return new CidonInfo(); } else throw new Error("Unknown message"); } protected Information.State makeAndUnloadState(GlueHelper help, Object o) { if (help == null || o == null) throw null; abstract class CidonRRUI implements PropertyVisitor { } class CidonState extends Information.State { boolean hasToken; CidonRRUI rrui; Channel intention; List<Channel> forward; List<Channel> info; public String toString() { return "(" + hasToken + "," + rrui + "," + intention + "," + forward + "," + info + ")"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("Has token?", String.valueOf(hasToken)); builder.compoundProperty("State", rrui); builder.simpleProperty("Token to:", intention == null ? "None" : intention.to.getLabel()); builder.compoundProperty("Candidates", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", forward.size() + " elements"); for (int i = 0, size = forward.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", forward.get(i).to.getLabel()); } } }); builder.compoundProperty("Neighbors", new PropertyVisitor() { public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", info.size() + " elements"); for (int i = 0, size = info.size(); i < size; i++) { builder.simpleProperty(String.valueOf(i) + ":", info.get(i).to.getLabel()); } } }); } } class CidonReceived extends CidonRRUI { private Channel c; public String toString() { return "Received<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Received"); builder.simpleProperty("From:", c.to.getLabel()); } } class CidonReplied extends CidonRRUI { private Channel c; public String toString() { return "Replied<" + c + ">"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Replied"); builder.simpleProperty("To:", c.to.getLabel()); } } class CidonUndefined extends CidonRRUI { public String toString() { return "Undefined"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Undefined"); } } class CidonInitiator extends CidonRRUI { public String toString() { return "Initiator"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Initiator"); } } TPS st = (TPS) o; CidonState result = new CidonState(); result.hasToken = st.mem$hasToken.call(); TRRUI rrui = st.mem$state.call(); if (rrui.asReceived() != null) { CidonReceived r = new CidonReceived(); r.c = help.getChannelByTuple(rrui.asReceived().mem1.call()); result.rrui = r; } else if (rrui.asReplied() != null) { CidonReplied r = new CidonReplied(); r.c = help.getChannelByTuple(rrui.asReplied().mem1.call()); result.rrui = r; } else if (rrui.asUndefined() != null) { result.rrui = new CidonUndefined(); } else if (rrui.asInitiator() != null) { result.rrui = new CidonInitiator(); } else { throw new Error("Invalid RRUI value"); } DJust<TTuple2<Integer, Integer>> in; in = st.mem$intention.call().asJust(); result.intention = in == null ? null : help.getChannelByTuple(in.mem1.call()); result.forward = help.forEdgeSet(st.mem$forward.call()); result.info = help.forEdgeSet(st.mem$info.call()); return result; } protected Result makeAndUnloadResult(GlueHelper helper, Object o) { class CidonTerminated extends Information.Result { public String toString() { return "Terminated"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Terminated"); } } class CidonDecided extends Information.Result { public String toString() { return "Decided"; } public void buildProperties(PropertyBuilder builder) { builder.simpleProperty("", "Decided"); } } boolean result = (Boolean) o; if (result) { return new CidonTerminated(); } else { return new CidonDecided(); } } protected TProcessDescription<Object, Object, Object, Object> getProcessDescription(GlueHelper helper) { return procDesc(Thunk.lazy(helper.getIdByNode(assumption.getInitiator()))).simsalabim(); } }
6,687
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ImageRoot.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/images/ImageRoot.java
package com.aexiz.daviz.images; public class ImageRoot { public static final String copyright = "Farm-Fresh v3.92, 10-04-2014 http://www.fatcow.com/free-icons"; private ImageRoot() {} }
195
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
AlgorithmSelection.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/AlgorithmSelection.java
package com.aexiz.daviz.ui; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.alg.*; class AlgorithmSelection { String name; Object alg; // use Object to avoid pulling in Algorithm class AlgorithmSelection(String name, Object alg) { this.name = name; this.alg = alg; } public String toString() { return name; } // It is necessary to expose the same methods as assumption, since // we do not want other classes depend on the class of Assumption. // It may pull in other classes compiled by Frege, which is too slow. public boolean isDirectedGraph() { return ((Algorithm) alg).getAssumption().isDirectedGraph(); } public boolean isAcyclicGraph() { return ((Algorithm) alg).getAssumption().isAcyclicGraph(); } public boolean isCentralized() { return ((Algorithm) alg).getAssumption().isCentralized(); } public boolean isDecentralized() { return ((Algorithm) alg).getAssumption().isDecentralized(); } public boolean isInitiatorUser() { return ((Algorithm) alg).getAssumption().isInitiatorUser(); } static AlgorithmSelection[] getAlgorithms() { // The class loader will pull in the Haskell dependencies return new AlgorithmSelection[]{ TARRY, DFS, VISITED, AWERBUCH, CIDON, TREE, TREEACK, ECHO, }; } static AlgorithmSelection TARRY = new AlgorithmSelection("Tarry", new Tarry()); static AlgorithmSelection DFS = new AlgorithmSelection("DFS", new DFS()); static AlgorithmSelection VISITED = new AlgorithmSelection("DFS + Visited", new Visited()); static AlgorithmSelection AWERBUCH = new AlgorithmSelection("Awerbuch", new Awerbuch()); static AlgorithmSelection CIDON = new AlgorithmSelection("Cidon", new Cidon()); static AlgorithmSelection TREE = new AlgorithmSelection("Tree", new Tree()); static AlgorithmSelection TREEACK = new AlgorithmSelection("Tree + Ack", new TreeAck()); static AlgorithmSelection ECHO = new AlgorithmSelection("Echo", new Echo()); }
2,048
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ControlFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/ControlFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.net.URI; import java.util.ArrayList; import java.util.concurrent.Callable; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.WindowConstants; import com.aexiz.daviz.images.ImageRoot; import com.aexiz.daviz.ui.swing.JAssignmentField; import com.aexiz.daviz.ui.swing.JCoolBar; import com.aexiz.daviz.ui.swing.GraphModel.NodeModel; public class ControlFrame extends JFrame { private static final long serialVersionUID = 6858557427390573562L; private static final boolean SHOW_TESTCASE_MENU = true; AboutFrame about; Controller controller; Handler handler; JCoolBar toolbar; JPanel pane; JComboBox<AlgorithmSelection> algorithmsBox; JLabel assumptionAcyclic; JLabel assumptionCentralized; JLabel assumptionDecentralized; JAssignmentField initiatorBox; JMenu testCaseMenu; JMenuItem[] testCaseButtons; public static void launch() { new ControlFrame(); } ControlFrame() { ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(ImageRoot.class.getResource("d16/multitool.png")).getImage()); icons.add(new ImageIcon(ImageRoot.class.getResource("d32/multitool.png")).getImage()); setIconImages(icons); about = new AboutFrame(this); handler = new Handler(); JPanel topPane = new JPanel(new BorderLayout()); toolbar = new JCoolBar(); topPane.add(toolbar, BorderLayout.CENTER); pane = new JPanel(); GridBagLayout gbl = new GridBagLayout(); pane.setLayout(gbl); pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); GridBagConstraints gbc = new GridBagConstraints(); JLabel label = new JLabel("Algorithm:"); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 0; gbc.gridy = 0; gbl.setConstraints(label, gbc); pane.add(label); algorithmsBox = new JComboBox<>(); algorithmsBox.setOpaque(false); algorithmsBox.setBorder(null); algorithmsBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Object selection = algorithmsBox.getSelectedItem(); AlgorithmSelection alg = (AlgorithmSelection) selection; assumptionAcyclic.setEnabled(alg.isAcyclicGraph()); assumptionCentralized.setEnabled(alg.isCentralized()); assumptionDecentralized.setEnabled(alg.isDecentralized()); initiatorBox.setEnabled(alg.isInitiatorUser()); } }); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 1; gbc.gridy = 0; gbl.setConstraints(algorithmsBox, gbc); pane.add(algorithmsBox); label = new JLabel("Assumptions:"); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 0; gbc.gridy = 1; gbl.setConstraints(label, gbc); pane.add(label); JPanel assPanel = new JPanel(new FlowLayout()); label = assumptionAcyclic = new JLabel("Acyclic"); label.setEnabled(false); assPanel.add(label); label = assumptionCentralized = new JLabel("Centralized"); label.setEnabled(false); assPanel.add(label); label = assumptionDecentralized = new JLabel("Decentralized"); label.setEnabled(false); assPanel.add(label); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 1; gbc.gridy = 1; gbl.setConstraints(assPanel, gbc); pane.add(assPanel); label = new JLabel("Initiators:"); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 0; gbc.gridy = 2; gbl.setConstraints(label, gbc); pane.add(label); initiatorBox = new JAssignmentField() { private static final long serialVersionUID = 2140481562657730772L; protected void filterValue() { ArrayList<Object> result = new ArrayList<>(); for (Object o : value) { if (o instanceof NodeModel) { result.add(o); } } value = result.toArray(); } }; gbc.gridx = 1; gbl.setConstraints(initiatorBox, gbc); pane.add(initiatorBox); JPanel fillPanel = new JPanel(); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; gbc.weighty = 1.0f; pane.add(fillPanel); Container contentPane = getContentPane(); contentPane.add(topPane, BorderLayout.PAGE_START); contentPane.add(pane, BorderLayout.CENTER); pane.requestFocusInWindow(); controller = new Controller(this); controller.registerGlobalActions(); controller.populateMenuBars(); controller.installFocusListeners(); controller.refreshActions(); initiatorBox.setSelectionModel(controller.selectionModel); loadAlgorithms(); updateTitle(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setVisible(true); Timer showWindowTimer = new Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.restoreWindows(); controller.control.requestFocus(); } }); showWindowTimer.setRepeats(false); showWindowTimer.start(); } void updateTitle() { String title = "DaViz - "; if (controller.filename != null) { title += controller.filename; } else { title += "Untitled"; } if (controller.isDirty()) { title += "*"; } setTitle(title); } void loadAlgorithms() { if (SHOW_TESTCASE_MENU) { controller.performJob(new Callable<Void>() { public Void call() throws Exception { // Loading the TestCases class also pulls in the Haskell compiled classes final TestCase[] testCases = TestCase.getTestCases(); SwingUtilities.invokeAndWait(() -> { testCaseButtons = new JMenuItem[testCases.length]; for (int i = 0; i < testCases.length; i++) { testCaseButtons[i] = new JMenuItem(testCases[i].getPage() + " (" + testCases[i].getName() + ")"); testCaseButtons[i].setActionCommand("load"); testCaseButtons[i].putClientProperty("TestCase", testCases[i]); testCaseButtons[i].addActionListener(handler); testCaseMenu.add(testCaseButtons[i]); } testCaseMenu.revalidate(); }); return null; } }); } controller.performJob(new Callable<Void>() { public Void call() throws Exception { // Loading the Algorithms also pulls in the Haskell compiled classes final AlgorithmSelection[] algorithms = AlgorithmSelection.getAlgorithms(); SwingUtilities.invokeAndWait(() -> { for (AlgorithmSelection alg : algorithms) { algorithmsBox.addItem(alg); } }); return null; } }); } // Called by Controller to create actions void registerActions(Controller controller) { controller.registerAction("control-start", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Start simulation"); putValue(Action.SHORT_DESCRIPTION, "Start simulation"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/record_slide_show.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/record_slide_show.png"))); } public void actionPerformed(ActionEvent e) { controller.start(); } }); controller.registerAction("control-reset", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Reset simulation"); putValue(Action.SHORT_DESCRIPTION, "Reset simulation"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/clock_history_frame.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/clock_history_frame.png"))); } public void actionPerformed(ActionEvent e) { controller.stop(); } }); controller.registerAction("new-scenario", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "New scenario"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "New scenario"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_N); } public void actionPerformed(ActionEvent e) { if (controller.confirmSave("Unsaved changes get lost if you start from scratch.\nDo you want to save the current scenario?")) { controller.clear(); } } }); controller.registerAction("load-scenario", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Open scenario..."); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "Open scenario"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O); } public void actionPerformed(ActionEvent e) { } }); controller.registerAction("save-scenario", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Save scenario"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "Save scenario"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); } public void actionPerformed(ActionEvent e) { } }); controller.registerAction("save-as-scenario", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Save as..."); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "Save scenario"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A); } public void actionPerformed(ActionEvent e) { } }); controller.registerAction("exit", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Exit"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK)); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X); } public void actionPerformed(ActionEvent e) { System.exit(0); } }); controller.registerAction("help-contents", new AbstractAction() { private static final long serialVersionUID = 345831661808747964L; { putValue(Action.NAME, "Contents"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); } public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI("https://github.com/praalhans/DaViz/wiki")); } catch (Exception ex) { getToolkit().beep(); } } }); controller.registerAction("help-about", new AbstractAction() { private static final long serialVersionUID = 345831661808747964L; { putValue(Action.NAME, "About"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A); } public void actionPerformed(ActionEvent e) { about.setVisible(true); } }); } // Called by Controller to refresh registered actions void refreshActions(Controller controller) { if (controller.isDirty()) { controller.getAction("save-as-scenario").setEnabled(true); controller.getAction("save-scenario").setEnabled(true); } else { controller.getAction("save-as-scenario").setEnabled(false); controller.getAction("save-scenario").setEnabled(false); } updateTitle(); if (controller.isSimulationLoaded()) { controller.getAction("control-start").setEnabled(false); controller.getAction("control-reset").setEnabled(true); algorithmsBox.setEnabled(false); initiatorBox.setEnabled(false); pane.setEnabled(false); } else { controller.getAction("control-start").setEnabled(true); controller.getAction("control-reset").setEnabled(false); algorithmsBox.setEnabled(true); initiatorBox.setEnabled(true); pane.setEnabled(true); } } void populateMenuBar(Controller controller, JMenuBar menubar) { if (SHOW_TESTCASE_MENU) { testCaseMenu = new JMenu("Book"); testCaseMenu.setMnemonic('b'); menubar.add(testCaseMenu, 0); // Test case menu is populated asynchronously } JMenu menu = new JMenu("Simulation"); menu.setMnemonic('s'); JMenuItem mb = new JMenuItem(controller.getAction("control-start")); mb.setToolTipText(null); AbstractButton tb = new JButton(controller.getAction("control-start")); tb.setHideActionText(true); toolbar.add(tb); menu.add(mb); mb = new JMenuItem(controller.getAction("control-reset")); mb.setToolTipText(null); tb = new JButton(controller.getAction("control-reset")); tb.setHideActionText(true); toolbar.add(tb); menu.add(mb); menubar.add(menu, 0); menu = new JMenu("File"); menu.setMnemonic('f'); mb = new JMenuItem(controller.getAction("new-scenario")); mb.setToolTipText(null); menu.add(mb); // TODO: saving and loading scenarios is not yet supported /*mb = new JMenuItem(controller.getAction("load-scenario")); mb.setToolTipText(null); menu.add(mb); mb = new JMenuItem(controller.getAction("save-scenario")); mb.setToolTipText(null); menu.add(mb); mb = new JMenuItem(controller.getAction("save-as-scenario")); mb.setToolTipText(null); menu.add(mb);*/ menu.addSeparator(); mb = new JMenuItem(controller.getAction("exit")); mb.setToolTipText(null); menu.add(mb); menubar.add(menu, 0); menu = new JMenu("Help"); menu.setMnemonic('h'); mb = new JMenuItem(controller.getAction("help-contents")); mb.setToolTipText(null); menu.add(mb); menu.addSeparator(); mb = new JMenuItem(controller.getAction("help-about")); mb.setToolTipText(null); menu.add(mb); menubar.add(menu); } class Handler implements ActionListener { public void actionPerformed(ActionEvent e) { for (int i = 0; i < testCaseButtons.length; i++) { if (e.getSource() == testCaseButtons[i]) { TestCase test = (TestCase) testCaseButtons[i].getClientProperty("TestCase"); controller.startTestCase(test); } } } } }
15,272
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ChoiceFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/ChoiceFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Image; import java.awt.Window; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JMenuBar; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.aexiz.daviz.images.ImageRoot; import com.aexiz.daviz.ui.swing.JCarousel; class ChoiceFrame extends JDialog { private static final long serialVersionUID = -7132485866652653356L; TimelineFrame timeline; JCarousel carousel; ChoiceFrame(Window owner) { super(owner, "Choice"); setAutoRequestFocus(false); ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(ImageRoot.class.getResource("d16/arrow_branch.png")).getImage()); icons.add(new ImageIcon(ImageRoot.class.getResource("d32/arrow_branch.png")).getImage()); setIconImages(icons); carousel = new JCarousel(); carousel.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { timeline.timeline.requestFocus(); } }); JScrollPane scrollPane = new JScrollPane(carousel); scrollPane.setBorder(BorderFactory.createEmptyBorder()); Container contentPane = getContentPane(); contentPane.add(scrollPane, BorderLayout.CENTER); } // Called by Controller to create actions void registerActions(Controller controller) { } // Called by Controller to refresh registered actions void refreshActions(Controller controller) { } // Called by Controller to change menubar void populateMenuBar(Controller controller, JMenuBar menubar) { } }
1,796
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
InfoFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/InfoFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.Window; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JMenuBar; import javax.swing.JScrollPane; import com.aexiz.daviz.images.ImageRoot; import com.aexiz.daviz.ui.swing.JInfoTable; class InfoFrame extends JDialog { private static final long serialVersionUID = -4023604933733179384L; JInfoTable table; public InfoFrame(Window owner) { super(owner, "Information"); setAutoRequestFocus(false); ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(ImageRoot.class.getResource("d16/preferences.png")).getImage()); icons.add(new ImageIcon(ImageRoot.class.getResource("d32/preferences.png")).getImage()); setIconImages(icons); setType(Window.Type.UTILITY); table = new JInfoTable(); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setBorder(BorderFactory.createEmptyBorder()); Container contentPane = getContentPane(); contentPane.add(scrollPane, BorderLayout.CENTER); } // Called by Controller to create actions void registerActions(Controller controller) { } // Called by Controller to refresh registered actions void refreshActions(Controller controller) { } void populateMenuBar(Controller controller, JMenuBar menubar) { menubar.setPreferredSize(new Dimension(0, 0)); menubar.setFocusable(false); } }
1,598
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
TimelineFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/TimelineFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Image; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JToggleButton; import com.aexiz.daviz.images.ImageRoot; import com.aexiz.daviz.ui.swing.JCoolBar; import com.aexiz.daviz.ui.swing.JStatus; import com.aexiz.daviz.ui.swing.JTimeline; import com.aexiz.daviz.ui.swing.ExecutionModel.ReorderEvent; import com.aexiz.daviz.ui.swing.ExecutionModel.ReorderEventListener; class TimelineFrame extends JDialog { private static final long serialVersionUID = -3706031677602330641L; ChoiceFrame choice; InfoFrame info; JCoolBar toolbar; JTimeline timeline; JStatus status; public TimelineFrame(Window owner) { super(owner, "Timeline"); setAutoRequestFocus(false); ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(ImageRoot.class.getResource("d16/node.png")).getImage()); icons.add(new ImageIcon(ImageRoot.class.getResource("d32/node.png")).getImage()); setIconImages(icons); JPanel topPane = new JPanel(new BorderLayout()); toolbar = new JCoolBar(); topPane.add(toolbar, BorderLayout.CENTER); timeline = new JTimeline(); timeline.addReorderEventListener(new ReorderEventListener() { public void reorderStarted(ReorderEvent e) { status.setTemporaryStatus("Drag the events over each other to reorder them, release to commit."); } public void reorderUpdating(ReorderEvent e) { } public void reorderEnded(ReorderEvent e) { status.setTemporaryStatus(null); } }); JScrollPane scrollPane = new JScrollPane(timeline); scrollPane.setBorder(BorderFactory.createEmptyBorder()); scrollPane.getHorizontalScrollBar().setUnitIncrement(10); scrollPane.getVerticalScrollBar().setUnitIncrement(10); JPanel bottomPane = new JPanel(new BorderLayout()); status = new JStatus(); status.setDefaultStatus("Drag the ruler or use the left and right arrows."); bottomPane.add(new JSeparator(), BorderLayout.PAGE_START); bottomPane.add(status, BorderLayout.CENTER); Container contentPane = getContentPane(); contentPane.add(topPane, BorderLayout.PAGE_START); contentPane.add(scrollPane, BorderLayout.CENTER); contentPane.add(bottomPane, BorderLayout.PAGE_END); } // Called by Controller to create actions void registerActions(Controller controller) { controller.registerAction("timeline-mode-select", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Selection"); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Selection"); putValue(Action.LONG_DESCRIPTION, "Drag the ruler or use the left and right arrows."); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/draw_smudge.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/draw_smudge.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); } public void actionPerformed(ActionEvent e) { timeline.requestFocusInWindow(); } }); /*controller.registerAction("timeline-mode-concurrent", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Concurrent"); putValue(Action.SELECTED_KEY, false); putValue(Action.SHORT_DESCRIPTION, "Move events concurrently in time"); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/arrow_divide.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/arrow_divide.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C); } public void actionPerformed(ActionEvent e) { choice.setVisible(false); info.setVisible(false); timeline.requestFocusInWindow(); timeline.setEditMode(JTimeline.MODE_SWAP); controller.simulationManager.setLinear(false); } }); controller.registerAction("timeline-mode-linear", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Linear"); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Choose a linear order"); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/arrow_rrr.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/arrow_rrr.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_L); } public void actionPerformed(ActionEvent e) { choice.setVisible(true); info.setVisible(true); timeline.requestFocusInWindow(); timeline.setEditMode(JTimeline.MODE_SELECTION); controller.simulationManager.setLinear(true); } }); controller.registerAction("timeline-show-classes", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Concurrency classes"); putValue(Action.SELECTED_KEY, false); putValue(Action.SHORT_DESCRIPTION, "Show concurrency classes"); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/categories.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/categories.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_W); setEnabled(false); // TODO } public void actionPerformed(ActionEvent e) { timeline.requestFocusInWindow(); } });*/ controller.registerAction("timeline-next", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Next"); putValue(Action.SHORT_DESCRIPTION, "Next time unit"); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/arrow_right.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/arrow_right.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_N); } public void actionPerformed(ActionEvent e) { timeline.setCurrentTime(timeline.getCurrentTime() + 1.0f); timeline.requestFocusInWindow(); } }); controller.registerAction("timeline-previous", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Previous"); putValue(Action.SHORT_DESCRIPTION, "Previous time unit"); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/arrow_left.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/arrow_left.png"))); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P); } public void actionPerformed(ActionEvent e) { timeline.setCurrentTime(timeline.getCurrentTime() - 1.0f); timeline.requestFocusInWindow(); } }); } // Called by Controller to refresh registered actions void refreshActions(Controller controller) { } // Called by Controller to change menubar void populateMenuBar(Controller controller, JMenuBar menubar) { AbstractButton tb; ButtonGroup tgrp = new ButtonGroup(); tb = new JToggleButton(controller.getAction("timeline-mode-select")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); /*toolbar.addSeparator(); tgrp = new ButtonGroup(); tb = new JToggleButton(controller.getAction("timeline-mode-concurrent")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); tb = new JToggleButton(controller.getAction("timeline-mode-linear")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); toolbar.addSeparator(); tgrp = new ButtonGroup(); tb = new JToggleButton(controller.getAction("timeline-show-classes")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb);*/ toolbar.addHorizontalGlue(); tb = new JButton(controller.getAction("timeline-previous")); tb.setHideActionText(true); toolbar.add(tb); tb = new JButton(controller.getAction("timeline-next")); tb.setHideActionText(true); toolbar.add(tb); } }
8,608
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
RandomProgram.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/RandomProgram.java
package com.aexiz.daviz.ui; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Random; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Event; import com.aexiz.daviz.glue.Execution; import com.aexiz.daviz.glue.Network; import com.aexiz.daviz.glue.Simulation; import com.aexiz.daviz.glue.Event.SendEvent; import com.aexiz.daviz.glue.Viewpoint.Channel; import com.aexiz.daviz.glue.Viewpoint.Node; import com.aexiz.daviz.glue.alg.Cidon; public class RandomProgram { private Simulation sim = new Simulation(); private Random random = new Random(); public void setAlgorithm(Algorithm alg) { sim.setAlgorithm(alg); } public void setNetwork(Network network) { sim.setNetwork(network); } public void generateNetwork(int minSize, int maxSize, float edgesRatio) { Network result; while (true) { result = new Network(); int size = minSize + (minSize < maxSize ? random.nextInt(maxSize - minSize) : 0); Node[] nodes = new Node[size]; for (int i = 0; i < size; i++) { nodes[i] = new Node(String.valueOf(i)); result.addNode(nodes[i]); } if (result.getNodes().length != size) throw new Error(); int maxEdges = (size * (size - 1)) / 2; int edges = (int) (edgesRatio * maxEdges); for (int i = 0, j = 0; i < edges && j < maxEdges; i++, j++) { int from = random.nextInt(size); int to = random.nextInt(size); if (to > from) { int tmp = from; from = to; to = tmp; } Channel c = new Channel(nodes[from], nodes[to]); Channel d = result.addChannel(c); if (c != d) i--; } result.makeUndirected(); if (result.isStronglyConnected()) break; } setNetwork(result); } public void generateInitiator() { Node[] nodes = sim.getNetwork().getNodes(); if (nodes.length == 0) throw new Error("Network is invalid"); sim.setInitiator(nodes[random.nextInt(nodes.length)]); } public void simulate(PrintStream out) throws Exception { sim.load(); ExecutionStepper st = new ExecutionStepper(sim.getExecution()) { Execution getNext() { Execution[] c = current.getSuccessors(); return c[random.nextInt(c.length)]; } }; st.max_rounds = sim.getAlgorithm().getMaxRounds().maxRounds(sim.getNetwork()); // Run simulation until termination while (st.hasNext()) { st.step(st.getNext()); } // Compute number of messages int messages = 0; Event[] events = st.current.getLinkedEvents(); for (Event e : events) { if (e instanceof SendEvent) messages++; } int edges = sim.getNetwork().getChannels().length / 2; int vertices = sim.getNetwork().getNodes().length; out.print(events.length + "," + messages + "," + edges + "," + vertices + "," + st.limited() + ","); } public static void main(String[] args) throws Exception { System.out.println("param_min,param_max,param_ratio,events,messages,edges,vertices,limited,time_ns"); Params[] params = new Params[]{ // Small, dense networks new Params(5, 10, 0.9f), new Params(5, 10, 0.8f), new Params(5, 10, 0.7f), new Params(5, 10, 0.6f), // Small, sparse networks new Params(5, 10, 0.5f), new Params(5, 10, 0.4f), // Large, dense networks new Params(10, 100, 0.9f), new Params(10, 100, 0.8f), new Params(10, 100, 0.7f), new Params(10, 100, 0.6f), // Large, sparse networks new Params(10, 100, 0.5f), new Params(10, 100, 0.4f), // Huge, dense networks new Params(100, 1000, 0.9f), new Params(100, 1000, 0.8f), new Params(100, 1000, 0.7f), new Params(100, 1000, 0.6f), // Huge, sparse networks new Params(100, 1000, 0.5f), new Params(100, 1000, 0.4f), }; int MAX_TESTS = 1024; int WORKERS = 16; for (Params p : params) { int TESTS_PER_WORKER = MAX_TESTS / WORKERS; class Worker { RandomProgram r = new RandomProgram(); public void call() throws Exception { r.setAlgorithm(new Cidon()); for (int i = 0; i < TESTS_PER_WORKER; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); long before = System.nanoTime(); out.print(p); out.print(","); r.generateNetwork(p.min, p.max, p.ratio); r.generateInitiator(); r.simulate(out); long after = System.nanoTime(); out.print(after - before); synchronized (System.out) { System.out.println(baos.toString("UTF-8")); System.out.flush(); } } } }; Thread[] th = new Thread[WORKERS]; for (int i = 0; i < WORKERS; i++) { th[i] = new Thread() { public void run() { Worker w = new Worker(); try { w.call(); } catch (Exception|Error ex) { synchronized (System.out) { ex.printStackTrace(System.out); System.out.flush(); } } } }; th[i].start(); } for (int i = 0; i < WORKERS; i++) { th[i].join(); } } } static class Params { int min, max; float ratio; Params(int min, int max, float ratio) { this.min = min; this.max = max; this.ratio = ratio; } public String toString() { return min + "," + max + "," + ratio; } } }
5,341
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
SimulationManager.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/SimulationManager.java
package com.aexiz.daviz.ui; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.SwingUtilities; import com.aexiz.daviz.glue.Event; import com.aexiz.daviz.glue.Execution; import com.aexiz.daviz.glue.Network; import com.aexiz.daviz.glue.Simulation; import com.aexiz.daviz.glue.Configuration.StateVisitor; import com.aexiz.daviz.glue.Information.Message; import com.aexiz.daviz.glue.Information.PropertyBuilder; import com.aexiz.daviz.glue.Information.PropertyVisitor; import com.aexiz.daviz.glue.Information.Result; import com.aexiz.daviz.glue.Information.State; import com.aexiz.daviz.glue.Viewpoint.Channel; import com.aexiz.daviz.glue.Viewpoint.Node; import com.aexiz.daviz.ui.swing.ExecutionModel; import com.aexiz.daviz.ui.swing.FutureEvent; import com.aexiz.daviz.ui.swing.GraphModel; import com.aexiz.daviz.ui.swing.InfoModel; import com.aexiz.daviz.ui.swing.ExecutionModel.EventModel; import com.aexiz.daviz.ui.swing.ExecutionModel.EventType; import com.aexiz.daviz.ui.swing.ExecutionModel.MessageModel; import com.aexiz.daviz.ui.swing.ExecutionModel.PendingMessageModel; import com.aexiz.daviz.ui.swing.GraphModel.EdgeModel; import com.aexiz.daviz.ui.swing.GraphModel.NodeModel; import com.aexiz.daviz.ui.swing.InfoModel.PropertyModel; class SimulationManager { private static final int MAX_ROUNDS = 100; Controller controller; boolean fresh = true; boolean loadedNetwork = false; boolean linear = true; // Transient fields transient Execution executionRoot; // from glue transient ArrayList<Execution> executionPath; // from glue (via choice or predetermined) transient Node[] nodes; // from glue transient State[] nodeInitialStates; // from glue (via execution root) transient State[] nodeLastStates; // from glue (via selection) transient Result[] nodeLastTermStatus; // from glue (via selection) transient int[] nodeProcessIds; // from timeline GUI transient NodeModel[] nodeModels; // from network GUI transient Channel[] channels; // from glue transient EdgeModel[] channelEdgeModels; // from network GUI transient ArrayList<Message>[] channelStates; // from glue (via selection) transient Execution[] choiceExecutions; // from glue transient FutureEvent[] choiceEvents; // from GUI transient ArrayList<Event> events = new ArrayList<>(); // from glue transient ArrayList<EventModel> eventModels = new ArrayList<>(); // from timeline GUI transient ArrayList<Object> messageModels = new ArrayList<>(); // from timeline GUI, MessageModel and PendingMessageModel transient ArrayList<Event> messageSendEvents = new ArrayList<>(); // from glue, corresponding send event SimulationManager(Controller controller) { this.controller = controller; initWorkerThread(); } // Executes within worker thread private void clear() throws Exception { SwingUtilities.invokeAndWait(() -> { controller.clearSimulation(); }); // Clear transient fields executionRoot = null; executionPath = new ArrayList<>(); nodes = null; nodeProcessIds = null; nodeModels = null; nodeInitialStates = null; nodeLastStates = null; nodeLastTermStatus = null; channels = null; channelEdgeModels = null; channelStates = null; choiceExecutions = null; choiceEvents = null; events = new ArrayList<>(); eventModels = new ArrayList<>(); messageModels = new ArrayList<>(); messageSendEvents = new ArrayList<>(); loadedNetwork = false; fresh = true; } // Executes within worker thread private void clearEvents() throws Exception { // Clear transient fields events = new ArrayList<>(); eventModels = new ArrayList<>(); messageModels = new ArrayList<>(); messageSendEvents = new ArrayList<>(); // Called after loadNetwork for (int i = 0; i < channels.length; i++) { channelStates[i].clear(); } for (int i = 0; i < nodes.length; i++) { nodeLastStates[i] = nodeInitialStates[i]; nodeLastTermStatus[i] = null; } SwingUtilities.invokeAndWait(() -> { controller.selectionModel.clearSelection(); controller.timelineModel.clearEventsAndMessages(); }); } // Executes within worker thread private void clearEventsAfter(int time) throws Exception { // Called after loadNetwork for (int i = 0; i < channels.length; i++) { channelStates[i].clear(); } for (int i = 0; i < nodes.length; i++) { nodeLastStates[i] = nodeInitialStates[i]; nodeLastTermStatus[i] = null; } SwingUtilities.invokeAndWait(() -> { // Selectively delete events for (int i = 0, size = events.size(); i < size; i++) { EventModel em = eventModels.get(i); int at = (int) em.getTimeWithoutDelta(); if (at >= time) { // Deletion if past controller.timelineModel.removeEvent(em); events.remove(i); eventModels.remove(i); i--; size--; } } // Selectively delete messages for (int i = 0, size = messageModels.size(); i < size; i++) { Object tr = messageModels.get(i); int from, to; if (tr instanceof MessageModel) { MessageModel msg = (MessageModel) tr; from = (int) msg.getFrom().getTimeWithoutDelta(); to = (int) msg.getTo().getTimeWithoutDelta(); if (from >= time && to >= time) { // Deletion if past controller.timelineModel.removeMessage(msg); messageModels.remove(i); messageSendEvents.remove(i); i--; size--; } else if (from < time && to >= time) { // Delete message, replace by pending message (keep send event) PendingMessageModel pmsg = controller.timelineModel.createPendingMessage(msg.getFrom(), msg.getTo().getProcessIndex()); controller.timelineModel.removeMessage(msg); controller.timelineModel.addPendingMessage(pmsg); messageModels.set(i, pmsg); } } else if (tr instanceof PendingMessageModel) { PendingMessageModel msg = (PendingMessageModel) tr; from = (int) msg.getFrom().getTimeWithoutDelta(); if (from >= time) { // Deletion if past controller.timelineModel.removePendingMessage(msg); messageModels.remove(i); messageSendEvents.remove(i); i--; size--; } } else throw new Error(); } // Synchronize UI controller.selectionModel.clearSelection(); }); } // Executes within AWT dispatch thread void changeFutureEvent(FutureEvent fe) { if (!loadedNetwork) return; if (!linear) return; Execution succ = null; for (int i = 0; i < choiceEvents.length; i++) { if (choiceEvents[i] == fe) { succ = choiceExecutions[i]; } } if (succ == null) throw new Error(); // Check if successor is different for (Execution ex : executionPath) { if (ex == succ) return; } // Otherwise reload execution Execution fsucc = succ; float maxOldTime = controller.timelineModel.getMaxLastTime(); controller.timelineModel.setTemporaryMaxTime(maxOldTime); float oldTime = controller.timelineModel.getCurrentTimeWithoutDelta(); controller.choiceModel.clear(); performJob(() -> { loadExecution(executionRoot, fsucc.getExecutionPath()); SwingUtilities.invokeAndWait(() -> { // Update time to update choice window controller.timelineModel.setCurrentTime(oldTime); controller.timelineModel.clearTemporaryMaxTime(); }); return null; }); } // Executes within AWT dispatcher thread void changeTime() { performJob(() -> { if (!linear) return null; if (!loadedNetwork) return null; SwingUtilities.invokeAndWait(() -> { // TODO This method is way too coupled to the timeline model: // the timeline model is changed with regard to relative ordering by the // user, but this method assumes that the events are at exactly the same // time as when they were inserted. EventModel[] last = controller.timelineModel.getHappenedLastEvent(); for (int i = 0; i < nodes.length; i++) { nodeLastStates[i] = nodeInitialStates[i]; nodeLastTermStatus[i] = null; } // Find events based on time for (EventModel event : last) { Event foundE = null; for (int i = 0, size = events.size(); i < size; i++) { if (eventModels.get(i) == event) { foundE = events.get(i); break; } } if (foundE == null) throw new Error("Unable to find event"); int p = event.getProcessIndex(); Node foundN = null; for (int i = 0; i < nodes.length; i++) { if (nodeProcessIds[i] == p) { if (foundE.hasNextState()) { nodeLastStates[i] = foundE.getNextState(); } else { Event previous = foundE.getPreviousEvent(); if (previous != null && previous.hasNextState()) { nodeLastStates[i] = previous.getNextState(); } if (foundE instanceof Event.ResultEvent) { nodeLastTermStatus[i] = ((Event.ResultEvent) foundE).getResult(); } else throw new Error(); } foundN = nodes[i]; break; } } if (foundN == null) throw new Error("Unable to find node"); } // Find messages (pending or delivered) Object[] transit = controller.timelineModel.getHappenedTransitMessage(); for (int i = 0; i < channels.length; i++) channelStates[i].clear(); for (Object tr : transit) { int from, to; if (tr instanceof MessageModel) { MessageModel msg = (MessageModel) tr; from = msg.getFrom().getProcessIndex(); to = msg.getTo().getProcessIndex(); } else if (tr instanceof PendingMessageModel) { PendingMessageModel msg = (PendingMessageModel) tr; from = msg.getFrom().getProcessIndex(); to = msg.getTo(); } else throw new Error(); Event send = null; for (int i = 0, size = messageModels.size(); i < size; i++) { if (messageModels.get(i) == tr) { send = messageSendEvents.get(i); break; } } if (send == null) throw new Error(); Node fromN = null, toN = null; for (int i = 0; (fromN == null || toN == null) && i < nodes.length; i++) { if (nodeProcessIds[i] == from) { fromN = nodes[i]; } if (nodeProcessIds[i] == to) { toN = nodes[i]; } } if (fromN == null) throw new Error(); if (toN == null) throw new Error(); Message message = send.getMessage(); for (int i = 0; i < channels.length; i++) { if (channels[i].from == fromN && channels[i].to == toN) { channelStates[i].add(message); } } } // Fire selection listener, updates info controller.selectionModel.refreshSelection(); // Update execution choices int time = (int) controller.timelineModel.getCurrentTime(); int size = executionPath.size(); controller.choiceModel.clear(); if (time < size) { Execution ex = executionPath.get(time); Execution[] succs = ex.getSuccessors(); choiceExecutions = succs; choiceEvents = new FutureEvent[succs.length]; for (int i = 0; i < succs.length; i++) { Event e = succs[i].getLastEvent(); EventType type = getEventType(e); String other = null; if (e.hasReceiver()) other = e.getReceiver().getLabel(); if (e.hasSender()) other = e.getSender().getLabel(); choiceEvents[i] = new FutureEvent(e.getHappensAt().getLabel(), type, other); controller.choiceModel.addElement(choiceEvents[i]); // Default selection corresponds to path taken } boolean found = false; if (time + 1 < size) { Execution sel = executionPath.get(time + 1); for (int i = 0; i < succs.length; i++) { if (succs[i] == sel) { controller.listSelectionModel.setSelectionInterval(i, i); found = true; break; } } } if (!found) controller.listSelectionModel.clearSelection(); } }); return null; }); } // Executes within AWT dispatch thread private void resetTimeEvents() { for (int i = 0; i < eventModels.size(); i++) { float time = i; EventModel model = eventModels.get(i); model.setTime(time); } } // Executes within AWT dispatch thread void setLinear(boolean linear) { this.linear = linear; if (linear) { // Ensure that all events are linearly ordered according to simulation resetTimeEvents(); } else { } } // Executes within AWT dispatch thread void changeNodeSelection(NodeModel node) { if (!loadedNetwork) return; State last = null; Result status = null; for (int i = 0; i < nodes.length; i++) { if (nodeModels[i] == node) { last = nodeLastStates[i]; status = nodeLastTermStatus[i]; break; } } if (last == null) throw new Error(); PropertyModel p; p = controller.infoModel.createProperty("Process:", node.getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); if (status != null) { p = controller.infoModel.createProperty("Status:", null, InfoModel.COMPOUND_TYPE); loadResult(p, status); controller.infoModel.addProperty(p); } p = controller.infoModel.createProperty("Last state", null, InfoModel.COMPOUND_TYPE); loadState(p, last); controller.infoModel.addProperty(p); } // Executes within AWT dispatch thread void changeEdgeSelection(EdgeModel edge) { if (!loadedNetwork) return; ArrayList<Message> transit = new ArrayList<Message>(); ArrayList<Channel> channel = new ArrayList<Channel>(); for (int i = 0; i < channels.length; i++) { if (channelEdgeModels[i] == edge) { for (Message m : channelStates[i]) { transit.add(m); channel.add(channels[i]); } } } PropertyModel p; p = controller.infoModel.createProperty("Type:", edge.isDirected() ? "Directed" : "Undirected", InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); p = controller.infoModel.createProperty("Messages", null, InfoModel.COMPOUND_TYPE); PropertyModel p2 = controller.infoModel.createNestedProperty(p, "", transit.size() + " elements", InfoModel.SIMPLE_TYPE); controller.infoModel.addNestedProperty(p, p2); for (int i = 0, size = transit.size(); i < size; i++) { Channel c = channel.get(i); p2 = controller.infoModel.createNestedProperty(p, i + " dir:", c.from.getLabel() + " -> " + c.to.getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addNestedProperty(p, p2); p2 = controller.infoModel.createNestedProperty(p, i + " msg:", null, InfoModel.COMPOUND_TYPE); loadMessage(p2, transit.get(i)); controller.infoModel.addNestedProperty(p, p2); } controller.infoModel.addProperty(p); } private Event findEventByModel(EventModel model) { for (int i = 0, size = events.size(); i < size; i++) { if (eventModels.get(i) == model) return events.get(i); } throw new Error(); } // Executes within AWT dispatch thread void changeEventSelection(EventModel ev) { if (!loadedNetwork) throw new Error(); Event event = findEventByModel(ev); PropertyModel p; p = controller.infoModel.createProperty("Process:", event.getHappensAt().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); p = controller.infoModel.createProperty("Type:", ev.getEventType().toString(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); if (event.hasSender()) { p = controller.infoModel.createProperty("From:", event.getSender().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); } if (event.hasReceiver()) { if (event.hasMatchingEvent()) { p = controller.infoModel.createProperty("Delivered to:", event.getReceiver().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); } else { p = controller.infoModel.createProperty("Underway to:", event.getReceiver().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); } } if (event.hasNextState()) { p = controller.infoModel.createProperty("Next state", null, InfoModel.COMPOUND_TYPE); loadState(p, event.getNextState()); controller.infoModel.addProperty(p); } if (event.hasMessage()) { p = controller.infoModel.createProperty("Message", null, InfoModel.COMPOUND_TYPE); loadMessage(p, event.getMessage()); controller.infoModel.addProperty(p); } if (event.hasResult()) { p = controller.infoModel.createProperty("Result", null, InfoModel.COMPOUND_TYPE); loadResult(p, event.getResult()); controller.infoModel.addProperty(p); } } // Executes within AWT dispatch thread void changeMessageSelection(Object sel) { if (!loadedNetwork) throw new Error(); Event send = null; for (int i = 0, size = messageModels.size(); i < size; i++) { if (messageModels.get(i) == sel) { send = messageSendEvents.get(i); break; } } if (send == null) throw new Error("Unable to find required send event"); PropertyModel p; p = controller.infoModel.createProperty("From:", send.getHappensAt().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); if (send.hasReceiver()) { if (send.hasMatchingEvent()) { p = controller.infoModel.createProperty("Delivered to:", send.getReceiver().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); } else { p = controller.infoModel.createProperty("Underway to:", send.getReceiver().getLabel(), InfoModel.SIMPLE_TYPE); controller.infoModel.addProperty(p); } } else throw new Error(); if (!send.hasMessage()) throw new Error(); p = controller.infoModel.createProperty("Message", null, InfoModel.COMPOUND_TYPE); loadMessage(p, send.getMessage()); controller.infoModel.addProperty(p); } class InfoPropertyBuilder implements PropertyBuilder { PropertyModel property; private boolean disposed; public void simpleProperty(String name, String value) { if (disposed) throw new Error(); PropertyModel p = controller.infoModel.createNestedProperty(property, name, value, InfoModel.SIMPLE_TYPE); controller.infoModel.addNestedProperty(property, p); } public void compoundProperty(String name, PropertyVisitor visitor) { if (disposed) throw new Error(); InfoPropertyBuilder nest = new InfoPropertyBuilder(); nest.property = controller.infoModel.createNestedProperty(property, name, null, InfoModel.COMPOUND_TYPE); try { visitor.buildProperties(nest); } finally { nest.dispose(); } controller.infoModel.addNestedProperty(property, nest.property); } void dispose() { disposed = true; } } private void loadState(PropertyModel p, State state) { InfoPropertyBuilder ipb = new InfoPropertyBuilder(); ipb.property = p; try { state.buildProperties(ipb); } finally { ipb.dispose(); } } private void loadMessage(PropertyModel p, Message message) { InfoPropertyBuilder ipb = new InfoPropertyBuilder(); ipb.property = p; try { message.buildProperties(ipb); } finally { ipb.dispose(); } } private void loadResult(PropertyModel p, Result result) { InfoPropertyBuilder ipb = new InfoPropertyBuilder(); ipb.property = p; try { result.buildProperties(ipb); } finally { ipb.dispose(); } } private EventType getEventType(Event e) { EventType type; if (e instanceof Event.SendEvent) { type = ExecutionModel.SEND_TYPE; } else if (e instanceof Event.ReceiveEvent) { type = ExecutionModel.RECEIVE_TYPE; } else if (e instanceof Event.InternalEvent) { type = ExecutionModel.INTERNAL_TYPE; } else if (e instanceof Event.ResultEvent) { type = ExecutionModel.TERMINATE_TYPE; } else throw new Error(); return type; } // Executes within AWT dispatch thread private void addEventToTimeline(Event e) { // Convert event to event model Node node = e.getHappensAt(); int proc = -1; for (int i = 0; proc < 0 && i < nodes.length; i++) { if (nodes[i] == node) proc = nodeProcessIds[i]; } EventType type = getEventType(e); int time = events.size(); EventModel model = controller.timelineModel.createEvent(proc, type, time); controller.timelineModel.addEvent(model); events.add(e); eventModels.add(model); // If receive event, find matching send event, add message if (e instanceof Event.ReceiveEvent) { Event other = e.getMatchingEvent(); EventModel otherModel = null; for (int i = 0, size = events.size(); otherModel == null && i < size; i++) { if (events.get(i) == other) otherModel = eventModels.get(i); } if (otherModel == null) throw new Error("Unable to match event"); // Find pending message and remove it int j = -1; for (int i = 0, size = messageModels.size(); i < size; i++) { Object msg = messageModels.get(i); if (msg instanceof PendingMessageModel) { PendingMessageModel pmsg = (PendingMessageModel) msg; if (pmsg.getFrom() == otherModel && pmsg.getTo() == proc) { j = i; controller.timelineModel.removePendingMessage(pmsg); break; } } } if (j < 0) throw new Error("Pending message not found"); // Construct message MessageModel msg = controller.timelineModel.createMessage(otherModel, model); messageModels.set(j, msg); controller.timelineModel.addMessage(msg); } // If send event, and no matching receive event, add pending message if (e instanceof Event.SendEvent) { Event other = e.getMatchingEvent(); if (other == null) { Node receiver = ((Event.SendEvent) e).getReceiver(); int process = -1; for (int i = 0; i < nodes.length; i++) { if (nodes[i] == receiver) { process = nodeProcessIds[i]; break; } } if (process < 0) throw new Error("Unable to match process"); // Construct pending message PendingMessageModel msg = controller.timelineModel.createPendingMessage(model, process); messageModels.add(msg); messageSendEvents.add(e); controller.timelineModel.addPendingMessage(msg); } } // Update time to fire time listener // TODO: maybe enable this later if necessary: I do not know what it does //float timeline = controller.timelineModel.getCurrentTimeWithoutDelta(); //controller.timelineModel.setCurrentTime(timeline); } // Executes within worker thread private void loadNetwork(Network net) throws Exception { SwingUtilities.invokeAndWait(() -> { nodes = net.getNodes(); nodeProcessIds = new int[nodes.length]; nodeModels = new NodeModel[nodes.length]; nodeInitialStates = new State[nodes.length]; nodeLastStates = new State[nodes.length]; nodeLastTermStatus = new Result[nodes.length]; for (int i = 0; i < nodes.length; i++) { nodeProcessIds[i] = controller.timelineModel.addProcess(nodes[i].getLabel()); float x = i, y = i; // default positions if (nodes[i].hasClientProperty(Node.CLIENT_PROPERTY_NODEMODEL)) { nodeModels[i] = (NodeModel) nodes[i].getClientProperty(Node.CLIENT_PROPERTY_NODEMODEL); } else { if (nodes[i].hasClientProperty(Node.CLIENT_PROPERTY_POSITION_X, Float.class)) x = (Float) nodes[i].getClientProperty(Node.CLIENT_PROPERTY_POSITION_X); if (nodes[i].hasClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, Float.class)) y = (Float) nodes[i].getClientProperty(Node.CLIENT_PROPERTY_POSITION_Y); nodeModels[i] = controller.networkModel.createNode(x, y); nodes[i].putClientProperty(Node.CLIENT_PROPERTY_NODEMODEL, nodeModels[i]); nodeModels[i].setLabel(nodes[i].getLabel()); controller.networkModel.addNode(nodeModels[i]); } } channels = net.getChannels(); channelEdgeModels = new EdgeModel[channels.length]; @SuppressWarnings("unchecked") ArrayList<Message>[] ics = (ArrayList<Message>[]) new ArrayList<?>[channels.length]; channelStates = ics; for (int i = 0; i < channels.length; i++) { channelStates[i] = new ArrayList<Message>(); } for (int i = 0; i < channels.length; i++) { GraphModel.NodeModel from = null, to = null; for (int j = 0; (from == null || to == null) && j < nodes.length; j++) { if (channels[i].from == nodes[j]) { from = nodeModels[j]; } if (channels[i].to == nodes[j]) { to = nodeModels[j]; } } if (from == null || to == null) throw new Error("Invalid channel model"); int twice = -1; for (int k = 0; twice < 0 && k < i; k++) { if (channels[k].from == channels[i].from && channels[k].to == channels[i].to) twice = k; else if (channels[k].from == channels[i].to && channels[k].to == channels[i].from) twice = k; } if (channels[i].hasClientProperty(Channel.CLIENT_PROPERTY_EDGEMODEL)) { channelEdgeModels[i] = (EdgeModel) channels[i].getClientProperty(Channel.CLIENT_PROPERTY_EDGEMODEL); } else { // Construct closure variables if (twice < 0) { // Create a directed edge channelEdgeModels[i] = controller.networkModel.createEdge(from, to); channelEdgeModels[i].setDirected(true); channels[i].putClientProperty(Channel.CLIENT_PROPERTY_EDGEMODEL, channelEdgeModels[i]); controller.networkModel.addEdge(channelEdgeModels[i]); } else { // Convert to a non-directed edge channelEdgeModels[i] = channelEdgeModels[twice]; channelEdgeModels[i].setDirected(false); } } } loadedNetwork = true; }); } // Executes within worker thread private void loadInitialState(Execution ex) { executionRoot = ex; class LoadInitialState implements StateVisitor { public void setState(Node process, State state) { for (int i = 0; i < nodes.length; i++) { if (nodes[i] == process) { nodeInitialStates[i] = state; return; } } throw new Error("Unable to find node"); } } executionRoot.getConfiguration().loadProcessState(new LoadInitialState()); for (int i = 0; i < nodes.length; i++) { if (nodeInitialStates[i] == null) throw new Error("No initial state"); nodeLastStates[i] = nodeInitialStates[i]; nodeLastTermStatus[i] = null; } } // Executes within worker thread private void loadExecution(Execution ex, List<Execution> path) throws Exception { // Check validity if (path != null && path.size() > 0 && path.get(0) != ex) throw new Error("Invalid execution root"); // Clear path executionPath.clear(); // Only simulate after the given path elements if (path == null || path.size() == 0 || path.size() == 1) { clearEvents(); loadInitialState(ex); } else { clearEventsAfter(path.size() - 2); } ExecutionStepper st = new ExecutionStepper(ex) { void step(Execution next) throws Exception { super.step(next); if (!replay) { SwingUtilities.invokeAndWait(() -> { addEventToTimeline(next.getLastEvent()); }); } } }; st.max_rounds = MAX_ROUNDS; // Replay original execution if (path != null) { st.replay = true; for (int i = 1, size = path.size() - 1; i < size; i++) { st.step(path.get(i)); } } // Otherwise, just continue st.replay = false; // First do last, chosen path element if (path != null && path.size() > 1) st.step(path.get(path.size() - 1)); while (st.hasNext()) { // Introduce a short delay, so the user can follow what changes happen on the UI Thread.sleep(50l); st.step(st.getNext()); } executionPath.clear(); executionPath.addAll(st.path); // Update time to update choice window } // Executes within AWT dispatch thread void afterSimulation(Runnable r) { performJob(() -> { SwingUtilities.invokeAndWait(r); return null; }); } // Executes within AWT dispatch thread void stopSimulation() { performJob(() -> { clear(); SwingUtilities.invokeAndWait(() -> { controller.refreshActions(); }); return null; }); } // Executes within AWT dispatch thread void loadSimulation(Callable<Simulation> method) { performJob(() -> { clear(); fresh = false; SwingUtilities.invokeAndWait(() -> { controller.refreshActions(); }); Simulation sim = method.call(); loadNetwork(sim.getNetwork()); if (sim.hasInitiator()) { Node initiator = sim.getInitiator(); NodeModel nodeModel = (NodeModel) initiator.getClientProperty(Node.CLIENT_PROPERTY_NODEMODEL); controller.control.initiatorBox.setValue(new Object[] { nodeModel }); } else { controller.control.initiatorBox.clearValue(); } loadExecution(sim.getExecution(), null); SwingUtilities.invokeAndWait(() -> { // Update time to update choice window float t = controller.timelineModel.getCurrentTimeWithoutDelta(); controller.timelineModel.setCurrentTime(t); }); return null; }); } private Thread worker; private LinkedBlockingQueue<Callable<Void>> queue = new LinkedBlockingQueue<>(); private void initWorkerThread() { worker = new Thread(new Runnable() { public void run() { try { while (true) { Callable<Void> job = queue.take(); SwingUtilities.invokeLater(() -> { controller.setWaiting(true); }); try { job.call(); } catch (Exception ex) { System.err.println("Worker thread job failed with exception"); ex.printStackTrace(); } finally { SwingUtilities.invokeLater(() -> { controller.setWaiting(false); }); } } } catch (Exception ex) { System.err.println("Worker thread died with exception"); ex.printStackTrace(); } } }); worker.setDaemon(true); worker.start(); } // Executes within AWT dispatch thread public void performJob(Callable<Void> call) { queue.add(call); } }
30,243
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
Controller.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/Controller.java
package com.aexiz.daviz.ui; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.util.EventObject; import java.util.HashMap; import java.util.concurrent.Callable; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.DefaultListSelectionModel; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.aexiz.daviz.glue.Algorithm; import com.aexiz.daviz.glue.Network; import com.aexiz.daviz.glue.Simulation; import com.aexiz.daviz.glue.Viewpoint.Node; import com.aexiz.daviz.ui.swing.DefaultExecutionModel; import com.aexiz.daviz.ui.swing.DefaultGraphModel; import com.aexiz.daviz.ui.swing.DefaultInfoModel; import com.aexiz.daviz.ui.swing.DefaultObjectSelectionModel; import com.aexiz.daviz.ui.swing.FutureEvent; import com.aexiz.daviz.ui.swing.InfoModel; import com.aexiz.daviz.ui.swing.ExecutionModel.CoarseTimeEventListener; import com.aexiz.daviz.ui.swing.ExecutionModel.EventModel; import com.aexiz.daviz.ui.swing.ExecutionModel.MessageModel; import com.aexiz.daviz.ui.swing.ExecutionModel.PendingMessageModel; import com.aexiz.daviz.ui.swing.GraphModel.EdgeModel; import com.aexiz.daviz.ui.swing.GraphModel.NodeModel; import com.aexiz.daviz.ui.swing.InfoModel.PropertyModel; import com.aexiz.daviz.glue.Viewpoint.Channel; class Controller { ControlFrame control; NetworkFrame network; TimelineFrame timeline; InfoFrame info; ChoiceFrame choice; DefaultObjectSelectionModel selectionModel; DefaultGraphModel networkModel; DefaultExecutionModel timelineModel; DefaultInfoModel infoModel; DefaultListModel<FutureEvent> choiceModel; DefaultListSelectionModel listSelectionModel; private HashMap<String,Action> actionMap = new HashMap<>(); private SimulationManager simulationManager; boolean dirty; String filename; Controller(ControlFrame owner) { control = owner; network = new NetworkFrame(owner); timeline = new TimelineFrame(owner); info = new InfoFrame(owner); choice = new ChoiceFrame(owner); timeline.choice = choice; timeline.info = info; choice.timeline = timeline; selectionModel = new DefaultObjectSelectionModel(); networkModel = new DefaultGraphModel(); networkModel.setSnapToGrid(true); timelineModel = new DefaultExecutionModel(); infoModel = new DefaultInfoModel(); choiceModel = new DefaultListModel<>(); listSelectionModel = new DefaultListSelectionModel(); network.graph.setModel(networkModel); network.graph.setSelectionModel(selectionModel); timeline.timeline.setModel(timelineModel); timeline.timeline.setSelectionModel(selectionModel); info.table.setModel(infoModel); choice.carousel.setModel(choiceModel); choice.carousel.setSelectionModel(listSelectionModel); installTimeListener(); installSelectionListener(); simulationManager = new SimulationManager(this); control.registerActions(this); network.registerActions(this); timeline.registerActions(this); info.registerActions(this); choice.registerActions(this); } void restoreWindows() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int spaceleft = 25, spacetop = 25; int posleft = (screenSize.width - 300 - spaceleft - 500 - spaceleft - 600 - spaceleft) / 2; int postop = (screenSize.height - 300 - spacetop - 250) / 2; info.setLocation(posleft, postop); info.setSize(300, 300 + spacetop + 250); info.setMinimumSize(new Dimension(300, 300 + spacetop + 250)); info.setVisible(true); timeline.setLocation(posleft + 500 + spaceleft + 300 + spaceleft, postop); timeline.setSize(600, 300 + spacetop + 100); timeline.setMinimumSize(new Dimension(600, 300 + spacetop + 100)); timeline.setVisible(true); choice.setLocation(posleft + 500 + spaceleft + 300 + spaceleft, postop + 300 + spacetop + 100 + spacetop); choice.setSize(600, 125); choice.setMinimumSize(new Dimension(600, 125)); choice.setVisible(true); control.setLocation(posleft + 300 + spaceleft, postop); control.setSize(500, 200); control.setMinimumSize(new Dimension(500, 200)); control.setVisible(true); network.setLocation(posleft + 300 + spaceleft, postop + 200 + spacetop); network.setSize(500, 350); network.setMinimumSize(new Dimension(500, 350)); network.setVisible(true); } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Window"); menu.setMnemonic('w'); menuBar.add(menu); menu.add(new JMenuItem(getAction("show-info"))); menu.add(new JMenuItem(getAction("show-simulation"))); menu.add(new JMenuItem(getAction("show-network"))); menu.add(new JMenuItem(getAction("show-timeline"))); menu.add(new JMenuItem(getAction("show-choice"))); menu.addSeparator(); menu.add(new JMenuItem(getAction("show-windows"))); return menuBar; } void populateMenuBars() { JMenuBar menubar; menubar = createMenuBar(); control.populateMenuBar(this, menubar); control.setJMenuBar(menubar); menubar = createMenuBar(); network.populateMenuBar(this, menubar); network.setJMenuBar(menubar); menubar = createMenuBar(); timeline.populateMenuBar(this, menubar); timeline.setJMenuBar(menubar); menubar = createMenuBar(); info.populateMenuBar(this, menubar); info.setJMenuBar(menubar); menubar = createMenuBar(); choice.populateMenuBar(this, menubar); choice.setJMenuBar(menubar); } void registerGlobalActions() { registerAction("show-info", new AbstractAction() { private static final long serialVersionUID = 345831661808747964L; { putValue(Action.NAME, "Information"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_I); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0)); } public void actionPerformed(ActionEvent e) { info.setVisible(true); if (!info.isAutoRequestFocus()) info.requestFocus(); } }); registerAction("show-simulation", new AbstractAction() { private static final long serialVersionUID = -6443065148322819900L; { putValue(Action.NAME, "Simulation"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)); } public void actionPerformed(ActionEvent e) { control.setVisible(true); if (!control.isAutoRequestFocus()) control.requestFocus(); } }); registerAction("show-network", new AbstractAction() { private static final long serialVersionUID = -1727287039452985389L; { putValue(Action.NAME, "Network"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_N); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0)); } public void actionPerformed(ActionEvent e) { network.setVisible(true); if (!network.isAutoRequestFocus()) network.requestFocus(); } }); registerAction("show-timeline", new AbstractAction() { private static final long serialVersionUID = 3482120594679489667L; { putValue(Action.NAME, "Timeline"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_T); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0)); } public void actionPerformed(ActionEvent e) { timeline.setVisible(true); if (!timeline.isAutoRequestFocus()) timeline.requestFocus(); } }); registerAction("show-choice", new AbstractAction() { private static final long serialVersionUID = 8948578948320158195L; { putValue(Action.NAME, "Choice"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0)); setEnabled(false); } public void actionPerformed(ActionEvent e) { if (choice.isVisible()) { choice.setVisible(true); if (!choice.isAutoRequestFocus()) choice.requestFocus(); } } }); choice.addComponentListener(new ComponentAdapter() { public void componentHidden(ComponentEvent e) { getAction("show-choice").setEnabled(false); } public void componentShown(ComponentEvent e) { getAction("show-choice").setEnabled(true); } }); registerAction("show-windows", new AbstractAction() { private static final long serialVersionUID = -718811887577227221L; { putValue(Action.NAME, "Restore windows"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0)); } public void actionPerformed(ActionEvent e) { restoreWindows(); } }); } void registerAction(String name, Action action) { if (name == null || action == null) throw null; if (actionMap.containsKey(name)) throw new Error("Duplicate action key"); actionMap.put(name, action); } Action getAction(String name) { if (!actionMap.containsKey(name)) throw new Error("Invalid action key"); return actionMap.get(name); } void refreshActions() { control.refreshActions(this); network.refreshActions(this); timeline.refreshActions(this); info.refreshActions(this); choice.refreshActions(this); } boolean isSimulationLoaded() { return !simulationManager.fresh; } boolean isDirty() { return dirty; } void installFocusListeners() { Window[] windows = new Window[]{control, network, timeline, info, choice}; class WindowHandler implements WindowListener, WindowFocusListener { public void windowGainedFocus(WindowEvent e) { Window active = e.getWindow(); for (Window window : windows) window.setAutoRequestFocus(true); for (Window window : windows) if (active != window) window.setFocusableWindowState(false); for (Window window : windows) if (active != window && window.isVisible()) window.setVisible(true); active.setVisible(true); SwingUtilities.invokeLater(() -> { for (Window window : windows) if (active != window) window.setFocusableWindowState(true); for (Window window : windows) window.setAutoRequestFocus(false); }); } public void windowLostFocus(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { Window active = e.getWindow(); for (Window window : windows) if (active != window && window instanceof Frame) ((Frame) window).setState(Frame.NORMAL); } public void windowIconified(WindowEvent e) { Window active = e.getWindow(); for (Window window : windows) if (active != window && window instanceof Frame) ((Frame) window).setState(Frame.ICONIFIED); } public void windowOpened(WindowEvent e) { } }; WindowHandler h = new WindowHandler(); for (Window window : windows) { window.setAutoRequestFocus(false); window.addWindowFocusListener(h); window.addWindowListener(h); } for (Window window : windows) { if (window instanceof JFrame) ((JFrame) window).setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); else if (window instanceof JDialog) ((JDialog) window).setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); } } private void installSelectionListener() { class SelectionHandler implements ChangeListener, Runnable { boolean delayed = false; public void stateChanged(ChangeEvent e) { if (!delayed) { // Consume all state change events in one go. delayed = true; SwingUtilities.invokeLater(this); } } public void run() { delayed = false; Object[] sels = selectionModel.getSelection(); infoModel.clear(); if (sels.length == 0) { PropertyModel p = infoModel.createProperty("Empty selection", null, InfoModel.COMPOUND_TYPE); infoModel.addProperty(p); return; } else if (sels.length >= 2) { Class<?> firstType = sels[0].getClass(); boolean sameType = true; for (int i = 1; i < sels.length; i++) { if (sels[i].getClass() != firstType) { sameType = false; break; } } PropertyModel p; if (sameType) { p = infoModel.createProperty(sels.length + " homogeneous objects", null, InfoModel.COMPOUND_TYPE); } else { p = infoModel.createProperty(sels.length + " heterogeneous objects", null, InfoModel.COMPOUND_TYPE); } infoModel.addProperty(p); return; } Object sel = sels[0]; if (sel instanceof NodeModel) { NodeModel node = (NodeModel) sel; simulationManager.changeNodeSelection(node); } else if (sel instanceof EdgeModel) { EdgeModel edge = (EdgeModel) sel; simulationManager.changeEdgeSelection(edge); } else if (sel instanceof EventModel) { EventModel ev = (EventModel) sel; simulationManager.changeEventSelection(ev); } else if (sel instanceof MessageModel || sel instanceof PendingMessageModel) { simulationManager.changeMessageSelection(sel); } else throw new Error("Unknown selected object"); } } SelectionHandler h = new SelectionHandler(); h.stateChanged(null); selectionModel.addChangeListener(h); } private void installTimeListener() { class TimeHandler implements ListSelectionListener, CoarseTimeEventListener { public void valueChanged(ListSelectionEvent e) { int index = listSelectionModel.getMinSelectionIndex(); if (index < 0) return; FutureEvent fe = (FutureEvent) choiceModel.getElementAt(index); simulationManager.changeFutureEvent(fe); } public void timeChanged(EventObject o) { simulationManager.changeTime(); } } TimeHandler h = new TimeHandler(); timelineModel.addCoarseTimeEventListener(h); listSelectionModel.addListSelectionListener(h); } boolean confirmSave(String msg) { if (isDirty()) { int result = JOptionPane.showConfirmDialog(control, msg, "Unsaved changes", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { // Save and then proceed // TODO save return true; } else if (result == JOptionPane.NO_OPTION) { // Discard and proceed return true; } else if (result == JOptionPane.CANCEL_OPTION) { // Cancel operation return false; } else throw new Error(); } return true; } void clear() { simulationManager.stopSimulation(); simulationManager.afterSimulation(() -> { clear0(); }); } private void clear0() { networkModel.clear(); clearSimulation(); refreshActions(); } void start() { simulationManager.afterSimulation(() -> { AlgorithmSelection alg = (AlgorithmSelection) control.algorithmsBox.getSelectedItem(); Object[] init = control.initiatorBox.getValue(); if (networkModel.isEmpty()) { JOptionPane.showMessageDialog(control, "The network is empty.", "Unable to start simulation", JOptionPane.ERROR_MESSAGE); return; } if (alg.isAcyclicGraph() && !networkModel.isAcyclic()) { JOptionPane.showMessageDialog(control, "The network contains cycles.", "Unable to start simulation", JOptionPane.ERROR_MESSAGE); return; } if (alg.isInitiatorUser() && (init == null || init.length == 0)) { JOptionPane.showMessageDialog(control, "No initiator selected.", "Unable to start simulation", JOptionPane.ERROR_MESSAGE); return; } if (alg.isInitiatorUser() && alg.isCentralized() && init != null && init.length > 1) { JOptionPane.showMessageDialog(control, "Too many initiators selected.", "Unable to start simulation", JOptionPane.ERROR_MESSAGE); return; } simulationManager.loadSimulation(() -> { // Create a simulation Simulation sim = new Simulation(); sim.setAlgorithm((Algorithm) alg.alg); // Load network vertices, edges and initiator Network network = new Network(); NodeModel[] nodes = networkModel.getNode(); Node[] ps = new Node[nodes.length]; for (int i = 0; i < nodes.length; i++) { ps[i] = new Node(nodes[i].getLabel()); ps[i].putClientProperty(Node.CLIENT_PROPERTY_NODEMODEL, nodes[i]); network.addNode(ps[i]); } EdgeModel[] edges = networkModel.getValidEdge(); Channel[] es = new Channel[edges.length]; for (int i = 0; i < edges.length; i++) { NodeModel from = edges[i].getFrom(), to = edges[i].getTo(); Node f = null, t = null; for (int j = 0; (f == null || t == null) && j < nodes.length; j++) { if (nodes[j] == from) f = ps[j]; if (nodes[j] == to) t = ps[j]; } if (f == null || t == null) throw new Error(); es[i] = new Channel(f , t); es[i].putClientProperty(Channel.CLIENT_PROPERTY_EDGEMODEL, edges[i]); es[i].putClientProperty(Channel.CLIENT_PROPERTY_FIRST_DIRECTED, true); network.addChannel(es[i]); if (!edges[i].isDirected()) { // Also add reverse edge Channel c = new Channel(t, f); c.putClientProperty(Channel.CLIENT_PROPERTY_EDGEMODEL, edges[i]); c.putClientProperty(Channel.CLIENT_PROPERTY_FIRST_DIRECTED, false); network.addChannel(c); } } sim.setNetwork(network); if (init != null) { Node[] is = new Node[init.length]; for (int i = 0; i < init.length; i++) { for (int j = 0; is[i] == null && j < nodes.length; j++) { if (nodes[j] == init[i]) is[i] = ps[j]; } if (is[i] == null) throw new Error(); } sim.setInitiator(is[0]); } sim.load(); return sim; }); }); } void startTestCase(TestCase testCase) { // Clear any existing model, because we are loading a new one networkModel.clear(); control.algorithmsBox.setSelectedItem(testCase.algorithm); // Load the simulation as prepared by the TestCase method. simulationManager.performJob(new Callable<Void>() { public Void call() throws Exception { // By the action listener, the status flags are updated too simulationManager.loadSimulation(testCase.method); return null; } }); } void clearSimulation() { selectionModel.clearSelection(); listSelectionModel.clearSelection(); timelineModel.clear(); choiceModel.clear(); } void stop() { // stopSimulation calls clearSimulation simulationManager.stopSimulation(); } void performJob(Callable<Void> call) { // Runs the task in a separate thread simulationManager.performJob(call); } // Executes within AWT dispatch thread void setWaiting(boolean loading) { Cursor c; if (loading) { c = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); } else { c = Cursor.getDefaultCursor(); } control.setCursor(c); network.setCursor(c); timeline.setCursor(c); info.setCursor(c); } }
19,760
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ExecutionStepper.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/ExecutionStepper.java
package com.aexiz.daviz.ui; import java.util.ArrayList; import com.aexiz.daviz.glue.Execution; class ExecutionStepper { int max_rounds; ArrayList<Execution> path; Execution current; boolean replay = false; ExecutionStepper(Execution ex) { path = new ArrayList<>(); path.add(current = ex); } boolean hasNext() { return path.size() < max_rounds && current.hasNext(); } boolean limited() { return path.size() >= max_rounds; } Execution getNext() { return current.getNext(); } void step(Execution next) throws Exception { if (max_rounds <= 0) throw new Error("Invalid step bound"); boolean found = false; for (Execution succ : current.getSuccessors()) { if (succ == next) { found = true; break; } } if (!found) throw new Error("Stepping into unknown successor"); path.add(next); current = next; } }
892
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
AboutFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/AboutFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.URI; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; class AboutFrame extends JDialog { private static final long serialVersionUID = 7837200967453244201L; public AboutFrame(Window owner) { super(owner, ModalityType.APPLICATION_MODAL); setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = 450; int height = 250; setBounds((screenSize.width - width) / 2, (screenSize.height - height) / 2, width, height); setTitle("About DaViz"); setResizable(false); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); JPanel pane = new JPanel(gbl); pane.setBackground(Color.WHITE); pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JLabel title = new JLabel("Distributed Algorithms Visualisation"); title.setFont(title.getFont().deriveFont(24.0f)); gbc.gridwidth = 2; gbl.setConstraints(title, gbc); pane.add(title); JLabel author = new JLabel("Programming by: "); gbc.ipady = 20; gbc.anchor = GridBagConstraints.LINE_END; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.gridy = 1; gbl.setConstraints(author, gbc); pane.add(author); JLabel author_name = new JLabel("Hans-Dieter Hiep"); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 1; gbl.setConstraints(author_name, gbc); pane.add(author_name); JLabel icons = new JLabel("Icons: "); gbc.ipady = 2; gbc.ipadx = 0; gbc.anchor = GridBagConstraints.LINE_END; gbc.gridx = 0; gbc.gridy = 2; gbl.setConstraints(icons, gbc); pane.add(icons); JLabel icons_name = new JLabel("http://fatcow.com/free-icons"); icons_name.setForeground(Color.BLUE); icons_name.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); icons_name.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { try { Desktop.getDesktop().browse(new URI("http://fatcow.com/free-icons")); } catch (Exception ex) { getToolkit().beep(); } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} }); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 1; gbl.setConstraints(icons_name, gbc); pane.add(icons_name); JLabel thanks = new JLabel("Special thanks to:"); gbc = new GridBagConstraints(); gbc.ipady = 20; gbc.anchor = GridBagConstraints.CENTER; gbc.gridwidth = 2; gbc.gridx = 0; gbc.gridy = 3; gbl.setConstraints(thanks, gbc); pane.add(thanks); JLabel thanks_name = new JLabel("Wan Fokkink, Jacco van Splunter, Wesley Shann"); gbc.anchor = GridBagConstraints.NORTH; gbc.ipady = 0; gbc.gridy = 4; gbl.setConstraints(thanks_name, gbc); pane.add(thanks_name); JButton close = new JButton("OK"); close.setOpaque(false); close.setPreferredSize(new Dimension(85, close.getPreferredSize().height)); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.SOUTHEAST; gbc.gridwidth = 2; gbc.gridx = 0; gbc.gridy = 5; gbc.weighty = 1.0; gbl.setConstraints(close, gbc); pane.add(close); add(pane, BorderLayout.CENTER); } }
4,037
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
TestCase.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/TestCase.java
package com.aexiz.daviz.ui; import java.util.concurrent.Callable; import com.aexiz.daviz.glue.*; import com.aexiz.daviz.glue.Viewpoint.*; import com.aexiz.daviz.glue.alg.*; // Note that loading this class will also load all Haskell code class TestCase { String page; AlgorithmSelection algorithm; Callable<Simulation> method; TestCase(String page, AlgorithmSelection algorithm, Callable<Simulation> method) { this.page = page; this.algorithm = algorithm; this.method = method; } String getPage() { return page; } String getName() { return algorithm.name; } static TestCase[] getTestCases() { return new TestCase[] { new TestCase("Page 20", AlgorithmSelection.TARRY, TestCase::page20book), new TestCase("Page 21", AlgorithmSelection.DFS, TestCase::page21book_dfs), new TestCase("Page 21", AlgorithmSelection.VISITED, TestCase::page21book_visited), new TestCase("Page 22", AlgorithmSelection.AWERBUCH, TestCase::page22book_awerbuch), new TestCase("Page 22", AlgorithmSelection.CIDON, TestCase::page22book_cidon), new TestCase("Page 23", AlgorithmSelection.TREE, TestCase::page23book_tree), new TestCase("Page 23", AlgorithmSelection.TREEACK, TestCase::page23book_tree_ack), new TestCase("Page 24", AlgorithmSelection.ECHO, TestCase::page24book_echo) }; } static Simulation page20book() { // Example 4.1 Simulation sim = new Simulation(); sim.setAlgorithm(new Tarry()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(q, t)); net.addChannel(new Channel(p, t)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(p, s)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } static Simulation page21book_dfs() { // Example 4.2 Simulation sim = new Simulation(); sim.setAlgorithm(new DFS()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(q, t)); net.addChannel(new Channel(p, t)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(p, s)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } static Simulation page21book_visited() { // Example 4.2 Simulation sim = new Simulation(); sim.setAlgorithm(new Visited()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(q, t)); net.addChannel(new Channel(p, t)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(p, s)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } static Simulation page22book_awerbuch() { // Example 4.1 Simulation sim = new Simulation(); sim.setAlgorithm(new Awerbuch()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(q, t)); net.addChannel(new Channel(p, t)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(p, s)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } static Simulation page22book_cidon() { // Example 4.3 Simulation sim = new Simulation(); sim.setAlgorithm(new Cidon()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(p, r)); net.addChannel(new Channel(p, s)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(s, r)); net.addChannel(new Channel(r, t)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } static Simulation page23book_tree() { // Example 4.4 Simulation sim = new Simulation(); sim.setAlgorithm(new Tree()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 1.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 1.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 6.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node u = net.addNode(new Node("u")); u.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 6.0f); u.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, r)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(r, s)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(s, u)); net.makeUndirected(); sim.setNetwork(net); sim.load(); return sim; } static Simulation page23book_tree_ack() { // Example 4.4 Simulation sim = new Simulation(); sim.setAlgorithm(new TreeAck()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 1.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 1.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 6.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node u = net.addNode(new Node("u")); u.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 6.0f); u.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, r)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(r, s)); net.addChannel(new Channel(s, t)); net.addChannel(new Channel(s, u)); net.makeUndirected(); sim.setNetwork(net); sim.load(); return sim; } static Simulation page24book_echo() { // Example 4.5 Simulation sim = new Simulation(); sim.setAlgorithm(new Echo()); Network net = new Network(); Node p = net.addNode(new Node("p")); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); p.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node q = net.addNode(new Node("q")); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); q.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node r = net.addNode(new Node("r")); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 4.0f); r.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 0.0f); Node s = net.addNode(new Node("s")); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 0.0f); s.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); Node t = net.addNode(new Node("t")); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_X, 2.0f); t.putClientProperty(Node.CLIENT_PROPERTY_POSITION_Y, 2.0f); net.addChannel(new Channel(p, q)); net.addChannel(new Channel(p, t)); net.addChannel(new Channel(p, s)); net.addChannel(new Channel(q, r)); net.addChannel(new Channel(q, s)); net.addChannel(new Channel(q, t)); net.addChannel(new Channel(t, s)); net.makeUndirected(); sim.setNetwork(net); sim.setInitiator(p); sim.load(); return sim; } }
12,345
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
NetworkFrame.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/NetworkFrame.java
package com.aexiz.daviz.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Image; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JToggleButton; import javax.swing.KeyStroke; import com.aexiz.daviz.images.ImageRoot; import com.aexiz.daviz.ui.swing.JCoolBar; import com.aexiz.daviz.ui.swing.JGraph; import com.aexiz.daviz.ui.swing.JStatus; class NetworkFrame extends JDialog { private static final long serialVersionUID = -3706031677602330641L; JCoolBar toolbar; JGraph graph; JStatus status; NetworkFrame(Window owner) { super(owner, "Network"); setAutoRequestFocus(false); ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(ImageRoot.class.getResource("d16/molecule.png")).getImage()); icons.add(new ImageIcon(ImageRoot.class.getResource("d32/molecule.png")).getImage()); setIconImages(icons); JPanel topPane = new JPanel(new BorderLayout()); toolbar = new JCoolBar(); topPane.add(toolbar, BorderLayout.CENTER); graph = new JGraph(); JScrollPane scrollPane = new JScrollPane(graph); scrollPane.setBorder(BorderFactory.createEmptyBorder()); JPanel bottomPane = new JPanel(new BorderLayout()); status = new JStatus(); bottomPane.add(new JSeparator(), BorderLayout.PAGE_START); bottomPane.add(status, BorderLayout.CENTER); Container contentPane = getContentPane(); contentPane.add(topPane, BorderLayout.PAGE_START); contentPane.add(scrollPane, BorderLayout.CENTER); contentPane.add(bottomPane, BorderLayout.PAGE_END); } // Called by Controller to create actions void registerActions(Controller controller) { controller.registerAction("network-mode-select", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Select"); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Object selection and movement"); putValue(Action.LONG_DESCRIPTION, "Drag processes around or select processes and channels."); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/draw_smudge.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/draw_smudge.png"))); } public void actionPerformed(ActionEvent e) { graph.switchToSelectionMode(); graph.requestFocusInWindow(); status.setDefaultStatus(getValue(Action.LONG_DESCRIPTION).toString()); } }); controller.getAction("network-mode-select").actionPerformed(null); controller.registerAction("network-mode-create-node", new AbstractAction() { private static final long serialVersionUID = 7169285620597064570L; { putValue(Action.NAME, "Create process"); putValue(Action.SELECTED_KEY, false); putValue(Action.SHORT_DESCRIPTION, "Create processes"); putValue(Action.LONG_DESCRIPTION, "Add a process by clicking on an empty space."); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/draw_points.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/draw_points.png"))); } public void actionPerformed(ActionEvent e) { graph.switchToVertexMode(); graph.clearSelection(); graph.requestFocusInWindow(); status.setDefaultStatus(getValue(Action.LONG_DESCRIPTION).toString()); } }); controller.registerAction("network-mode-create-edge", new AbstractAction() { private static final long serialVersionUID = 5026362295254309891L; { putValue(Action.NAME, "Create channel"); putValue(Action.SELECTED_KEY, false); putValue(Action.SHORT_DESCRIPTION, "Create channels"); putValue(Action.LONG_DESCRIPTION, "Add a channel by start dragging from a process."); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/draw_vertex.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/draw_vertex.png"))); } public void actionPerformed(ActionEvent e) { graph.switchToEdgeMode(); graph.clearSelection(); graph.requestFocusInWindow(); status.setDefaultStatus(getValue(Action.LONG_DESCRIPTION).toString()); } }); controller.registerAction("network-mode-erase", new AbstractAction() { private static final long serialVersionUID = 5026362295254309891L; { putValue(Action.NAME, "Erase objects"); putValue(Action.SELECTED_KEY, false); putValue(Action.SHORT_DESCRIPTION, "Erase processes and channels"); putValue(Action.LONG_DESCRIPTION, "Click or drag to remove processes and channels."); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_E); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/draw_eraser.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/draw_eraser.png"))); } public void actionPerformed(ActionEvent e) { graph.switchToEraseMode(); graph.clearSelection(); graph.requestFocusInWindow(); status.setDefaultStatus(getValue(Action.LONG_DESCRIPTION).toString()); } }); controller.registerAction("network-select-all", new AbstractAction() { private static final long serialVersionUID = -9066116899817193241L; { putValue(Action.NAME, "Select all"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK)); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A); } public void actionPerformed(ActionEvent e) { graph.selectAll(); graph.requestFocusInWindow(); } }); controller.registerAction("network-remove-selected", new AbstractAction() { private static final long serialVersionUID = -5198464866688780148L; { putValue(Action.NAME, "Remove"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); } public void actionPerformed(ActionEvent e) { graph.removeSelection(); graph.requestFocusInWindow(); } }); controller.registerAction("network-zoom-in", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Zoom in"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, InputEvent.CTRL_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "Zoom in"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_I); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/zoom_in.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/zoom_in.png"))); } public void actionPerformed(ActionEvent e) { graph.zoomIn(); graph.requestFocusInWindow(); } }); controller.registerAction("network-zoom-out", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Zoom out"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, InputEvent.CTRL_DOWN_MASK)); putValue(Action.SHORT_DESCRIPTION, "Zoom out"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O); putValue(Action.LARGE_ICON_KEY, new ImageIcon(ImageRoot.class.getResource("d32/zoom_out.png"))); putValue(Action.SMALL_ICON, new ImageIcon(ImageRoot.class.getResource("d16/zoom_out.png"))); } public void actionPerformed(ActionEvent e) { graph.zoomOut(); graph.requestFocusInWindow(); } }); controller.registerAction("network-show-grid", new AbstractAction() { private static final long serialVersionUID = -7423205754550925733L; { putValue(Action.NAME, "Grid & origin"); putValue(Action.SELECTED_KEY, false); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_G); } public void actionPerformed(ActionEvent e) { boolean sel = (Boolean) getValue(Action.SELECTED_KEY); graph.setShowGrid(sel); } }); } // Called by Controller to refresh registered actions void refreshActions(Controller controller) { if (controller.isSimulationLoaded()) { controller.getAction("network-mode-create-node").setEnabled(false); controller.getAction("network-mode-create-edge").setEnabled(false); controller.getAction("network-mode-erase").setEnabled(false); controller.getAction("network-remove-selected").setEnabled(false); if (graph.getEditMode() != JGraph.MODE_SELECTION) { controller.getAction("network-mode-select").actionPerformed(null); } graph.setReadOnly(true); } else { controller.getAction("network-mode-create-node").setEnabled(true); controller.getAction("network-mode-create-edge").setEnabled(true); controller.getAction("network-mode-erase").setEnabled(true); controller.getAction("network-remove-selected").setEnabled(true); graph.setReadOnly(false); } } // Called by Controller to change menubar void populateMenuBar(Controller controller, JMenuBar menubar) { JMenu menu = new JMenu("Edit"); menu.setMnemonic('e'); ButtonGroup mgrp = new ButtonGroup(); ButtonGroup tgrp = new ButtonGroup(); JMenuItem mb; AbstractButton tb; mb = new JRadioButtonMenuItem(controller.getAction("network-mode-select")); mb.setToolTipText(null); tb = new JToggleButton(controller.getAction("network-mode-select")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); mgrp.add(mb); menu.add(mb); mb = new JRadioButtonMenuItem(controller.getAction("network-mode-create-node")); mb.setToolTipText(null); tb = new JToggleButton(controller.getAction("network-mode-create-node")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); mgrp.add(mb); menu.add(mb); mb = new JRadioButtonMenuItem(controller.getAction("network-mode-create-edge")); mb.setToolTipText(null); tb = new JToggleButton(controller.getAction("network-mode-create-edge")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); mgrp.add(mb); menu.add(mb); mb = new JRadioButtonMenuItem(controller.getAction("network-mode-erase")); mb.setToolTipText(null); tb = new JToggleButton(controller.getAction("network-mode-erase")); tb.setHideActionText(true); tgrp.add(tb); toolbar.add(tb); mgrp.add(mb); menu.add(mb); menu.addSeparator(); menu.add(new JMenuItem(controller.getAction("network-select-all"))); menu.add(new JMenuItem(controller.getAction("network-remove-selected"))); menubar.add(menu, 0); toolbar.addHorizontalGlue(); menu = new JMenu("View"); menu.setMnemonic('v'); mb = new JMenuItem(controller.getAction("network-zoom-in")); mb.setToolTipText(null); tb = new JButton(controller.getAction("network-zoom-in")); tb.setHideActionText(true); toolbar.add(tb); menu.add(mb); mb = new JMenuItem(controller.getAction("network-zoom-out")); mb.setToolTipText(null); tb = new JButton(controller.getAction("network-zoom-out")); tb.setHideActionText(true); toolbar.add(tb); menu.add(mb); menu.addSeparator(); mb = new JCheckBoxMenuItem(controller.getAction("network-show-grid")); mb.setToolTipText(null); menu.add(mb); menubar.add(menu, 1); } }
12,066
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DefaultCarouselCellRenderer.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/DefaultCarouselCellRenderer.java
package com.aexiz.daviz.ui.swing; import java.awt.Component; import java.awt.Rectangle; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.border.Border; public class DefaultCarouselCellRenderer extends JLabel implements CarouselCellRenderer { private static final long serialVersionUID = 6948963333208661930L; boolean loaded; Border selectedAndFocus; Border notSelectedAndFocus; Border notFocus; private void loadBordersFromListRenderer() { if (loaded) return; JList<Object> l = new JList<>(); ListCellRenderer<Object> lcr = l.getCellRenderer(); Component c = lcr.getListCellRendererComponent(l, "", 0, true, true); if (c instanceof JComponent) { selectedAndFocus = ((JComponent) c).getBorder(); } c = lcr.getListCellRendererComponent(l, "", 0, false, true); if (c instanceof JComponent) { notSelectedAndFocus = ((JComponent) c).getBorder(); } c = lcr.getListCellRendererComponent(l, "", 0, false, false); if (c instanceof JComponent) { notFocus = ((JComponent) c).getBorder(); } loaded = true; } public Component getCarouselCellRendererComponent(JCarousel list, Object value, int index, boolean isSelected, boolean cellHasFocus) { loadBordersFromListRenderer(); setOpaque(true); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setText(value == null ? "" : value.toString()); setEnabled(list.isEnabled()); setFont(list.getFont()); Border border = null; if (cellHasFocus) { if (isSelected) { border = selectedAndFocus; } if (border == null) { border = notSelectedAndFocus; } } else { border = notFocus; } if (border == null) { border = BorderFactory.createEmptyBorder(1, 1, 1, 1); } setBorder(border); return this; } public void validate() {} public void invalidate() {} public void repaint() {} public void repaint(long tm, int x, int y, int width, int height) {} public void repaint(Rectangle r) {} }
2,286
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DefaultObjectSelectionModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/DefaultObjectSelectionModel.java
package com.aexiz.daviz.ui.swing; import java.util.IdentityHashMap; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; public class DefaultObjectSelectionModel implements ObjectSelectionModel { private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } private boolean multiSelection = true; protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } private IdentityHashMap<Object,Object> set = new IdentityHashMap<Object,Object>(); private static Object SENTINEL = new Object(); public void clearSelection() { set.clear(); fireStateChanged(); } public boolean isSelected(Object o) { return set.containsKey(o); } public boolean isSelectionEmpty() { return set.isEmpty(); } public boolean addSelection(Object o) { if (!multiSelection && set.size() == 1) return false; boolean result = set.put(o, SENTINEL) == null; if (result) { fireStateChanged(); } return result; } public void removeSelection(Object o) { if (set.remove(o) != null) { fireStateChanged(); } } public Object[] getSelection() { return set.keySet().toArray(new Object[0]); } public void setMultiSelection(boolean multi) { throw new Error("Not implemented yed"); } public boolean isMultiSelection() { return multiSelection; } public void refreshSelection() { fireStateChanged(); } }
2,034
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
GraphModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/GraphModel.java
package com.aexiz.daviz.ui.swing; import java.util.ArrayList; import java.util.EventListener; import java.util.EventObject; import javax.swing.event.ChangeListener; public interface GraphModel { public interface NodeModel { public void addChangeListener(ChangeListener l); public void removeChangeListener(ChangeListener l); public void setX(float x); public void setDeltaX(float dx); public float getX(); public float getXWithoutDelta(); public void setY(float y); public void setDeltaY(float dy); public float getY(); public float getYWithoutDelta(); public GraphModel getParent(); public boolean isPressed(); public void setPressed(boolean pressed); public void validate(); public void setLabel(String label); public String getLabel(); public boolean isOverlapping(); public void remove(); public void addIncomingNode(String node); public void removeIncomingNode(String node); public ArrayList<String> getIncomingNodes(); public void addOutgoingNode(String node); public void removeOutgoingNode(String node); public ArrayList<String> getOutgoingNodes(); } public interface EdgeModel { public void addChangeListener(ChangeListener l); public void removeChangeListener(ChangeListener l); public boolean isDirected(); public void setDirected(boolean directed); public NodeModel getFrom(); public NodeModel getTo(); public GraphModel getParent(); public void validate(); public void remove(); } interface ModeEventListener extends EventListener { void modeChanged(EventObject e); } public void addChangeListener(ChangeListener l); public void removeChangeListener(ChangeListener l); public void addModeEventListener(ModeEventListener l); public void removeModeEventListener(ModeEventListener l); public NodeModel createNode(float x, float y); public EdgeModel createEdge(NodeModel from, NodeModel to); public int getNodeCount(); public NodeModel getNode(int index); public NodeModel[] getNode(); public NodeModel getRandomNode(); public void addNode(NodeModel n); public void removeNode(NodeModel n); public int getEdgeCount(); public EdgeModel getEdge(int index); public void addEdge(EdgeModel e); public void removeEdge(EdgeModel e); public EdgeModel[] getEdge(); public NodeModel[] getValidNode(); public EdgeModel[] getValidEdge(); public void setSnapToGrid(boolean snap); public boolean isSnapToGrid(); static final int MODE_SELECTION = 0; static final int MODE_VERTEX = 1; static final int MODE_EDGE = 2; static final int MODE_ERASE = 3; public void setEditMode(int mode); public int getEditMode(); public void setTemporaryNode(NodeModel n); public NodeModel getTemporaryNode(); public NodeModel findNearestValidNodeToTemporary(); public NodeModel findNearestValidNode(float fx, float fy); public void clearTemporaryNode(); public void setTemporaryEdge(EdgeModel e); public EdgeModel getTemporaryEdge(); public void clearTemporaryEdge(); public void validate(); public void clear(); public void setZoomLevel(float zoom); public float getZoomLevel(); public void setReadOnly(boolean read); public boolean isReadOnly(); }
3,500
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JTimeline.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JTimeline.java
package com.aexiz.daviz.ui.swing; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.util.EventObject; import javax.swing.JComponent; import javax.swing.JViewport; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.ExecutionModel.DecideEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.EventModel; import com.aexiz.daviz.ui.swing.ExecutionModel.InternalEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.MessageModel; import com.aexiz.daviz.ui.swing.ExecutionModel.PendingMessageModel; import com.aexiz.daviz.ui.swing.ExecutionModel.ReceiveEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.ReorderEvent; import com.aexiz.daviz.ui.swing.ExecutionModel.ReorderEventListener; import com.aexiz.daviz.ui.swing.ExecutionModel.SendEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.TerminateEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.TimeEventListener; import com.aexiz.daviz.ui.swing.plaf.TimelineUI; import com.aexiz.daviz.ui.swing.plaf.basic.BasicTimelineUI; /** * A timeline visually represents a particular execution model. */ public class JTimeline extends JComponent { private static final long serialVersionUID = 1947693107247971077L; static final String UICLASSID = "TimelineUI"; protected ExecutionModel model; protected ObjectSelectionModel selectionModel; private Handler handler; protected ChangeListener changeListener; protected TimeEventListener timeEventListener; protected ReorderEventListener reorderEventListener; protected transient ChangeEvent changeEvent; static { UIDefaults def = UIManager.getDefaults(); if (def.get(UICLASSID) == null) def.put(UICLASSID, BasicTimelineUI.class.getName()); } public JTimeline() { setOpaque(true); setFocusable(true); setModel(new DefaultExecutionModel()); setSelectionModel(new DefaultObjectSelectionModel()); updateUI(); } private Color alternateBackground; public void setAlternateBackground(Color c) { Color old = alternateBackground; alternateBackground = c; firePropertyChange("alternateBackground", old, c); repaint(); } public Color getAlternateBackground() { return alternateBackground; } private Color innerBackground; public void setInnerBackground(Color c) { Color old = innerBackground; innerBackground = c; firePropertyChange("innerBackground", old, c); repaint(); } public Color getInnerBackground() { return innerBackground; } private Border innerBorder; public void setInnerBorder(Border b) { Border old = innerBorder; innerBorder = b; firePropertyChange("innerBorder", old, b); repaint(); } public Border getInnerBorder() { return innerBorder; } public Insets getInnerInsets() { if (innerBorder != null) return innerBorder.getBorderInsets(this); return new Insets(0, 0, 0, 0); } public Insets getInnerInsets(Insets i) { if (i == null) return getInnerInsets(); if (innerBorder instanceof AbstractBorder) return ((AbstractBorder) innerBorder).getBorderInsets(this, i); if (innerBorder != null) return getInnerInsets(); i.top = i.left = i.right = i.bottom = 0; return i; } public static class JEvent extends JKnob { private static final long serialVersionUID = 1985826609656196598L; private EventModel model; private ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { fireStateChanged(); revalidate(); } }; protected JEvent() { } public void setModel(EventModel model) { EventModel oldModel = this.model; if (oldModel != null) { oldModel.removeChangeListener(changeListener); } this.model = model; if (model != null) { model.addChangeListener(changeListener); } firePropertyChange("model", oldModel, model); } public EventModel getModel() { return model; } public JTimeline getTimeline() { Component c = getParent(); if (c instanceof JTimeline) return (JTimeline) c; return null; } public void setRollover(boolean b) { if (model == null) return; model.setRollover(b); } public boolean isRollover() { if (model == null) return false; return model.isRollover(); } public void setPressed(boolean b) { if (model == null || !model.isLeader()) return; boolean old = model.isPressed(); model.setPressed(b); if (!(old && !b)) return; model.validate(); } public boolean isPressed() { if (model == null) return false; return model.isPressed(); } public boolean isTerminateEvent() { return model != null && model.getEventType() instanceof TerminateEventType; } public boolean isDecideEvent() { return model != null && model.getEventType() instanceof DecideEventType; } public boolean isInternalEvent() { return model != null && model.getEventType() instanceof InternalEventType; } public boolean isSendEvent() { return model != null && model.getEventType() instanceof SendEventType; } public boolean isReceiveEvent() { return model != null && model.getEventType() instanceof ReceiveEventType; } public void setDelta(float delta) { if (model == null || !model.isLeader()) return; model.setDelta(delta); } public int getProcessIndex() { if (model == null) return 0; return model.getProcessIndex(); } public float getTime() { if (model == null) return 0.0f; return model.getTime(); } public float getAscention() { if (model == null) return 0.0f; return model.getAscention(); } public boolean isSelected() { JTimeline g = getTimeline(); if (g == null) return false; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { return selModel.isSelected(model); } else { return false; } } public void setSelected(boolean sel) { if (isSelected() == sel) return; JTimeline g = getTimeline(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { if (sel) { selModel.addSelection(model); } else { selModel.removeSelection(model); } } } public void requestSingleSelected() { JTimeline g = getTimeline(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { selModel.clearSelection(); selModel.addSelection(model); } } public void requestClearSelection() { JTimeline g = getTimeline(); if (g == null) return; g.clearSelection(); } public void requestAllSelected() { JTimeline g = getTimeline(); if (g == null) return; g.selectAllEvents(); } // Utilities for scrolling public JViewport getViewport() { JViewport viewport; Container p = getParent(); while (p != null && !(p instanceof JViewport)) p = p.getParent(); viewport = (JViewport) p; return viewport; } public Point scrollRectToVisibleWithEffect(Rectangle rect) { // A simple utility for UIs to find out the effect in pixels of scrolling, // to adjust the tracking of the mouse JViewport viewport = getViewport(); if (viewport == null) return new Point(0, 0); // No effect Point old = viewport.getViewPosition(); super.scrollRectToVisible(rect); Point next = viewport.getViewPosition(); return new Point(old.x - next.x, old.y - next.y); } } public static class JMessage extends JKnob { private static final long serialVersionUID = -1075183018340778712L; public static final int DIR_NORTH_EAST = 1; public static final int DIR_SOUTH_EAST = 2; public static final int DIR_SOUTH_WEST = 3; public static final int DIR_NORTH_WEST = 4; // Either MessageModel or PendingMessageModel protected Object model; protected int direction; protected JMessage() { } public void setModel(MessageModel model) { Object oldModel = this.model; this.model = model; firePropertyChange("model", oldModel, model); } public void setModel(PendingMessageModel model) { Object oldModel = this.model; this.model = model; firePropertyChange("model", oldModel, model); } public Object getModel() { return model; } public MessageModel getMessageModel() { return (MessageModel) model; } public PendingMessageModel getPendingMessageModel() { return (PendingMessageModel) model; } public JTimeline getTimeline() { Component c = getParent(); if (c instanceof JTimeline) return (JTimeline) c; return null; } private Color errorColor; public void setErrorColor(Color color) { Color old = errorColor; errorColor = color; firePropertyChange("errorColor", old, color); repaint(); } public Color getErrorColor() { return errorColor; } private EventModel modelGetFrom() { if (model instanceof MessageModel) { return ((MessageModel) model).getFrom(); } else if (model instanceof PendingMessageModel) { return ((PendingMessageModel) model).getFrom(); } else { return null; } } public JEvent getFromEvent() { JTimeline t = getTimeline(); EventModel from = modelGetFrom(); if (t != null && from != null) { return t.findEventComponent(from); } else { return null; } } public Integer getFromProcessIndex() { EventModel from = modelGetFrom(); if (from == null) return null; return from.getProcessIndex(); } public JEvent getToEvent() { JTimeline t = getTimeline(); if (t != null && model instanceof MessageModel) { return t.findEventComponent(((MessageModel) model).getTo()); } else { return null; } } public Integer getToProcessIndex() { if (model instanceof MessageModel) { return ((MessageModel) model).getTo().getProcessIndex(); } else if (model instanceof PendingMessageModel) { return ((PendingMessageModel) model).getTo(); } else { return null; } } public boolean isConflicting() { if (model instanceof MessageModel) { return ((MessageModel) model).isConflicting(); } else { return false; } } public boolean isPending() { return model instanceof PendingMessageModel; } public boolean isSelected() { JTimeline g = getTimeline(); if (g == null) return false; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { return selModel.isSelected(model); } else { return false; } } public void setSelected(boolean sel) { if (isSelected() == sel) return; JTimeline g = getTimeline(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { if (sel) { selModel.addSelection(model); } else { selModel.removeSelection(model); } } } public void requestSingleSelected() { JTimeline g = getTimeline(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { selModel.clearSelection(); selModel.addSelection(model); } } public void requestClearSelection() { JTimeline g = getTimeline(); if (g == null) return; g.clearSelection(); } public void requestAllSelected() { JTimeline g = getTimeline(); if (g == null) return; g.selectAllMessages(); } // Updated by L&F public void setDirection(int direction) { if (direction < 0 || direction > DIR_NORTH_WEST) throw new IllegalArgumentException(); this.direction = direction; } public int getDirection() { return direction; } } public static class JTimeRuler extends JComponent { private static final long serialVersionUID = 7409778629836110204L; protected ExecutionModel model; protected float time; protected boolean pressed; private Handler handler; protected TimeEventListener timeEventListener; protected transient EventObject timeEvent; protected JTimeRuler() { setAutoscrolls(true); } public void addTimeEventListener(TimeEventListener listener) { listenerList.add(TimeEventListener.class, listener); } public void removeTimeEventListener(TimeEventListener listener) { listenerList.remove(TimeEventListener.class, listener); } protected void fireTimeChanged() { if (timeEvent == null) timeEvent = new EventObject(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == TimeEventListener.class) ((TimeEventListener) listeners[i+1]).timeChanged(timeEvent); } public void setModel(ExecutionModel model) { ExecutionModel oldModel = this.model; if (oldModel != null) { oldModel.removeTimeEventListener(timeEventListener); timeEventListener = null; } this.model = model; if (model != null) { timeEventListener = createTimeEventListener(); model.addTimeEventListener(timeEventListener); } firePropertyChange("model", oldModel, model); fireTimeChanged(); } public ExecutionModel getModel() { return model; } public void setUI(ComponentUI ui) { super.setUI(ui); } public ComponentUI getUI() { return ui; } public void setPressed(boolean b) { pressed = b; if (!(pressed && model != null)) model.validateTime(); } public boolean isPressed() { return pressed; } public void setDelta(float d) { if (model == null) return; model.setCurrentTimeDelta(d); } public JViewport getViewport() { JViewport viewport; Container p = getParent(); while (p != null && !(p instanceof JViewport)) p = p.getParent(); viewport = (JViewport) p; return viewport; } public Point scrollRectToVisibleWithEffect(Rectangle rect) { // A simple utility for UIs to find out the effect in pixels of scrolling, // to adjust the tracking of the mouse JViewport viewport = getViewport(); if (viewport == null) return new Point(0, 0); // No effect Point old = viewport.getViewPosition(); super.scrollRectToVisible(rect); Point next = viewport.getViewPosition(); return new Point(old.x - next.x, old.y - next.y); } protected TimeEventListener createTimeEventListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } class Handler implements TimeEventListener { public void timeChanged(EventObject e) { fireTimeChanged(); } } } public void setModel(ExecutionModel newModel) { ExecutionModel oldModel = getModel(); removeSubComponents(); if (oldModel != null) { oldModel.removeChangeListener(changeListener); changeListener = null; oldModel.removeTimeEventListener(timeEventListener); timeEventListener = null; oldModel.removeReorderEventListener(reorderEventListener); reorderEventListener = null; } model = newModel; if (newModel != null) { changeListener = createChangeListener(); newModel.addChangeListener(changeListener); timeEventListener = createTimeEventListener(); newModel.addTimeEventListener(timeEventListener); reorderEventListener = createReorderEventListener(); newModel.addReorderEventListener(reorderEventListener); } firePropertyChange("model", oldModel, newModel); if (newModel != oldModel) { updateSubComponents(); } } public ExecutionModel getModel() { return model; } public void setSelectionModel(ObjectSelectionModel selModel) { ObjectSelectionModel oldModel = getSelectionModel(); if (oldModel != null) { oldModel.removeChangeListener(changeListener); changeListener = null; } selectionModel = selModel; if (selModel != null) { changeListener = createChangeListener(); selModel.addChangeListener(changeListener); } firePropertyChange("selectionModel", oldModel, selModel); if (selModel != oldModel) { repaint(); } } public ObjectSelectionModel getSelectionModel() { return selectionModel; } public void clearSelection() { if (selectionModel != null) selectionModel.clearSelection(); } public void selectAllEvents() { if (selectionModel != null && model != null) { for (EventModel event : model.getValidEvent()) { selectionModel.addSelection(event); } } } public void selectAllMessages() { if (selectionModel != null && model != null) { for (MessageModel msg : model.getValidMessage()) { selectionModel.addSelection(msg); } for (PendingMessageModel msg : model.getValidPendingMessage()) { selectionModel.addSelection(msg); } } } public float getCurrentTime() { if (model == null) return 0.0f; return model.getCurrentTime(); } public void setCurrentTime(float time) { if (model == null) return; model.setCurrentTime(time); } public void updateUI() { setUI((TimelineUI) UIManager.getUI(this)); } public void setUI(TimelineUI ui) { removeSubComponents(); super.setUI(ui); updateSubComponents(); } public TimelineUI getUI() { return (TimelineUI) ui; } public String getUIClassID() { return UICLASSID; } public boolean isOptimizedDrawingEnabled() { return false; } public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } public ChangeListener[] getChangeListeners() { return listenerList.getListeners(ChangeListener.class); } protected void fireStateChanged() { if (changeEvent == null) changeEvent = new ChangeEvent(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ChangeListener.class) ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } public void addReorderEventListener(ReorderEventListener l) { listenerList.add(ReorderEventListener.class, l); } public void removeReorderEventListener(ReorderEventListener l) { listenerList.remove(ReorderEventListener.class, l); } protected void fireReorderStarted(ReorderEvent e) { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderStarted(e); } protected void fireReorderEnded(ReorderEvent e) { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderEnded(e); } protected void fireReorderUpdating(ReorderEvent e) { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderUpdating(e); } private JTimeRuler ruler; private void removeSubComponents() { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JEvent) { ((JEvent) c).setModel(null); remove(i--); n--; } else if (c instanceof JMessage) { ((JMessage) c).setModel((MessageModel) null); remove(i--); n--; } else if (c instanceof JTimeRuler) { remove(i--); n--; ruler = null; } } } private void updateSubComponents() { removeSubComponents(); ExecutionModel model = getModel(); if (model == null) return; TimelineUI ui = getUI(); for (EventModel event : model.getValidEvent()) { JEvent c = createEventComponent(event); if (ui != null) ui.configureEventComponent(c); add(c); } for (MessageModel message : model.getValidMessage()) { JMessage c = createMessageComponent(message); if (ui != null) ui.configureMessageComponent(c); add(c); } for (PendingMessageModel message : model.getValidPendingMessage()) { JMessage c = createMessageComponent(message); if (ui != null) ui.configureMessageComponent(c); add(c); } { JTimeRuler c = createTimeRulerComponent(); c.setModel(model); if (ui != null) ui.configureTimeRulerComponent(c); add(c); // lowest z-order ruler = c; } } public JTimeRuler getRuler() { return ruler; } public static final int MODE_SELECTION = 0; public static final int MODE_SWAP = 1; public void setEditMode(int mode) { if (model == null) return; model.setEditMode(mode); } public int getEditMode() { if (model == null) return MODE_SELECTION; return model.getEditMode(); } public JEvent findEventComponent(EventModel event) { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JEvent) { JEvent e = (JEvent) c; if (e.model == event) return e; } } throw new IllegalArgumentException("Component not found for " + event); } public JMessage findMessageComponent(MessageModel message) { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JMessage) { JMessage m = (JMessage) c; if (m.model == message) return m; } } throw new IllegalArgumentException("Component not found for " + message); } protected JEvent createEventComponent(EventModel event) { JEvent result = new JEvent(); result.setModel(event); return result; } protected JMessage createMessageComponent(MessageModel message) { JMessage result = new JMessage(); result.setModel(message); return result; } protected JMessage createMessageComponent(PendingMessageModel message) { JMessage result = new JMessage(); result.setModel(message); return result; } protected JTimeRuler createTimeRulerComponent() { JTimeRuler result = new JTimeRuler(); return result; } protected ChangeListener createChangeListener() { return getHandler(); } protected TimeEventListener createTimeEventListener() { return getHandler(); } protected ReorderEventListener createReorderEventListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } class Handler implements ChangeListener, TimeEventListener, ReorderEventListener { public void stateChanged(ChangeEvent e) { if (e.getSource() == model) { updateSubComponents(); revalidate(); repaint(); fireStateChanged(); } else if (e.getSource() == selectionModel) { repaint(); } } public void timeChanged(EventObject e) { revalidate(); } public void reorderStarted(ReorderEvent e) { fireReorderStarted(ReorderEvent.createFromComponent(e, JTimeline.this)); } public void reorderUpdating(ReorderEvent e) { fireReorderUpdating(ReorderEvent.createFromComponent(e, JTimeline.this)); } public void reorderEnded(ReorderEvent e) { fireReorderEnded(ReorderEvent.createFromComponent(e, JTimeline.this)); } } }
24,274
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DefaultInfoModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/DefaultInfoModel.java
package com.aexiz.daviz.ui.swing; import java.util.ArrayList; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; public class DefaultInfoModel implements InfoModel { class DefaultPropertyModel implements PropertyModel { String title; Object value; PropertyType type; Object parent; private ArrayList<DefaultPropertyModel> properties; private transient boolean added; DefaultPropertyModel(PropertyModel parent, String title, Object value, PropertyType type) { if (title == null || type == null) throw null; if (type instanceof InfoModel.SimplePropertyType) { if (!(value instanceof String)) throw new IllegalArgumentException(); } else if (type instanceof InfoModel.CompoundPropertyType) { this.properties = new ArrayList<DefaultPropertyModel>(); if (value != null) throw new IllegalArgumentException(); } else throw new Error(); this.title = title; this.value = value; this.type = type; this.parent = parent == null ? DefaultInfoModel.this : parent; } public String getTitle() { return title; } public Object getValue() { if (properties != null) return properties.toArray(new PropertyModel[properties.size()]); return value; } public PropertyType getType() { return type; } public Object getParent() { return parent; } DefaultInfoModel getRoot() { return DefaultInfoModel.this; } public void setProperty(PropertyModel[] ps) { for (DefaultPropertyModel p : properties) { p.unown(); } properties.clear(); for (PropertyModel p : ps) { addProperty0(-1, p); } if (added) fireStateChanged(); } public void addProperty(PropertyModel p) { addProperty0(-1, p); if (added) fireStateChanged(); } private void addProperty0(int index, PropertyModel m) { if (m == null) throw null; DefaultPropertyModel dm = (DefaultPropertyModel) m; if (dm.getRoot() != DefaultInfoModel.this) throw new IllegalArgumentException(); if (dm.added) throw new IllegalArgumentException(); if (dm.getParent() != this) throw new IllegalArgumentException(); DefaultPropertyModel old = index < 0 ? null : properties.get(index); for (DefaultPropertyModel k : properties) { if (k == old) continue; if (k.getTitle().equals(dm.getTitle())) throw new IllegalArgumentException(); } if (index < 0) properties.add(dm); else properties.set(index, dm); if (added) dm.own(); } public void clear() { for (DefaultPropertyModel p : properties) { p.unown(); } properties.clear(); if (added) fireStateChanged(); } void unown() { added = false; if (properties != null) for (DefaultPropertyModel p : properties) p.unown(); } void own() { if (properties != null) for (DefaultPropertyModel p : properties) p.own(); added = true; } } public PropertyModel createProperty(String title, Object value, PropertyType type) { return new DefaultPropertyModel(null, title, value, type); } public PropertyModel createNestedProperty(PropertyModel parent, String title, Object value, PropertyType type) { if (parent == null) throw null; if (((DefaultPropertyModel) parent).getRoot() != this) throw new IllegalArgumentException(); return new DefaultPropertyModel(parent, title, value, type); } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { if (changeEvent == null) changeEvent = new ChangeEvent(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ChangeListener.class) ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } private ArrayList<DefaultPropertyModel> properties = new ArrayList<DefaultPropertyModel>(); public int getPropertyCount() { return properties.size(); } public PropertyModel[] getProperty() { return properties.toArray(new PropertyModel[properties.size()]); } public String getPropertyTitle(int index) { return properties.get(index).getTitle(); } public Object getPropertyValue(int index) { return properties.get(index).getValue(); } public void setProperty(PropertyModel[] ps) { for (DefaultPropertyModel p : properties) { p.unown(); } properties.clear(); for (PropertyModel p : ps) { addProperty0(-1, p); } fireStateChanged(); } public void addProperty(PropertyModel p) { addProperty0(-1, p); fireStateChanged(); } public void addNestedProperty(PropertyModel parent, PropertyModel nested) { ((DefaultPropertyModel) parent).addProperty(nested); } private void addProperty0(int index, PropertyModel m) { if (m == null) throw null; DefaultPropertyModel dm = (DefaultPropertyModel) m; if (dm.getRoot() != this) throw new IllegalArgumentException(); if (dm.added) throw new IllegalArgumentException(); if (dm.getParent() != this) throw new IllegalArgumentException(); DefaultPropertyModel old = index < 0 ? null : properties.get(index); for (DefaultPropertyModel k : properties) { if (k == old) continue; if (k.getTitle().equals(dm.getTitle())) throw new IllegalArgumentException(); } if (index < 0) properties.add(dm); else properties.set(index, dm); dm.own(); } public void clear() { for (DefaultPropertyModel p : properties) { p.unown(); } properties.clear(); fireStateChanged(); } }
5,986
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
InfoModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/InfoModel.java
package com.aexiz.daviz.ui.swing; import java.io.Serializable; import javax.swing.event.ChangeListener; public interface InfoModel { static abstract class PropertyType implements Serializable { private static final long serialVersionUID = -7469784089240414551L; PropertyType() {} } // value is String static class SimplePropertyType extends PropertyType { private static final long serialVersionUID = 3989437777413291201L; SimplePropertyType() {} } // value is Property[] static class CompoundPropertyType extends PropertyType { private static final long serialVersionUID = -8024401864871586063L; CompoundPropertyType() {} } static final SimplePropertyType SIMPLE_TYPE = new SimplePropertyType(); static final CompoundPropertyType COMPOUND_TYPE = new CompoundPropertyType(); interface PropertyModel { String getTitle(); Object getValue(); PropertyType getType(); // PropertyModel if nested, InfoModel if top-level Object getParent(); } PropertyModel createProperty(String title, Object value, PropertyType type); PropertyModel createNestedProperty(PropertyModel parent, String title, Object value, PropertyType type); void addChangeListener(ChangeListener l); void removeChangeListener(ChangeListener l); int getPropertyCount(); PropertyModel[] getProperty(); String getPropertyTitle(int index); Object getPropertyValue(int index); }
1,474
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JInfoTable.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JInfoTable.java
package com.aexiz.daviz.ui.swing; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.aexiz.daviz.ui.swing.InfoModel.PropertyModel; import com.aexiz.daviz.ui.swing.plaf.InfoTableUI; import com.aexiz.daviz.ui.swing.plaf.basic.BasicInfoTableUI; public class JInfoTable extends JComponent { private static final long serialVersionUID = -1127997595981620390L; public static final String CLIENT_PROPERTY_MODEL = "model"; public static final String CLIENT_PROPERTY_KIND = "kind"; public static final String KIND_LABEL = "label"; public static final String KIND_VALUE = "value"; public static final String KIND_FILLER = "filler"; static final String UICLASSID = "BasicInfoUI"; protected InfoModel model; private Handler handler; protected ChangeListener changeListener; protected transient ChangeEvent changeEvent; static { UIDefaults def = UIManager.getDefaults(); if (def.get(UICLASSID) == null) def.put(UICLASSID, BasicInfoTableUI.class.getName()); } public JInfoTable() { setOpaque(true); setModel(new DefaultInfoModel()); updateUI(); } public void setModel(InfoModel newModel) { InfoModel oldModel = getModel(); removeSubComponents(); if (oldModel != null) { oldModel.removeChangeListener(changeListener); changeListener = null; } model = newModel; if (newModel != null) { changeListener = createChangeListener(); newModel.addChangeListener(changeListener); } firePropertyChange("model", oldModel, newModel); if (newModel != oldModel) { updateSubComponents(); } } public InfoModel getModel() { return model; } public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } public ChangeListener[] getChangeListeners() { return listenerList.getListeners(ChangeListener.class); } protected void fireStateChanged() { if (changeEvent == null) changeEvent = new ChangeEvent(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ChangeListener.class) ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } public void updateUI() { setUI((InfoTableUI) UIManager.getUI(this)); } public void setUI(InfoTableUI ui) { removeSubComponents(); super.setUI(ui); updateSubComponents(); } public InfoTableUI getUI() { return (InfoTableUI) ui; } public String getUIClassID() { return UICLASSID; } public int getVisibleIndexCount() { class Procedure { int curSize = 0; void compute(PropertyModel[] properties) { for (int i = 0; i < properties.length; i++) { if (properties[i].getTitle().length() == 0) continue; if (properties[i].getType() instanceof InfoModel.SimplePropertyType) { curSize++; } else if (properties[i].getType() instanceof InfoModel.CompoundPropertyType) { curSize++; try { PropertyModel[] nested = (PropertyModel[]) properties[i].getValue(); for (PropertyModel n : nested) { if (n.getParent() != properties[i]) throw new Exception(); } compute(nested); } catch (Exception ex) { // Ignore whole property contents } } else throw new Error(); } } } if (model == null) return 0; PropertyModel[] properties = model.getProperty(); for (PropertyModel nested : properties) { // Ignore invalid models if (nested.getParent() != model) return 0; } Procedure p = new Procedure(); p.compute(properties); return p.curSize; } public int getVisibleIndex(PropertyModel property) { if (property.getTitle().length() == 0) throw new UnsupportedOperationException(); class Procedure { int curSize = 0; int index = -1; void compute(PropertyModel[] properties) { for (int i = 0; i < properties.length; i++) { if (properties[i].getTitle().length() == 0) continue; if (properties[i] == property) { index = curSize; break; } if (properties[i].getType() instanceof InfoModel.SimplePropertyType) { curSize++; } else if (properties[i].getType() instanceof InfoModel.CompoundPropertyType) { curSize++; try { PropertyModel[] nested = (PropertyModel[]) properties[i].getValue(); for (PropertyModel n : nested) { if (n.getParent() != properties[i]) throw new Exception(); } compute(nested); if (index >= 0) break; } catch (Exception ex) { // Ignore whole property contents } } else throw new Error(); } } } if (model == null) return -1; PropertyModel[] properties = model.getProperty(); for (PropertyModel nested : properties) { // Ignore invalid models if (nested.getParent() != model) return -1; } Procedure p = new Procedure(); p.compute(properties); return p.index; } private void removeSubComponents() { int n = getComponentCount(); for (int i = 0; i < n; i++) { // Component c = getComponent(i); remove(i--); n--; } } private void updateSubComponents() { removeSubComponents(); InfoModel model = getModel(); if (model == null) return; PropertyModel[] properties = model.getProperty(); for (PropertyModel p : properties) { // Ignore invalid models if (p.getParent() != model) return; } updateSubComponents_p0(properties); // Always add a filler label InfoTableUI ui = getUI(); JComponent filler = createFillerComponent(); filler.putClientProperty(CLIENT_PROPERTY_KIND, KIND_FILLER); if (ui != null) { ui.configureFillerComponent(filler); ui.addComponent(this, filler); } else { add(filler); } revalidate(); } private void updateSubComponents_p0(PropertyModel[] properties) { InfoTableUI ui = getUI(); for (PropertyModel p : properties) { String title = p.getTitle(); if (title.length() == 0) continue; JLabel label = createLabelComponent(title); label.putClientProperty(CLIENT_PROPERTY_MODEL, p); label.putClientProperty(CLIENT_PROPERTY_KIND, KIND_LABEL); if (ui != null) { ui.configureLabelComponent(label); ui.addComponent(this, label); } else { add(label); } if (p.getType() instanceof InfoModel.SimplePropertyType) { String value = p.getValue().toString(); // String.toString() = this JTextField field = createSimplePropertyComponent(value); field.putClientProperty(CLIENT_PROPERTY_MODEL, p); field.putClientProperty(CLIENT_PROPERTY_KIND, KIND_VALUE); if (ui != null) { ui.configureSimplePropertyComponent(field); ui.addComponent(this, field); } else { add(field); } } else if (p.getType() instanceof InfoModel.CompoundPropertyType) { PropertyModel[] nested; try { nested = (PropertyModel[]) p.getValue(); for (PropertyModel n : nested) { if (n.getParent() != p) throw new Exception(); } } catch (Exception ex) { continue; } // Find special key under properties PropertyModel special = null; for (PropertyModel n : nested) { if (n.getTitle().length() == 0) { special = n; break; } } if (special == null) { JComponent placeholder = createNestedPlaceholderComponent(); placeholder.putClientProperty(CLIENT_PROPERTY_MODEL, p); placeholder.putClientProperty(CLIENT_PROPERTY_KIND, KIND_VALUE); if (ui != null) { ui.configureNestedPlaceholderComponent(placeholder); ui.addComponent(this, placeholder); } else { add(placeholder); } } else { String value = special.getValue().toString(); JTextField field = createSimplePropertyComponent(value); field.putClientProperty(CLIENT_PROPERTY_MODEL, p); field.putClientProperty(CLIENT_PROPERTY_KIND, KIND_VALUE); if (ui != null) { ui.configureSimplePropertyComponent(field); ui.addComponent(this, field); } else { add(field); } } updateSubComponents_p0(nested); } else throw new Error(); } } protected JLabel createLabelComponent(String name) { JLabel result = new JLabel(name); return result; } protected JTextField createSimplePropertyComponent(String value) { JTextField result = new JTextField(); result.setText(value); result.setEditable(false); return result; } protected JComponent createNestedPlaceholderComponent() { return new JLabel(); } protected JComponent createFillerComponent() { return new JLabel(); } protected ChangeListener createChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } class Handler implements ChangeListener { @Override public void stateChanged(ChangeEvent arg0) { updateSubComponents(); revalidate(); repaint(); fireStateChanged(); } } }
9,423
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DefaultExecutionModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/DefaultExecutionModel.java
package com.aexiz.daviz.ui.swing; import java.util.ArrayList; import java.util.Collections; import java.util.EventObject; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; /** * An execution model consists of zero or more processes, numbered $0, 1, \ldots, n - 1$. * * Each event has an associated process number, $0 \leq e_p \le n$, an extensible type * value (disjoint: send, receive, internal) and time $0 \leq e_t$. For the same process, * no two events have the same time value. * * Each message has a sender event and a receiver event. We assume that these events * occur at different processes, but they may occur at the same time. * * Events are grouped together, and within one process no events may overlap. Also, * messages being sent may not occur at an event after the message being received. The * model will maintain these constraints. */ public class DefaultExecutionModel implements ExecutionModel { private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { if (changeEvent == null) changeEvent = new ChangeEvent(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ChangeListener.class) ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } public void addTimeEventListener(TimeEventListener l) { listenerList.add(TimeEventListener.class, l); } public void removeTimeEventListener(TimeEventListener l) { listenerList.remove(TimeEventListener.class, l); } public void addCoarseTimeEventListener(CoarseTimeEventListener l) { listenerList.add(CoarseTimeEventListener.class, l); } public void removeCoarseTimeEventListener(CoarseTimeEventListener l) { listenerList.remove(CoarseTimeEventListener.class, l); } protected float lastCoarseTime = Float.NaN; protected transient EventObject timeEvent; protected void fireTimeChanged() { if (timeEvent == null) timeEvent = new EventObject(this); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == TimeEventListener.class) ((TimeEventListener) listeners[i+1]).timeChanged(timeEvent); float time = getCurrentTime(); if (time == lastCoarseTime) return; lastCoarseTime = time; for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == CoarseTimeEventListener.class) ((TimeEventListener) listeners[i+1]).timeChanged(timeEvent); } public void addReorderEventListener(ReorderEventListener l) { listenerList.add(ReorderEventListener.class, l); } public void removeReorderEventListener(ReorderEventListener l) { listenerList.remove(ReorderEventListener.class, l); } protected void fireReorderStarted(EventModel leader, EventModel target) { ReorderEvent reorderEvent = new ReorderEvent(leader, target, ReorderEvent.START); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderStarted(reorderEvent); } protected void fireReorderInfeasible(EventModel leader, EventModel target) { ReorderEvent reorderEvent = new ReorderEvent(leader, target, ReorderEvent.START_INFEASIBLE); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderStarted(reorderEvent); } protected void fireReorderCanceled(EventModel leader, EventModel target) { ReorderEvent reorderEvent = new ReorderEvent(leader, target, ReorderEvent.END_CANCEL); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderEnded(reorderEvent); } protected void fireReorderCommitted(EventModel leader, EventModel target) { ReorderEvent reorderEvent = new ReorderEvent(leader, target, ReorderEvent.END_COMMIT); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderEnded(reorderEvent); } protected void fireReorderUpdating(EventModel leader, EventModel target, float progress) { ReorderEvent reorderEvent = new ReorderEvent(leader, target, ReorderEvent.PROGRESS, progress); Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) if (listeners[i] == ReorderEventListener.class) ((ReorderEventListener) listeners[i+1]).reorderUpdating(reorderEvent); } DefaultEventModel movingLeader; DefaultEventModel reorderTarget; float totalTime; float lastDelta; float getReorderingAscention(DefaultEventModel e) { if (movingLeader == null || reorderTarget == null) return 0.0f; if (movingLeader.group.events.contains(e)) return (float) (Math.sin(lastDelta / totalTime * Math.PI) / 2.0); if (reorderTarget.group.events.contains(e)) return (float) (-Math.sin(lastDelta / totalTime * Math.PI) / 2.0); return 0.0f; } float getReorderingDelta(DefaultEventModel e) { if (movingLeader == null || reorderTarget == null) return 0.0f; EventGroup m = movingLeader.group, r = reorderTarget.group; float ratio = m.getTimeLength() / r.getTimeLength(); if (m.events.contains(e)) return lastDelta; if (r.events.contains(e)) return -lastDelta * ratio; return 0.0f; } boolean startOrUpdateReordering(EventGroup group, float delta) { if (movingLeader == null) return false; DefaultEventModel target = group.getLeader(); if (!target.isAllowedToReorderWith(movingLeader)) return false; if (reorderTarget != null && reorderTarget != target) stopReordering(); if (reorderTarget != target) { reorderTarget = target; totalTime = reorderTarget.group.getTimeLength(); fireReorderStarted(movingLeader, reorderTarget); } else { fireReorderUpdating(movingLeader, reorderTarget, delta); } if (delta > totalTime) delta = totalTime; if (delta < -totalTime) delta = -totalTime; lastDelta = delta; return true; } void stopReordering() { if (movingLeader == null || reorderTarget == null) return; fireReorderCanceled(movingLeader, reorderTarget); reorderTarget = null; } void startMoving(DefaultEventModel leader) { if (movingLeader != null) stopMoving(); movingLeader = leader; } void stopMoving() { if (reorderTarget != null) stopReordering(); if (movingLeader != null) { movingLeader = null; } } class DefaultEventModel implements EventModel { static final float MAX_NEAR_DIST = 1f; int process; EventType type; float time; float delta; EventGroup group; boolean rollover; boolean pressed; DefaultEventModel(int process, EventType type, float time) { if (type == null) throw null; if (process < 0 || time < 0.0f) throw new IllegalArgumentException(); this.process = process; this.type = type; this.time = time; } public boolean isAllowedToReorderWith(DefaultEventModel otherLeader) { if (type instanceof TerminateEventType || type instanceof DecideEventType) return false; if (otherLeader.type instanceof TerminateEventType || otherLeader.type instanceof DecideEventType) return false; return true; } public DefaultExecutionModel getParent() { return DefaultExecutionModel.this; } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public int getProcessIndex() { return process; } public EventType getEventType() { return type; } public float getTime() { return time + delta + getReorderingDelta(this); } public float getTimeWithoutDelta() { return time; } public float getAscention() { return getReorderingAscention(this); } public boolean isLeader() { if (group != null) return group.getLeader() == this; return (type instanceof ReceiveEventType) || (type instanceof DecideEventType) || (type instanceof TerminateEventType); } public void setTime(float time) { this.time = time; this.delta = 0.0f; adjustCurrentTime(); fireStateChanged(); } public void setDelta(float delta) { this.delta = delta; validateGroupConstraints(); if (group != null) group.setDelta(this.delta); else setDeltaByGroup(this.delta); } void setDeltaByGroup(float delta) { this.delta = delta; fireStateChanged(); } public void validate() { validateMessageConstraints(); if (group != null) group.setDelta(this.delta); else setDeltaByGroup(this.delta); if (group != null) group.validate(); else validateByGroup(); } void validateByGroup() { time = (float) Math.round(time + delta); delta = 0.0f; adjustCurrentTime(); fireStateChanged(); } void validateMessageConstraints() { Iterable<DefaultEventModel> events = (group != null) ? group.events : Collections.singletonList(this); for (DefaultEventModel e : events) { for (DefaultMessageModel m : messages) { DefaultEventModel leader, trailer; if (m.to == e) { leader = m.from; trailer = e; if (trailer.time + delta < leader.time) delta = leader.time - trailer.time; } else if(m.from == e) { leader = e; trailer = m.to; if (leader.time + delta > trailer.time) delta = trailer.time - leader.time; } else continue; } } } void validateGroupConstraints() { DefaultEventModel leader = this, trailer = this; if (group != null) leader = group.getLeader(); if (group != null) trailer = group.getTrailer(); if (leader.time + delta < 0.0f) delta = -leader.time; boolean stopReorder = true; EventGroup prev = findPreviousGroup(this); if (prev != null) { float d = prev.getTrailer().time + MAX_NEAR_DIST; if (leader.time + delta < d) { if (startOrUpdateReordering(prev, leader.time + delta - prev.getTrailer().time - 1.0f)) { delta = d - leader.time; stopReorder = false; } else { delta = d - leader.time; } } } EventGroup next = findNextGroup(this); if (next != null) { float d = next.getLeader().time - MAX_NEAR_DIST; if (trailer.time + delta > d) { if (startOrUpdateReordering(next, trailer.time + delta - next.getLeader().time + 1.0f)) { delta = d - trailer.time; stopReorder = false; } else { delta = d - trailer.time; } } } if (stopReorder) stopReordering(); } public boolean isRollover() { return rollover && movingLeader == null; } public boolean isPressed() { return pressed; } public void setRollover(boolean b) { if (rollover != b) { rollover = b; fireStateChanged(); } } public void setPressed(boolean b) { if (pressed != b) { pressed = b; if (b) startMoving(this); else stopMoving(); fireStateChanged(); } } boolean overlaps(DefaultEventModel e) { return process == e.process && time == e.time; } public String toString() { return "DefaultEvent@" + process + "[" + type + "]-" + time; } } class EventGroup { int process; ArrayList<DefaultEventModel> events = new ArrayList<>(); EventGroup(DefaultEventModel e) { process = e.process; add(e); steal(findPreviousGroup(e)); } void add(DefaultEventModel e) { if (e.group != null) e.group.events.remove(e); e.group = this; events.add(e); } float getTimeLength() { return getTrailer().time - getLeader().time + 1.0f; } DefaultEventModel getLeader() { DefaultEventModel min = events.get(0); for (DefaultEventModel e : events) if (e.time < min.time) min = e; return min; } DefaultEventModel getTrailer() { DefaultEventModel max = events.get(0); for (DefaultEventModel e : events) if (e.time > max.time) max = e; return max; } void setDelta(float delta) { for (DefaultEventModel e : events) e.setDeltaByGroup(delta); } void validate() { for (DefaultEventModel e : events) e.validateByGroup(); } private void steal(EventGroup o) { if (o == null) return; DefaultEventModel l = getLeader(); for (DefaultEventModel e : o.events) if (e.time > l.time) add(e); } } class DefaultMessageModel implements MessageModel { DefaultEventModel from; DefaultEventModel to; DefaultMessageModel(DefaultEventModel from, DefaultEventModel to) { if (from.getParent() != DefaultExecutionModel.this || to.getParent() != DefaultExecutionModel.this || !(from.type instanceof SendEventType) || !(to.type instanceof ReceiveEventType) || from.process == to.process) throw new IllegalArgumentException(); this.from = from; this.to = to; } public DefaultExecutionModel getParent() { return DefaultExecutionModel.this; } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public DefaultEventModel getFrom() { return from; } public DefaultEventModel getTo() { return to; } public boolean isConflicting() { return to.getTime() < from.getTime(); } } class DefaultPendingMessageModel implements PendingMessageModel { DefaultEventModel from; int to; DefaultPendingMessageModel(DefaultEventModel from, int to) { if (from.getParent() != DefaultExecutionModel.this || !(from.type instanceof SendEventType) || to < 0) throw new IllegalArgumentException(); this.from = from; this.to = to; } public EventModel getFrom() { return from; } public int getTo() { return to; } public ExecutionModel getParent() { return DefaultExecutionModel.this; } } public DefaultEventModel createEvent(int process, EventType type, float time) { return new DefaultEventModel(process, type, time); } public DefaultMessageModel createMessage(EventModel from, EventModel to) { return new DefaultMessageModel((DefaultEventModel) from, (DefaultEventModel) to); } public PendingMessageModel createPendingMessage(EventModel from, int to) { return new DefaultPendingMessageModel((DefaultEventModel) from, to); } private ArrayList<String> processNames = new ArrayList<>(); public void setProcessCount(int size) { int n = processNames.size(); for (int i = n; i < size; i++) processNames.add("P" + i); n = processNames.size(); for (int i = size; i < n; i++) processNames.remove(size); fireStateChanged(); } public int getProcessCount() { return processNames.size(); } public void setProcessName(int index, String p) { if (p.length() == 0) throw new IllegalArgumentException(); processNames.set(index, p); fireStateChanged(); } public void setProcessName(String[] ps) { processNames.clear(); for (String p : ps) { if (p.length() == 0) throw new IllegalArgumentException(); processNames.add(p); } adjustCurrentTime(); fireStateChanged(); } public String getProcessName(int index) { return processNames.get(index); } public String[] getProcessName() { return processNames.toArray(new String[processNames.size()]); } public float getProcessMaxTime(int index) { float result = Float.MAX_VALUE; for (DefaultEventModel event : events) { if (event.process != index) continue; if (event.type instanceof ExecutionModel.DecideEventType || event.type instanceof ExecutionModel.TerminateEventType) { float time = event.getTime(); if (time < result) result = time; } } return result; } public float getProcessLastTime(int index) { float result = 0.0f; for (DefaultEventModel event : events) { if (event.process != index) continue; float time = event.getTime(); if (time > result) result = time; } return result + 1.0f; // compute end time } public float getProcessLastTimeWithoutDelta(int index) { float result = 0.0f; for (DefaultEventModel event : events) { if (event.process != index) continue; float time = event.getTimeWithoutDelta(); if (time > result) result = time; } return result + 1.0f; // compute end time } private float tempMaxTime = 0.0f; public void setTemporaryMaxTime(float maxTime) { tempMaxTime = maxTime; } public void clearTemporaryMaxTime() { tempMaxTime = 0.0f; } public float getTemporaryMaxTime() { return tempMaxTime; } public float getMaxLastTime() { float result = 0.0f; for (int i = 0, size = processNames.size(); i < size; i++) { float time = getProcessLastTime(i); if (time > result) result = time; } return result; } public float getMaxLastTimeWithoutDelta() { float result = 0.0f; for (int i = 0, size = processNames.size(); i < size; i++) { float time = getProcessLastTimeWithoutDelta(i); if (time > result) result = time; } return result; } private float currentTime; private float delta; private void adjustCurrentTime() { float maxTime = getMaxLastTime(); if (currentTime > maxTime) { currentTime = maxTime; fireTimeChanged(); } } public void setCurrentTime(float time) { if (time < 0.0f) time = 0.0f; currentTime = Math.round(time); delta = 0.0f; float maxTime = getMaxLastTime(); if (currentTime > maxTime) { currentTime = maxTime; } lastCoarseTime = Float.NaN; // Force event fireTimeChanged(); } public void setCurrentTimeDelta(float delta) { this.delta = delta; fireTimeChanged(); } public float getCurrentTime() { float result = currentTime + delta; float maxTime = getMaxLastTime(); if (result > maxTime) { result = maxTime; } if (result < 0.0f) result = 0.0f; return result; } public float getCurrentTimeWithoutDelta() { return currentTime; } public void validateTime() { setCurrentTime(getCurrentTime()); } public int addProcess(String p) { if (p.length() == 0) throw new IllegalArgumentException(); int n = processNames.size(); processNames.add(p); fireStateChanged(); return n; } private ArrayList<DefaultEventModel> events = new ArrayList<>(); private ArrayList<EventGroup> eventGroups = new ArrayList<>(); public int getEventCount() { return events.size(); } public void setEvent(int index, EventModel e) { addEvent0(index, e); fireStateChanged(); } public void setEvent(EventModel[] es) { events.clear(); for (EventModel e : es) addEvent0(-1, e); adjustCurrentTime(); fireStateChanged(); } public EventModel getEvent(int index) { return events.get(index); } public EventModel[] getEvent() { return events.toArray(new EventModel[events.size()]); } public void addEvent(EventModel e) { addEvent0(-1, e); fireStateChanged(); } public boolean removeEvent(EventModel e) { if (e == null) throw null; DefaultEventModel de = (DefaultEventModel) e; if (de.getParent() != this) throw new IllegalArgumentException(); boolean result = false; for (int i = 0, size = events.size(); i < size; i++) { if (events.get(i) == e) { events.remove(i); result = true; break; } } if (result) { clearEventGroups(); updateEventGroups(); fireStateChanged(); } return result; } private void addEvent0(int index, EventModel e) { if (e == null) throw null; DefaultEventModel de = (DefaultEventModel) e; if (de.getParent() != this) throw new IllegalArgumentException(); EventModel old = index < 0 ? null : events.get(index); for (DefaultEventModel f : events) { if (f == old) continue; if (f.overlaps(de)) throw new IllegalArgumentException(); } if (index < 0) events.add(de); else events.set(index, de); updateEventGroups(); } EventGroup findPreviousGroup(DefaultEventModel e) { float maxTime = -Float.MAX_VALUE; EventGroup max = null; for (EventGroup g : eventGroups) { if (g == e.group) continue; if (g.process != e.process) continue; DefaultEventModel l = g.getLeader(); if (l.time >= e.time) continue; if (maxTime < l.time) { maxTime = l.time; max = g; } } return max; } EventGroup findNextGroup(DefaultEventModel e) { float minTime = Float.MAX_VALUE; EventGroup min = null; for (EventGroup g : eventGroups) { if (g == e.group) continue; if (g.process != e.process) continue; DefaultEventModel l = g.getLeader(); if (l.time <= e.time) continue; if (minTime > l.time) { minTime = l.time; min = g; } } return min; } private void clearEventGroups() { eventGroups.clear(); for (DefaultEventModel e : events) { e.group = null; } } private void updateEventGroups() { for (DefaultEventModel e : events) { if (e.group != null) continue; EventGroup prev; if (e.isLeader() || (prev = findPreviousGroup(e)) == null) eventGroups.add(new EventGroup(e)); else prev.add(e); } } private ArrayList<DefaultMessageModel> messages = new ArrayList<>(); private ArrayList<DefaultPendingMessageModel> pendingMessages = new ArrayList<>(); public int getMessageCount() { return messages.size(); } public void setMessage(int index, MessageModel m) { addMessage0(index, m); fireStateChanged(); } public void setMessage(MessageModel[] ms) { messages.clear(); for (MessageModel m : ms) addMessage0(-1, m); fireStateChanged(); } public MessageModel getMessage(int index) { return messages.get(index); } public MessageModel[] getMessage() { return messages.toArray(new MessageModel[messages.size()]); } public void addMessage(MessageModel m) { addMessage0(-1, m); fireStateChanged(); } public boolean removeMessage(MessageModel m) { if (m == null) throw null; DefaultMessageModel dm = (DefaultMessageModel) m; if (dm.getParent() != this) throw new IllegalArgumentException(); boolean result = false; for (int i = 0, size = messages.size(); i < size; i++) { if (messages.get(i) == m) { messages.remove(i); result = true; break; } } if (result) fireStateChanged(); return result; } private void addMessage0(int index, MessageModel m) { if (m == null) throw null; DefaultMessageModel dm = (DefaultMessageModel) m; if (dm.getParent() != this) throw new IllegalArgumentException(); DefaultMessageModel old = index < 0 ? null : messages.get(index); for (DefaultMessageModel k : messages) { if (k == old) continue; if (k.from.equals(dm.from) && k.to.equals(dm.to)) throw new IllegalArgumentException(); } if (index < 0) messages.add(dm); else messages.set(index, dm); } public int getPendingMessageCount() { return pendingMessages.size(); } public void setPendingMessage(int index, PendingMessageModel m) { addPendingMessage0(index, m); fireStateChanged(); } public void setPendingMessage(PendingMessageModel[] ms) { pendingMessages.clear(); for (PendingMessageModel m : ms) addPendingMessage0(-1, m); fireStateChanged(); } public PendingMessageModel getPendingMessage(int index) { return pendingMessages.get(index); } public PendingMessageModel[] getPendingMessage() { return pendingMessages.toArray(new PendingMessageModel[pendingMessages.size()]); } public void addPendingMessage(PendingMessageModel m) { addPendingMessage0(-1, m); fireStateChanged(); } public boolean removePendingMessage(PendingMessageModel m) { if (m == null) throw null; DefaultPendingMessageModel dm = (DefaultPendingMessageModel) m; if (dm.getParent() != this) throw new IllegalArgumentException(); boolean result = false; for (int i = 0, size = pendingMessages.size(); i < size; i++) { if (pendingMessages.get(i) == m) { pendingMessages.remove(i); result = true; break; } } if (result) fireStateChanged(); return result; } private void addPendingMessage0(int index, PendingMessageModel m) { if (m == null) throw null; DefaultPendingMessageModel dm = (DefaultPendingMessageModel) m; if (dm.getParent() != this) throw new IllegalArgumentException(); DefaultPendingMessageModel old = index < 0 ? null : pendingMessages.get(index); for (DefaultPendingMessageModel k : pendingMessages) { if (k == old) continue; if (k.from.equals(dm.from) && k.to == dm.to) throw new IllegalArgumentException(); } if (index < 0) pendingMessages.add(dm); else pendingMessages.set(index, dm); } public EventModel[] getValidEvent() { ArrayList<EventModel> result = new ArrayList<>(); for (int i = 0, n = processNames.size(); i < n; i++) { for (DefaultEventModel event : events) if (event.process == i) result.add(event); } return result.toArray(new EventModel[result.size()]); } public MessageModel[] getValidMessage() { ArrayList<MessageModel> result = new ArrayList<>(); int n = processNames.size(); for (DefaultMessageModel m : messages) { if (events.contains(m.from) && m.from.process < n && events.contains(m.to) && m.to.process < n) result.add(m); } return result.toArray(new MessageModel[result.size()]); } public PendingMessageModel[] getValidPendingMessage() { ArrayList<PendingMessageModel> result = new ArrayList<>(); int n = processNames.size(); for (DefaultPendingMessageModel m : pendingMessages) { if (events.contains(m.from) && m.from.process < n && m.to < n) result.add(m); } return result.toArray(new PendingMessageModel[result.size()]); } public EventModel[] getHappenedLastEvent() { ArrayList<EventModel> happenedEvents = new ArrayList<>(); for (int i = 0, n = processNames.size(); i < n; i++) { for (DefaultEventModel event : events) if (event.process == i && event.getTimeWithoutDelta() < getCurrentTimeWithoutDelta()) happenedEvents.add(event); } ArrayList<EventModel> result = new ArrayList<>(); for (EventModel happened : happenedEvents) { EventModel foundAfter = null; EventModel foundBefore = null; for (EventModel other : result) { if (other.getProcessIndex() == happened.getProcessIndex() && happened.getTimeWithoutDelta() > other.getTimeWithoutDelta()) { foundBefore = other; } if (other.getProcessIndex() == happened.getProcessIndex() && happened.getTimeWithoutDelta() <= other.getTimeWithoutDelta()) { foundAfter = other; } } if (foundBefore != null) result.remove(foundBefore); if (foundAfter != null) continue; result.add(happened); } return result.toArray(new EventModel[result.size()]); } public Object[] getHappenedTransitMessage() { ArrayList<Object> result = new ArrayList<>(); int n = processNames.size(); for (DefaultMessageModel m : messages) { if (events.contains(m.from) && m.from.process < n && events.contains(m.to) && m.to.process < n && m.from.getTimeWithoutDelta() < getCurrentTimeWithoutDelta() && getCurrentTimeWithoutDelta() <= m.to.getTimeWithoutDelta()) result.add(m); } for (DefaultPendingMessageModel m : pendingMessages) { if (events.contains(m.from) && m.from.process < n && m.to < n && m.from.getTimeWithoutDelta() < getCurrentTimeWithoutDelta()) result.add(m); } return result.toArray(new Object[result.size()]); } public void clear() { events.clear(); eventGroups.clear(); messages.clear(); pendingMessages.clear(); processNames.clear(); stopMoving(); adjustCurrentTime(); fireStateChanged(); } public void clearEventsAndMessages() { events.clear(); eventGroups.clear(); messages.clear(); pendingMessages.clear(); adjustCurrentTime(); fireStateChanged(); } private int editMode = MODE_SELECTION; public void setEditMode(int mode) { if (mode != MODE_SELECTION && mode != MODE_SWAP) throw new IllegalArgumentException(); int old = editMode; editMode = mode; if (mode != old) { fireStateChanged(); } } public int getEditMode() { return editMode; } }
30,591
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ExecutionModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/ExecutionModel.java
package com.aexiz.daviz.ui.swing; import java.io.Serializable; import java.util.EventListener; import java.util.EventObject; import javax.swing.event.ChangeListener; import com.aexiz.daviz.ui.swing.JTimeline.JEvent; public interface ExecutionModel { static abstract class EventType implements Serializable { private static final long serialVersionUID = -7469784089240414551L; EventType() {} public abstract String toString(); } static class SendEventType extends EventType { private static final long serialVersionUID = 3989437777413291201L; SendEventType() {} public String toString() { return "Send"; } } static class ReceiveEventType extends EventType { private static final long serialVersionUID = -8024401864871586063L; ReceiveEventType() {} public String toString() { return "Receive"; } } static class InternalEventType extends EventType { private static final long serialVersionUID = -1467758305981819533L; InternalEventType() {} public String toString() { return "Internal"; } } static class TerminateEventType extends EventType { private static final long serialVersionUID = -2241813359102096812L; TerminateEventType() {} public String toString() { return "Terminate"; } } static class DecideEventType extends EventType { private static final long serialVersionUID = -8806882625351510880L; DecideEventType() {} public String toString() { return "Decide"; } } static final SendEventType SEND_TYPE = new SendEventType(); static final ReceiveEventType RECEIVE_TYPE = new ReceiveEventType(); static final InternalEventType INTERNAL_TYPE = new InternalEventType(); static final TerminateEventType TERMINATE_TYPE = new TerminateEventType(); static final DecideEventType DECIDE_TYPE = new DecideEventType(); interface EventModel { void addChangeListener(ChangeListener l); void removeChangeListener(ChangeListener l); int getProcessIndex(); EventType getEventType(); float getTime(); float getTimeWithoutDelta(); float getAscention(); void setTime(float time); void setDelta(float time); void validate(); boolean isRollover(); boolean isPressed(); void setRollover(boolean b); void setPressed(boolean b); boolean isLeader(); ExecutionModel getParent(); } interface MessageModel { void addChangeListener(ChangeListener l); void removeChangeListener(ChangeListener l); EventModel getFrom(); EventModel getTo(); boolean isConflicting(); ExecutionModel getParent(); } interface PendingMessageModel { EventModel getFrom(); int getTo(); ExecutionModel getParent(); } interface ReorderEventListener extends EventListener { void reorderStarted(ReorderEvent e); void reorderUpdating(ReorderEvent e); void reorderEnded(ReorderEvent e); } static class ReorderEvent extends EventObject { private static final long serialVersionUID = -5054396395438782856L; public static final int PROGRESS = 0; public static final int START = 1; public static final int START_INFEASIBLE = 2; public static final int END_COMMIT = 3; public static final int END_CANCEL = 4; EventModel leader; EventModel target; int type; float progress; JEvent leaderComponent; JEvent targetComponent; public ReorderEvent(EventModel leader, EventModel target, int type) { this(leader, target, type, 0.0f); } public ReorderEvent(EventModel leader, EventModel target, int type, float progress) { super(leader); if (leader == null || target == null) throw null; if (type < PROGRESS || type > END_CANCEL || progress != progress) throw new IllegalArgumentException(); this.leader = leader; this.target = target; this.type = type; this.progress = progress; } public ReorderEvent(JEvent leader, JEvent target, int type, float progress) { super(leader); this.leaderComponent = leader; this.leader = leader.getModel(); this.targetComponent = target; this.target = target.getModel(); this.type = type; this.progress = progress; } public static ReorderEvent createFromComponent(ReorderEvent event, JTimeline timeline) { return new ReorderEvent( timeline.findEventComponent(event.leader), timeline.findEventComponent(event.target), event.type, event.progress); } public EventModel getLeaderModel() { return leader; } public EventModel getTargetModel() { return target; } public JEvent getLeader() { return leaderComponent; } public JEvent getTarget() { return targetComponent; } public int getType() { return type; } public float getProgress() { return progress; } } interface TimeEventListener extends EventListener { void timeChanged(EventObject e); } interface CoarseTimeEventListener extends TimeEventListener { } void addChangeListener(ChangeListener l); void removeChangeListener(ChangeListener l); void addTimeEventListener(TimeEventListener l); void removeTimeEventListener(TimeEventListener l); void addCoarseTimeEventListener(CoarseTimeEventListener l); void removeCoarseTimeEventListener(CoarseTimeEventListener l); void addReorderEventListener(ReorderEventListener l); void removeReorderEventListener(ReorderEventListener l); EventModel createEvent(int process, EventType type, float time); MessageModel createMessage(EventModel from, EventModel to); PendingMessageModel createPendingMessage(EventModel from, int to); int getProcessCount(); String getProcessName(int index); float getProcessMaxTime(int index); float getProcessLastTime(int index); float getProcessLastTimeWithoutDelta(int index); float getTemporaryMaxTime(); float getMaxLastTime(); float getMaxLastTimeWithoutDelta(); void setCurrentTime(float time); void setCurrentTimeDelta(float delta); float getCurrentTime(); float getCurrentTimeWithoutDelta(); void validateTime(); String[] getProcessName(); int getEventCount(); EventModel getEvent(int index); EventModel[] getEvent(); EventModel[] getValidEvent(); int getMessageCount(); MessageModel getMessage(int index); MessageModel[] getMessage(); MessageModel[] getValidMessage(); int getPendingMessageCount(); PendingMessageModel getPendingMessage(int index); PendingMessageModel[] getPendingMessage(); PendingMessageModel[] getValidPendingMessage(); EventModel[] getHappenedLastEvent(); Object[] getHappenedTransitMessage(); static final int MODE_SELECTION = 0; static final int MODE_SWAP = 1; public void setEditMode(int mode); public int getEditMode(); }
6,988
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JCarousel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JCarousel.java
package com.aexiz.daviz.ui.swing; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import javax.swing.DefaultListModel; import javax.swing.DefaultListSelectionModel; import javax.swing.JComponent; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.aexiz.daviz.ui.swing.plaf.CarouselUI; import com.aexiz.daviz.ui.swing.plaf.basic.BasicCarouselUI; // JList only has HORIZONTAL_FLOW, but we need only horizontal items public class JCarousel extends JComponent { private static final long serialVersionUID = -2476657651802981334L; static final String UICLASSID = "CarouselUI"; static { UIDefaults def = UIManager.getDefaults(); if (def.get(UICLASSID) == null) def.put(UICLASSID, BasicCarouselUI.class.getName()); } private ListModel<?> listModel; private ListSelectionModel listSelectionModel; private CarouselCellRenderer listCellRenderer; protected ListDataListener listDataListener; protected ListSelectionListener listSelectionListener; private transient Handler handler; public JCarousel() { setOpaque(true); setCellRenderer(new DefaultCarouselCellRenderer()); setModel(new DefaultListModel<>()); setSelectionModel(new DefaultListSelectionModel()); updateUI(); } private Color selectionBackground; public void setSelectionBackground(Color color) { Color old = selectionBackground; selectionBackground = color; firePropertyChange("selectionBackground", old, color); repaint(); } public Color getSelectionBackground() { return selectionBackground; } private Color selectionForeground; public void setSelectionForeground(Color color) { Color old = selectionForeground; selectionForeground = color; firePropertyChange("selectionForeground", old, color); repaint(); } public Color getSelectionForeground() { return selectionForeground; } public void addListSelectionListener(ListSelectionListener listener) { listenerList.add(ListSelectionListener.class, listener); } public void removeListSelectionListener(ListSelectionListener listener) { listenerList.remove(ListSelectionListener.class, listener); } protected void fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting) { Object[] listeners = listenerList.getListenerList(); ListSelectionEvent e = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ListSelectionListener.class) { if (e == null) e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting); ((ListSelectionListener) listeners[i+1]).valueChanged(e); } } } public void setModel(ListModel<?> model) { ListModel<?> oldModel = listModel; if (oldModel != null) { oldModel.removeListDataListener(listDataListener); listDataListener = null; } listModel = model; if (model != null) { listDataListener = createListDataListener(); model.addListDataListener(listDataListener); } if (oldModel != model) { firePropertyChange("model", oldModel, model); } } public ListModel<?> getModel() { return listModel; } public void setSelectionModel(ListSelectionModel model) { ListSelectionModel oldModel = listSelectionModel; if (oldModel != null) { oldModel.removeListSelectionListener(listSelectionListener); listSelectionListener = null; } listSelectionModel = model; if (model != null) { listSelectionListener = createListSelectionListener(); model.addListSelectionListener(listSelectionListener); } if (oldModel != model) { firePropertyChange("selectionModel", oldModel, model); } } public ListSelectionModel getSelectionModel() { return listSelectionModel; } public void setSelectedIndex(int index) { ListModel<?> model = getModel(); if (model == null || index >= model.getSize()) { return; } ListSelectionModel selModel = getSelectionModel(); if (selModel == null) return; selModel.setSelectionInterval(index, index); } public int getSelectedIndex() { return getMinSelectionIndex(); } public Object getSelectedValue() { int i = getSelectedIndex(); if (i < 0) return null; ListModel<?> model = getModel(); if (model == null) return null; return model.getElementAt(i); } public int getValueCount() { ListModel<?> model = getModel(); if (model == null) return 0; return model.getSize(); } public Object getValue(int index) { ListModel<?> model = getModel(); if (model == null) return null; return model.getElementAt(index); } public int getAnchorSelectionIndex() { ListSelectionModel model = getSelectionModel(); if (model == null) return -1; return model.getAnchorSelectionIndex(); } public int getLeadSelectionIndex() { ListSelectionModel model = getSelectionModel(); if (model == null) return -1; return model.getLeadSelectionIndex(); } public int getMinSelectionIndex() { ListSelectionModel model = getSelectionModel(); if (model == null) return -1; return model.getMinSelectionIndex(); } public int getMaxSelectionIndex() { ListSelectionModel model = getSelectionModel(); if (model == null) return -1; return model.getMaxSelectionIndex(); } public boolean isSelectedIndex(int index) { ListSelectionModel selModel = getSelectionModel(); if (selModel == null) return false; return selModel.isSelectedIndex(index); } public boolean isSelectionEmpty() { ListSelectionModel model = getSelectionModel(); if (model == null) return true; return model.isSelectionEmpty(); } public void clearSelection() { ListSelectionModel model = getSelectionModel(); if (model == null) return; model.clearSelection(); } public void ensureIndexIsVisible(int index) { Rectangle cellBounds = getCellBounds(index, index); if (cellBounds != null) scrollRectToVisible(cellBounds); } public void setCellRenderer(CarouselCellRenderer renderer) { CarouselCellRenderer old = listCellRenderer; listCellRenderer = renderer; firePropertyChange("cellRenderer", old, renderer); } public CarouselCellRenderer getCellRenderer() { return listCellRenderer; } public void updateUI() { setUI((CarouselUI) UIManager.getUI(this)); CarouselCellRenderer renderer = getCellRenderer(); if (renderer instanceof Component) { SwingUtilities.updateComponentTreeUI((Component) renderer); } } public void setUI(CarouselUI ui) { super.setUI(ui); } public CarouselUI getUI() { return (CarouselUI) ui; } public String getUIClassID() { return UICLASSID; } public Rectangle getCellBounds(int from, int to) { CarouselUI ui = getUI(); return ui != null ? ui.getCellBounds(this, from, to) : null; } public int locationToIndex(Point location) { CarouselUI ui = getUI(); return ui != null ? ui.locationToIndex(this, location) : -1; } public Point indexToLocation(int index) { CarouselUI ui = getUI(); return ui != null ? ui.indexToLocation(this, index) : null; } protected ListDataListener createListDataListener() { return getHandler(); } protected ListSelectionListener createListSelectionListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } class Handler implements ListDataListener, ListSelectionListener { public void valueChanged(ListSelectionEvent e) { revalidate(); repaint(); fireSelectionValueChanged(e.getFirstIndex(), e.getLastIndex(), e.getValueIsAdjusting()); } public void contentsChanged(ListDataEvent e) { listSelectionModel.clearSelection(); // TODO repaint(); } public void intervalAdded(ListDataEvent e) { listSelectionModel.clearSelection(); // TODO repaint(); } public void intervalRemoved(ListDataEvent e) { listSelectionModel.clearSelection(); // TODO repaint(); } } }
8,428
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JKnob.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JKnob.java
package com.aexiz.daviz.ui.swing; import java.awt.Color; import javax.swing.JComponent; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; import javax.swing.plaf.ComponentUI; // Simple button-ish component, used by the Nodes of JGraph and Events of JTimeline // The component still depends on an external UI that renders it. public class JKnob extends JComponent { private static final long serialVersionUID = -2307896553409109184L; JKnob() { } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } // State protected boolean rollover; protected boolean pressed; protected boolean selected; public boolean isRollover() { return rollover; } public boolean isPressed() { return pressed; } public void setRollover(boolean b) { if (rollover != b) { rollover = b; fireStateChanged(); } } public void setPressed(boolean b) { if (pressed != b) { pressed = b; fireStateChanged(); } } public boolean isSelected() { return selected; } public void requestClearSelection() { setSelected(false); } public void requestSingleSelected() { setSelected(true); } public void requestAllSelected() { setSelected(true); } public void setSelected(boolean b) { if (selected != b) { selected = b; fireStateChanged(); } } // Colors private Color rolloverBackground; public void setRolloverBackground(Color color) { Color old = rolloverBackground; rolloverBackground = color; firePropertyChange("rolloverBackground", old, color); repaint(); } public Color getRolloverBackground() { return rolloverBackground; } private Color rolloverForeground; public void setRolloverForeground(Color color) { Color old = rolloverForeground; rolloverForeground = color; firePropertyChange("rolloverForeground", old, color); repaint(); } public Color getRolloverForeground() { return rolloverForeground; } private Color pressedBackground; public void setPressedBackground(Color color) { Color old = pressedBackground; pressedBackground = color; firePropertyChange("pressedBackground", old, color); repaint(); } public Color getPressedBackground() { return pressedBackground; } private Color pressedForeground; public void setPressedForeground(Color color) { Color old = pressedForeground; pressedForeground = color; firePropertyChange("pressedForeground", old, color); repaint(); } public Color getPressedForeground() { return pressedForeground; } private Color selectionBackground; public void setSelectionBackground(Color color) { Color old = selectionBackground; selectionBackground = color; firePropertyChange("selectionBackground", old, color); repaint(); } public Color getSelectionBackground() { return selectionBackground; } private Color selectionForeground; public void setSelectionForeground(Color color) { Color old = selectionForeground; selectionForeground = color; firePropertyChange("selectionForeground", old, color); repaint(); } public Color getSelectionForeground() { return selectionForeground; } private Color selectionRolloverBackground; public void setSelectionRolloverBackground(Color color) { Color old = selectionRolloverBackground; selectionRolloverBackground = color; firePropertyChange("selectionRolloverBackground", old, color); repaint(); } public Color getSelectionRolloverBackground() { if (selectionRolloverBackground == null && selectionBackground != null && rolloverBackground != null) return blend(selectionBackground, rolloverBackground); return selectionRolloverBackground; } private Color selectionRolloverForeground; public void setSelectionRolloverForeground(Color color) { Color old = selectionRolloverForeground; selectionRolloverForeground = color; firePropertyChange("selectionRolloverForeground", old, color); repaint(); } public Color getSelectionRolloverForeground() { if (selectionRolloverForeground == null && selectionForeground != null && rolloverForeground != null) return blend(selectionForeground, rolloverForeground); return selectionRolloverForeground; } private Color selectionPressedBackground; public void setSelectionPressedBackground(Color color) { Color old = selectionPressedBackground; selectionPressedBackground = color; firePropertyChange("selectionPressedBackground", old, color); repaint(); } public Color getSelectionPressedBackground() { if (selectionPressedBackground == null && selectionBackground != null && pressedBackground != null) return blend(selectionBackground, pressedBackground); return selectionPressedBackground; } private Color selectionPressedForeground; public void setSelectionPressedForeground(Color color) { Color old = selectionPressedForeground; selectionPressedForeground = color; firePropertyChange("selectionPressedForeground", old, color); repaint(); } public Color getSelectionPressedForeground() { if (selectionPressedForeground == null && selectionForeground != null && pressedForeground != null) return blend(selectionForeground, pressedForeground); return selectionPressedForeground; } public void setUI(ComponentUI ui) { super.setUI(ui); } public ComponentUI getUI() { return ui; } static Color blend(Color a, Color b) { int red = (int) (a.getRed() * 0.5f + b.getRed() * 0.5f); int green = (int) (a.getGreen() * 0.5f + b.getGreen() * 0.5f); int blue = (int) (a.getBlue() * 0.5f + b.getBlue() * 0.5f); return new Color(red, green, blue); } }
6,497
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JGraph.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JGraph.java
package com.aexiz.daviz.ui.swing; import java.awt.Color; import java.awt.Component; import java.io.Serializable; import java.util.EventObject; import javax.swing.JComponent; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.aexiz.daviz.ui.swing.GraphModel.EdgeModel; import com.aexiz.daviz.ui.swing.GraphModel.ModeEventListener; import com.aexiz.daviz.ui.swing.GraphModel.NodeModel; import com.aexiz.daviz.ui.swing.plaf.GraphUI; import com.aexiz.daviz.ui.swing.plaf.basic.BasicGraphUI; /** * A graph component that visualizes and allows user-interactive editing of graph structures. */ public class JGraph extends JComponent { private static final long serialVersionUID = 2243441260190095826L; public static final String CLIENT_PROPERTY_TEMPORARY = "temporary"; public static final int MODE_SELECTION = GraphModel.MODE_SELECTION; public static final int MODE_EDGE = GraphModel.MODE_EDGE; public static final int MODE_VERTEX = GraphModel.MODE_VERTEX; public static final int MODE_ERASE = GraphModel.MODE_ERASE; static final String UICLASSID = "GraphUI"; protected GraphModel model; protected ObjectSelectionModel selectionModel; private Handler handler; protected ChangeListener changeListener; protected transient ChangeEvent changeEvent; protected transient EventObject modeEvent; static { UIDefaults def = UIManager.getDefaults(); if (def.get(UICLASSID) == null) def.put(UICLASSID, BasicGraphUI.class.getName()); } public JGraph() { setOpaque(true); setModel(new DefaultGraphModel()); setSelectionModel(new DefaultObjectSelectionModel()); updateUI(); } public static class JNode extends JKnob { private static final long serialVersionUID = -3614183062524808053L; private NodeModel model; private ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { fireStateChanged(); revalidate(); getParent().repaint(); } }; protected JNode() { } public void setModel(NodeModel model) { NodeModel oldModel = this.model; if (oldModel != null) { oldModel.removeChangeListener(changeListener); } this.model = model; if (model != null) { model.addChangeListener(changeListener); } firePropertyChange("model", oldModel, model); } public NodeModel getModel() { return model; } public JGraph getGraph() { Component c = getParent(); if (c instanceof JGraph) return (JGraph) c; return null; } public boolean isPressed() { if (model == null) return false; return model.isPressed(); } public String getLabel() { if (model == null) return "?"; return model.getLabel(); } public void remove() { if (model == null) return; model.remove(); } public void setPressed(boolean b) { if (model == null) return; model.setPressed(b); } public void setDeltaX(float dx) { if (model == null) return; model.setDeltaX(dx); } public void setDeltaY(float dy) { if (model == null) return; model.setDeltaY(dy); } public boolean isSelected() { JGraph g = getGraph(); if (g == null) return false; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel == null) return false; return selModel.isSelected(model); } public void setSelected(boolean sel) { if (isSelected() == sel) return; JGraph g = getGraph(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { if (sel) { selModel.addSelection(model); } else { selModel.removeSelection(model); } } } public void requestSingleSelected() { JGraph g = getGraph(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { selModel.clearSelection(); selModel.addSelection(model); } } public void requestAllSelected() { JGraph graph = getGraph(); if (graph != null) { graph.selectAllNodes(); } } public void requestClearSelection() { JGraph graph = getGraph(); if (graph != null) { graph.clearSelection(); } } private float oldx, oldy; public void startMoving() { if (model != null) { oldx = model.getX(); oldy = model.getY(); } else { oldx = 0.0f; oldy = 0.0f; } } public boolean commitMoving() { if (model == null) return false; model.validate(); if (model.isOverlapping()) { model.setX(oldx); model.setY(oldy); return false; } else { return true; } } } public static class JEdge extends JKnob { private static final long serialVersionUID = -3116847790422523979L; private EdgeModel model; private ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { fireStateChanged(); revalidate(); } }; protected JEdge() { } public void setModel(EdgeModel model) { EdgeModel oldModel = this.model; if (oldModel != null) { oldModel.removeChangeListener(changeListener); } this.model = model; if (model != null) { model.addChangeListener(changeListener); } } public EdgeModel getModel() { return model; } public JGraph getGraph() { Component c = getParent(); if (c instanceof JGraph) return (JGraph) c; return null; } public JNode getFrom() { JGraph g = getGraph(); if (g != null) return g.findNodeComponent(model.getFrom()); return null; } public JNode getTo() { JGraph g = getGraph(); if (g != null) return g.findNodeComponent(model.getTo()); return null; } public void remove() { if (model == null) return; model.remove(); } public boolean isDirected() { if (model != null) return model.isDirected(); return false; } public boolean isSelected() { JGraph g = getGraph(); if (g == null) return false; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { return selModel.isSelected(model); } else { return false; } } public void setSelected(boolean sel) { if (isSelected() == sel) return; JGraph g = getGraph(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { if (sel) { selModel.addSelection(model); } else { selModel.removeSelection(model); } } } public void requestSingleSelected() { JGraph g = getGraph(); if (g == null) return; ObjectSelectionModel selModel = g.getSelectionModel(); if (selModel != null) { selModel.clearSelection(); selModel.addSelection(model); } } public void requestAllSelected() { JGraph graph = getGraph(); if (graph != null) { graph.selectAllEdges(); } } public void requestClearSelection() { JGraph graph = getGraph(); if (graph != null) { graph.clearSelection(); } } } public void setModel(GraphModel newModel) { GraphModel oldModel = getModel(); if (oldModel != null) { oldModel.removeChangeListener(changeListener); changeListener = null; } model = newModel; if (newModel != null) { changeListener = createChangeListener(); newModel.addChangeListener(changeListener); } firePropertyChange("model", oldModel, newModel); if (newModel != oldModel) { updateSubComponents(); } } public GraphModel getModel() { return model; } public void setSelectionModel(ObjectSelectionModel selModel) { ObjectSelectionModel oldModel = getSelectionModel(); if (oldModel != null) { oldModel.removeChangeListener(changeListener); changeListener = null; } selectionModel = selModel; if (selModel != null) { changeListener = createChangeListener(); selModel.addChangeListener(changeListener); } firePropertyChange("selectionModel", oldModel, selModel); if (selModel != oldModel) { repaint(); } } public ObjectSelectionModel getSelectionModel() { return selectionModel; } public void clearSelection() { if (selectionModel != null) selectionModel.clearSelection(); } public void selectAllEdges() { if (selectionModel != null && model != null) { for (EdgeModel edge : model.getValidEdge()) { selectionModel.addSelection(edge); } } } public void selectAllNodes() { if (selectionModel != null && model != null) { for (NodeModel node : model.getValidNode()) { selectionModel.addSelection(node); } } } public void selectAll() { if (selectionModel != null && model != null) { selectionModel.clearSelection(); selectAllNodes(); selectAllEdges(); } } public void removeSelection() { if (selectionModel != null && model != null) { for (Object sel : selectionModel.getSelection()) { if (sel instanceof EdgeModel) { EdgeModel edge = (EdgeModel) sel; if (edge.getParent() == model) { edge.remove(); } } if (sel instanceof NodeModel) { NodeModel node = (NodeModel) sel; if (node.getParent() == model) { node.remove(); } } } } } private Color readOnlyBackground; public void setReadOnlyBackground(Color color) { Color old = readOnlyBackground; readOnlyBackground = color; firePropertyChange("readOnlyBackground", old, color); } public Color getReadOnlyBackground() { return readOnlyBackground; } public void setReadOnly(boolean b) { if (model == null) return; model.setReadOnly(b); } public boolean isReadOnly() { if (model == null) return true; return model.isReadOnly(); } public void setEditMode(int mode) { if (model == null) return; model.setEditMode(mode); } public void switchToSelectionMode() { if (model == null) return; model.setEditMode(MODE_SELECTION); } public void switchToVertexMode() { if (model == null) return; model.setEditMode(MODE_VERTEX); } public void switchToEdgeMode() { if (model == null) return; model.setEditMode(MODE_EDGE); } public void switchToEraseMode() { if (model == null) return; model.setEditMode(MODE_ERASE); } public int getEditMode() { if (model == null) return MODE_SELECTION; else return model.getEditMode(); } public JNode startCreatingNode(float x, float y) { if (model == null) return null; NodeModel node = model.createNode(x, y); model.setTemporaryNode(node); NodeModel result = model.getTemporaryNode(); updateSubComponents(); revalidate(); repaint(); return findNodeComponent(result); } public boolean commitCreatingNode(JNode node) { boolean result = commitCreatingNodeImpl(node); if (!result) { JStatus.setTemporaryStatus(this, "A new node cannot overlap an existing one."); } return result; } private boolean commitCreatingNodeImpl(JNode node) { if (model == null) return false; if (model.getTemporaryNode() != node.getModel()) return false; boolean result; if (!node.commitMoving()) { result = false; } else { result = true; } if (result) { model.addNode(node.getModel()); } model.clearTemporaryNode(); updateSubComponents(); revalidate(); repaint(); return result; } public JNode findNearestNode(float x, float y) { if (model == null) return null; NodeModel node = model.findNearestValidNode(x, y); if (node == null) return null; return findNodeComponent(node); } public JNode startCreatingEdgeNode(float x, float y) { JNode node = startCreatingNode(x, y); JNode result; if (!commitCreatingNodeImpl(node)) { result = findNearestNode(x, y); } else { result = node; } return result; } public JNode startCreatingEdge(JNode from, float x, float y) { if (model == null) return null; NodeModel node = model.createNode(x, y); model.setTemporaryNode(node); EdgeModel edge = model.createEdge(from.getModel(), node); model.setTemporaryEdge(edge); updateSubComponents(); revalidate(); repaint(); return findNodeComponent(model.getTemporaryNode()); } public boolean commitCreatingEdge(JNode to) { if (model == null) return false; if (model.getTemporaryNode() != to.getModel()) return false; EdgeModel edge = model.getTemporaryEdge(); if (edge == null || edge.getTo() != to.getModel()) return false; boolean result; float oldx = to.getModel().getX(); float oldy = to.getModel().getY(); if (!to.commitMoving()) { // Find existing nearest node to connect with NodeModel from = edge.getFrom(); NodeModel node = model.findNearestValidNode(oldx, oldy); if (node == null || node == from) { JStatus.setTemporaryStatus(this, "Loops are not allowed."); result = false; } else { edge = model.createEdge(from, node); result = true; } } else { model.addNode(to.getModel()); result = true; } if (result) { model.addEdge(edge); } model.clearTemporaryNode(); model.clearTemporaryEdge(); updateSubComponents(); revalidate(); repaint(); return result; } private boolean showGrid = false; public void setShowGrid(boolean show) { boolean old = showGrid; showGrid = show; if (old != show) { firePropertyChange("showGrid", old, show); } } public boolean getShowGrid() { return showGrid; } private boolean erasing; public void setErasing(boolean erasing) { boolean old = this.erasing; this.erasing = erasing; if (old != erasing) { firePropertyChange("erasing", old, erasing); } } public boolean isErasing() { return erasing; } public void zoomIn() { if (model == null) return; float zoom = model.getZoomLevel(); if (zoom > 4.5f) { // Too deep return; } zoom *= 1.25f; zoom = Math.round(zoom * 100f) / 100f; model.setZoomLevel(zoom); } public void zoomOut() { if (model == null) return; float zoom = model.getZoomLevel(); if (zoom < 0.2f) { // Too deep return; } zoom /= 1.25f; zoom = Math.round(zoom * 100f) / 100f; model.setZoomLevel(zoom); } public float getZoomLevel() { if (model == null) return 1.0f; return model.getZoomLevel(); } public void updateUI() { setUI((GraphUI) UIManager.getUI(this)); } public void setUI(GraphUI ui) { removeSubComponents(); super.setUI(ui); updateSubComponents(); } public GraphUI getUI() { return (GraphUI) ui; } public String getUIClassID() { return UICLASSID; } public boolean isOptimizedDrawingEnabled() { return false; } public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } public ChangeListener[] getChangeListeners() { return listenerList.getListeners(ChangeListener.class); } protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public void addModeEventListener(ModeEventListener l) { listenerList.add(ModeEventListener.class, l); } public void removeModeEventListener(ModeEventListener l) { listenerList.remove(ModeEventListener.class, l); } public ModeEventListener[] getModeEventListeners() { return listenerList.getListeners(ModeEventListener.class); } protected void fireModeChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ModeEventListener.class) { if (modeEvent == null) modeEvent = new EventObject(this); ((ModeEventListener) listeners[i+1]).modeChanged(modeEvent); } } } private void removeSubComponents() { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JNode) { ((JNode) c).setModel(null); remove(i--); n--; } else if (c instanceof JEdge) { ((JEdge) c).setModel(null); remove(i--); n--; } } } private void updateSubComponents() { // We must not just remove all children and then readd them. This interferes with // event handling, e.g. dragging a node and then removing it makes the component very brittle. // 1. Find and remove all components that have models not occurring in the graph model. // 2. Find all node models that do not have a component, and add a new component for them. // 3. Special temporary node handling. // This should result in the same number of components, reusing non-changed models. int n = getComponentCount(); Component[] children = new Component[n]; JNode[] nodes = new JNode[n]; JEdge[] edges = new JEdge[n]; boolean[] remove = new boolean[n]; for (int i = 0; i < n; i++) { children[i] = getComponent(i); if (children[i] instanceof JNode) { nodes[i] = (JNode) children[i]; } else if (children[i] instanceof JEdge) { edges[i] = (JEdge) children[i]; } } GraphModel model = getModel(); NodeModel[] nodeModels = model.getValidNode(); boolean[] nodeMatch = new boolean[nodeModels.length]; boolean nodeTmpMatch = false; EdgeModel[] edgeModels = model.getValidEdge(); boolean[] edgeMatch = new boolean[edgeModels.length]; boolean edgeTmpMatch = false; outer: for (int i = 0; i < n; i++) { if (nodes[i] == null) continue; NodeModel node = nodes[i].getModel(); for (int j = 0; j < nodeModels.length; j++) { if (nodeModels[j] == node) { nodeMatch[j] = true; nodes[i].putClientProperty(CLIENT_PROPERTY_TEMPORARY, false); continue outer; } } if (node == model.getTemporaryNode()) { nodeTmpMatch = true; nodes[i].putClientProperty(CLIENT_PROPERTY_TEMPORARY, true); continue; } nodes[i].setModel(null); remove[i] = true; } outer: for (int i = 0; i < n; i++) { if (edges[i] == null) continue; EdgeModel edge = edges[i].getModel(); for (int j = 0; j < edgeModels.length; j++) { if (edgeModels[j] == edge) { edgeMatch[j] = true; edges[i].putClientProperty(CLIENT_PROPERTY_TEMPORARY, false); continue outer; } } if (edge == model.getTemporaryEdge()) { edgeTmpMatch = true; edges[i].putClientProperty(CLIENT_PROPERTY_TEMPORARY, true); continue; } edges[i].setModel(null); remove[i] = true; } for (int i = 0, j = 0; i < n; i++, j++) { if (remove[i]) remove(j--); } GraphUI ui = getUI(); for (int i = 0; i < nodeModels.length; i++) { if (nodeMatch[i]) continue; JNode c = createNodeComponent(nodeModels[i]); c.putClientProperty(CLIENT_PROPERTY_TEMPORARY, false); if (ui != null) ui.configureNodeComponent(c); add(c, 0); } NodeModel tn = model.getTemporaryNode(); if (tn != null && !nodeTmpMatch) { JNode c = createNodeComponent(tn); c.putClientProperty(CLIENT_PROPERTY_TEMPORARY, true); if (ui != null) ui.configureNodeComponent(c); add(c, 0); } for (int i = 0; i < edgeModels.length; i++) { if (edgeMatch[i]) continue; JEdge c = createEdgeComponent(edgeModels[i]); c.putClientProperty(CLIENT_PROPERTY_TEMPORARY, false); if (ui != null) ui.configureEdgeComponent(c); add(c); } EdgeModel te = model.getTemporaryEdge(); if (te != null && !edgeTmpMatch) { JEdge c = createEdgeComponent(te); c.putClientProperty(CLIENT_PROPERTY_TEMPORARY, true); if (ui != null) ui.configureEdgeComponent(c); add(c); } } public JNode findNodeComponent(NodeModel node) { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JNode) { JNode e = (JNode) c; if (e.getModel() == node) return e; } } return null; } public JEdge findEdgeComponent(EdgeModel edge) { int n = getComponentCount(); for (int i = 0; i < n; i++) { Component c = getComponent(i); if (c instanceof JEdge) { JEdge m = (JEdge) c; if (m.getModel() == edge) return m; } } return null; } protected JNode createNodeComponent(NodeModel node) { JNode result = new JNode(); result.setModel(node); return result; } protected JEdge createEdgeComponent(EdgeModel edge) { JEdge result = new JEdge(); result.setModel(edge); return result; } protected ChangeListener createChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } class Handler implements ChangeListener, Serializable { private static final long serialVersionUID = 8926957207286243301L; public void stateChanged(ChangeEvent e) { if (e.getSource() == model) { updateSubComponents(); revalidate(); repaint(); fireStateChanged(); } else if (e.getSource() == selectionModel) { repaint(); } } } }
21,918
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
FutureEvent.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/FutureEvent.java
package com.aexiz.daviz.ui.swing; import com.aexiz.daviz.ui.swing.ExecutionModel.DecideEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.EventType; import com.aexiz.daviz.ui.swing.ExecutionModel.InternalEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.ReceiveEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.SendEventType; import com.aexiz.daviz.ui.swing.ExecutionModel.TerminateEventType; public class FutureEvent { String process; EventType type; String other; public FutureEvent(String process, EventType type, String other) { if (process == null || type == null) throw null; this.process = process; this.type = type; if (type instanceof ReceiveEventType || type instanceof SendEventType) { if (other == null) throw null; this.other = other; } else if (other != null) throw new IllegalArgumentException(); } public String getProcessLabel() { return process; } public String getOtherLabel() { return other; } public EventType getType() { return type; } public String toString() { if (type instanceof ReceiveEventType) { return "(" + other + " ->) " + process; } if (type instanceof SendEventType) { return process + " (-> " + other + ")"; } if (type instanceof InternalEventType) { return process + " (i)"; } if (type instanceof TerminateEventType) { return process + " (|)"; } if (type instanceof DecideEventType) { return process + " (*)"; } throw new Error(); } }
1,540
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JAssignmentField.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JAssignmentField.java
package com.aexiz.daviz.ui.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import com.aexiz.daviz.images.ImageRoot; // Assignment field either pushes or pulls some object to/from selection. public class JAssignmentField extends JPanel { private static final long serialVersionUID = -2150341137917631106L; private int height; protected CustomDocument customDocument; protected JTextField field; protected JButton picker; protected ObjectSelectionModel selectionModel; protected Object[] value; public JAssignmentField() { super(null); Handler h = new Handler(); field = new JTextField(); field.setBorder(BorderFactory.createLineBorder(UIManager.getColor("Button.darkShadow"))); height = field.getPreferredSize().height; field.setPreferredSize(new Dimension(105, height)); field.setBackground(Color.WHITE); customDocument = new CustomDocument(); field.setDocument(customDocument); picker = new JButton(new ImageIcon(ImageRoot.class.getResource("d16/hand_property.png"))); picker.setToolTipText("Assign from selection"); picker.setPreferredSize(new Dimension(25, height)); picker.setFocusPainted(false); picker.setOpaque(false); picker.addActionListener(h); add(field, BorderLayout.CENTER); add(picker, BorderLayout.LINE_END); field.setBounds(0, 0, 105, height); int shiftleft = 2; picker.setBounds(105 - shiftleft, 0, 25 + shiftleft, height); } protected void updateField() { String text = ""; if (value != null) { for (int i = 0; i < value.length; i++) { if (i > 0) text += ", "; text += value[i].toString(); } } customDocument.locked = false; field.setText(text); customDocument.locked = true; } protected void filterValue() { } public void replayValue() { filterValue(); if (value.length == 0) { getToolkit().beep(); } updateField(); } public void setValue() { if (selectionModel == null) value = null; else value = selectionModel.getSelection(); replayValue(); } public void setValue(Object[] selection) { value = selection.clone(); replayValue(); } public void clearValue() { value = null; updateField(); } public Object[] getValue() { return value; } public void setEnabled(boolean enabled) { super.setEnabled(enabled); field.setEnabled(enabled); picker.setEnabled(enabled); updateField(); } public void setSelectionModel(ObjectSelectionModel selectionModel) { ObjectSelectionModel old = this.selectionModel; if (old != null) clearValue(); this.selectionModel = selectionModel; if (selectionModel != old) firePropertyChange("selectionModel", old, selectionModel); } public ObjectSelectionModel getSelectionModel() { return selectionModel; } public boolean isOptimizedDrawingEnabled() { return false; } public Dimension getMinimumSize() { return new Dimension(130, height); } public Dimension getPreferredSize() { return getMinimumSize(); } class Handler implements ActionListener { public void actionPerformed(ActionEvent e) { setValue(); field.requestFocusInWindow(); } } static class CustomDocument extends PlainDocument { private static final long serialVersionUID = 647932359351911969L; boolean locked = true; public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (locked) return; super.insertString(offs, str, a); } public void remove(int offs, int len) throws BadLocationException { if (locked) return; super.remove(offs, len); } public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (locked) return; super.replace(offset, length, text, attrs); } } }
4,303
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
CarouselCellRenderer.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/CarouselCellRenderer.java
package com.aexiz.daviz.ui.swing; import java.awt.Component; public interface CarouselCellRenderer { Component getCarouselCellRendererComponent(JCarousel list, Object value, int index, boolean isSelected, boolean cellHasFocus); }
246
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JCoolBar.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JCoolBar.java
package com.aexiz.daviz.ui.swing; import java.awt.Color; import java.awt.Component; import javax.swing.AbstractButton; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JToolBar; public class JCoolBar extends JToolBar { private static final long serialVersionUID = -1881213485624315909L; public JCoolBar() { setFloatable(false); setRollover(true); } public void addHorizontalGlue() { Component box = Box.createHorizontalGlue(); box.setFocusable(false); add(box); } protected void addImpl(Component comp, Object constraints, int index) { if (comp instanceof JComponent) { ((JComponent) comp).setOpaque(false); } if (comp instanceof AbstractButton) { // Change background, so button is rendered differently // Since the component is not opaque, we do not render this color ((AbstractButton) comp).setBackground(Color.BLACK); // We do allow the focus to be painted, for keyboard users ((AbstractButton) comp).setFocusPainted(true); // But the focus is not captured after a click ((AbstractButton) comp).setRequestFocusEnabled(false); } super.addImpl(comp, constraints, index); } }
1,203
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
ObjectSelectionModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/ObjectSelectionModel.java
package com.aexiz.daviz.ui.swing; import javax.swing.event.ChangeListener; public interface ObjectSelectionModel { public void clearSelection(); public boolean isSelected(Object o); public boolean isSelectionEmpty(); public boolean addSelection(Object o); public void removeSelection(Object o); public Object[] getSelection(); public void addChangeListener(ChangeListener l); public void removeChangeListener(ChangeListener l); }
481
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
JStatus.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/JStatus.java
package com.aexiz.daviz.ui.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.Timer; import com.aexiz.daviz.images.ImageRoot; public class JStatus extends JComponent { private static final long serialVersionUID = 5290034646898044837L; private static final int TEMPORARY_EXPIRE_TIME = 2000; // 2 seconds ImageIcon infoIcon; ImageIcon warningIcon; JLabel label; String defaultStatus; String temporaryStatus; Timer timer; public JStatus() { infoIcon = new ImageIcon(ImageRoot.class.getResource("d32/lightbulb_off.png")); warningIcon = new ImageIcon(ImageRoot.class.getResource("d32/lightbulb.png")); label = new JLabel(); label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); label.setBackground(Color.WHITE); label.setOpaque(true); setLayout(new BorderLayout()); add(label, BorderLayout.CENTER); timer = new Timer(TEMPORARY_EXPIRE_TIME, new ActionListener() { public void actionPerformed(ActionEvent e) { setTemporaryStatus(null); timer.stop(); } }); timer.setRepeats(false); } private void updateLabel() { if (temporaryStatus == null) { label.setIcon(infoIcon); label.setText(defaultStatus); label.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } else { label.setIcon(warningIcon); label.setText(temporaryStatus); label.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } } public void setDefaultStatus(String message) { defaultStatus = message; updateLabel(); } public String getDefaultStatus() { return defaultStatus; } public void setTemporaryStatus(String message) { temporaryStatus = message; updateLabel(); timer.stop(); if (message != null) { timer.start(); } } public String getTemporaryStatus() { return temporaryStatus; } public static void setTemporaryStatus(Component comp, String message) { // Traverse all back to root pane Container root = SwingUtilities.getRootPane(comp); // Perform depth first search for outer-most left-most JStatus JStatus status = dfs(root); if (status != null) { status.setTemporaryStatus(message); } } private static JStatus dfs(Container root) { for (int i = 0, s = root.getComponentCount(); i < s; i++) { Component c = root.getComponent(i); if (c instanceof JStatus) { return (JStatus) c; } if (c instanceof Container) { JStatus result = dfs((Container) c); if (result != null) return result; } } return null; } }
2,939
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
DefaultGraphModel.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/DefaultGraphModel.java
package com.aexiz.daviz.ui.swing; import java.util.ArrayList; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; public class DefaultGraphModel implements GraphModel { private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public void addModeEventListener(ModeEventListener l) { listenerList.add(ModeEventListener.class, l); } public void removeModeEventListener(ModeEventListener l) { listenerList.remove(ModeEventListener.class, l); } protected transient EventObject modeEvent; protected void fireModeChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ModeEventListener.class) { if (modeEvent == null) modeEvent = new EventObject(this); ((ModeEventListener) listeners[i+1]).modeChanged(modeEvent); } } } class DefaultNodeModel implements NodeModel { protected float x, y, dx, dy; protected boolean pressed; protected String label = "?"; protected ArrayList<String> incomingNodes = new ArrayList<>(); protected ArrayList<String> outgoingNodes = new ArrayList<>(); DefaultNodeModel(float x, float y) { this.x = x; this.y = y; } public DefaultGraphModel getParent() { return DefaultGraphModel.this; } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public void setX(float x) { if (x != x) x = 0.0f; this.x = x; this.dx = 0.0f; fireStateChanged(); } public void setDeltaX(float dx) { if (dx != dx) dx = 0.0f; this.dx = dx; fireStateChanged(); } public float getX() { return x + dx; } public float getXWithoutDelta() { return x; } public void setY(float y) { if (y != y) y = 0.0f; this.y = y; this.dy = 0.0f; fireStateChanged(); } public void setDeltaY(float dy) { if (dy != dy) dy = 0.0f; this.dy = dy; fireStateChanged(); } public float getY() { return y + dy; } public float getYWithoutDelta() { return y; } public boolean isPressed() { return pressed; } public void setPressed(boolean p) { pressed = p; fireStateChanged(); } public void validate() { if (isSnapToGrid()) { setX(Math.round(getX())); setY(Math.round(getY())); } else { setX(getX()); setY(getY()); } } public void setLabel(String label) { if (label == null) throw null; this.label = label; } public String getLabel() { return label; } public boolean isOverlapping() { for(NodeModel n : getValidNode()) { if (n == this) continue; if (n.getX() == getX() && n.getY() == getY()) return true; } return false; } public void remove() { removeNode(this); } public String toString() { return getLabel(); } @Override public void addIncomingNode(String node) { incomingNodes.add(node); } @Override public void removeIncomingNode(String node) { incomingNodes.remove(node); } @Override public ArrayList<String> getIncomingNodes() { return incomingNodes; } @Override public void addOutgoingNode(String node) { outgoingNodes.add(node); } @Override public void removeOutgoingNode(String node) { outgoingNodes.remove(node); } @Override public ArrayList<String> getOutgoingNodes() { return outgoingNodes; } } class DefaultEdgeModel implements EdgeModel { protected DefaultNodeModel from; protected DefaultNodeModel to; private boolean directed; DefaultEdgeModel(DefaultNodeModel from, DefaultNodeModel to) { if (from.getParent() != DefaultGraphModel.this || to.getParent() != DefaultGraphModel.this) throw new IllegalArgumentException(); this.from = from; this.to = to; } public DefaultGraphModel getParent() { return DefaultGraphModel.this; } private EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected transient ChangeEvent changeEvent; protected void fireStateChanged() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (changeEvent == null) changeEvent = new ChangeEvent(this); ((ChangeListener) listeners[i+1]).stateChanged(changeEvent); } } } public boolean isDirected() { return directed; } public void setDirected(boolean directed) { this.directed = directed; fireStateChanged(); } public NodeModel getFrom() { return from; } public NodeModel getTo() { return to; } public void validate() { } public void remove() { removeEdge(this); } } private Iterable<String> generateDefaultNames() { return new Iterable<String>() { public Iterator<String> iterator() { return new Iterator<String>() { int index = 0; char[] set = {'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public boolean hasNext() { return index >= 0; } public String next() { String result = ""; int index = this.index; while (index >= set.length) { result = String.valueOf(set[index % set.length]) + result; index = (index / set.length) - 1; } if (index < set.length) { result = String.valueOf(set[index]) + result; } this.index++; return result; } }; } }; } public DefaultNodeModel createNode(float x, float y) { DefaultNodeModel result = new DefaultNodeModel(x, y); // Find default name for (String name : generateDefaultNames()) { if (findNodeByLabel(name) == null) { result.setLabel(name); break; } } return result; } public DefaultEdgeModel createEdge(NodeModel from, NodeModel to) { return new DefaultEdgeModel((DefaultNodeModel) from, (DefaultNodeModel) to); } private ArrayList<DefaultNodeModel> nodes = new ArrayList<>(); public int getNodeCount() { return nodes.size(); } public NodeModel getNode(int index) { return nodes.get(index); } public NodeModel[] getNode() { return nodes.toArray(new NodeModel[nodes.size()]); } @Override public NodeModel getRandomNode() { int index = (int)(Math.random() * getNodeCount()) + 0; return nodes.get(index); } public void addNode(NodeModel n) { DefaultNodeModel dn = (DefaultNodeModel) n; if (dn.getParent() != this) throw new IllegalArgumentException(); if (nodes.contains(n)) return; nodes.add(dn); if (dn == temporaryNode) { temporaryNode = null; } fireStateChanged(); } public void removeNode(NodeModel n) { DefaultNodeModel dn = (DefaultNodeModel) n; if (dn.getParent() != this) throw new IllegalArgumentException(); if (!nodes.contains(n)) throw new IllegalArgumentException(); removeNodeFromAdjancet(dn); nodes.remove(n); fireStateChanged(); } public DefaultNodeModel findNodeByLabel(String label) { for (DefaultNodeModel n : nodes) { if (n.getLabel().equals(label)) return n; } return null; } private ArrayList<DefaultEdgeModel> edges = new ArrayList<>(); public int getEdgeCount() { return edges.size(); } public EdgeModel getEdge(int index) { return edges.get(index); } public EdgeModel[] getEdge() { return edges.toArray(new EdgeModel[edges.size()]); } public void addEdge(EdgeModel e) { DefaultEdgeModel de = (DefaultEdgeModel) e; if (de.getParent() != this) throw new IllegalArgumentException(); DefaultEdgeModel removeA = null, removeB = null; setNodesAsAdjacent(de.getFrom(), de.getTo(), de.isDirected()); /* Verifies if the new edge already exists */ if (e.isDirected()) { for (DefaultEdgeModel f : edges) { if (f.isDirected() && f.from == de.from && f.to == de.to) return; if (!f.isDirected() && (f.from == de.from && f.to == de.to || f.from == de.to && f.to == de.from)) return; } } else { for (DefaultEdgeModel f : edges) { /* Replace a previously unidirectional edge with the new bidirectional edge */ if (f.isDirected() && (f.from == de.from && f.to == de.to || f.from == de.to && f.to == de.from)) { if (removeA == null) removeA = f; else removeB = f; break; } if (!f.isDirected() && (f.from == de.from && f.to == de.to || f.from == de.to && f.to == de.from)) return; } } if (removeA != null) edges.remove(removeA); if (removeB != null) edges.remove(removeB); edges.add(de); if (de == temporaryEdge) { temporaryEdge = null; } fireStateChanged(); } public void removeEdge(EdgeModel e) { DefaultEdgeModel de = (DefaultEdgeModel) e; if (de.getParent() != this) throw new IllegalArgumentException(); if (!edges.contains(e)) throw new IllegalArgumentException(); edges.remove(e); fireStateChanged(); } public NodeModel[] getValidNode() { return getNode(); } public EdgeModel[] getValidEdge() { ArrayList<DefaultEdgeModel> result = new ArrayList<>(); for (DefaultEdgeModel e : edges) { if (nodes.contains(e.from) && nodes.contains(e.to)) result.add(e); } return result.toArray(new EdgeModel[result.size()]); } private boolean snapToGrid = false; public void setSnapToGrid(boolean snap) { if (snapToGrid != snap) { snapToGrid = snap; validate(); } } public boolean isSnapToGrid() { return snapToGrid; } public void validate() { for (EdgeModel edge : getValidEdge()) edge.validate(); for (NodeModel node : getValidNode()) node.validate(); } public void clear() { edges.clear(); nodes.clear(); fireStateChanged(); } private int editMode = MODE_SELECTION; public void setEditMode(int mode) { if (mode != MODE_SELECTION && mode != MODE_EDGE && mode != MODE_VERTEX && mode != MODE_ERASE) throw new IllegalArgumentException(); int oldmode = editMode; editMode = mode; if (mode != oldmode) { if (oldmode == MODE_VERTEX) { clearTemporaryNode(); } else if (oldmode == MODE_EDGE) { clearTemporaryEdge(); clearTemporaryNode(); } fireModeChanged(); } } public int getEditMode() { return editMode; } private DefaultNodeModel temporaryNode; public void setTemporaryNode(NodeModel n) { if (editMode != MODE_EDGE && editMode != MODE_VERTEX) return; DefaultNodeModel dn = (DefaultNodeModel) n; if (dn.getParent() != this) throw new IllegalArgumentException(); temporaryNode = dn; } public NodeModel getTemporaryNode() { return temporaryNode; } public static final float SNAP_DISTANCE = 1.0f; public NodeModel findNearestValidNodeToTemporary() { if (temporaryNode == null) return null; float fx = temporaryNode.getX(); float fy = temporaryNode.getY(); return findNearestValidNode(fx, fy); } public NodeModel findNearestValidNode(float fx, float fy) { float dist = Float.MAX_VALUE; NodeModel result = null; for (NodeModel n : getValidNode()) { float tx = n.getX(); float ty = n.getY(); float d = (fx - tx) * (fx - tx) + (fy - ty) * (fy - ty); if (d < dist) { dist = d; result = n; } } if (dist <= SNAP_DISTANCE) return result; else return null; } public void clearTemporaryNode() { temporaryNode = null; } private DefaultEdgeModel temporaryEdge; public void setTemporaryEdge(EdgeModel e) { if (editMode != MODE_EDGE) return; DefaultEdgeModel de = (DefaultEdgeModel) e; if (de.getParent() != this) throw new IllegalArgumentException(); temporaryEdge = de; } public EdgeModel getTemporaryEdge() { return temporaryEdge; } public void clearTemporaryEdge() { temporaryEdge = null; } private float zoom = 1.0f; public void setZoomLevel(float zoom) { if (zoom < 0.0f || zoom != zoom) zoom = 1.0f; this.zoom = zoom; fireStateChanged(); } public float getZoomLevel() { return zoom; } public boolean isAcyclic() { Map<String, Boolean> visited = createNodeVisitedMap(); for (NodeModel node : nodes) { if (!visited.get(node.getLabel()) && isAcyclicHelper(node, "", visited)) { return false; } } return true; } private Map<String, Boolean> createNodeVisitedMap() { Map<String, Boolean> visited = new HashMap<String, Boolean>(); for (NodeModel node : nodes) { visited.put(node.getLabel(), false); } return visited; } private boolean isAcyclicHelper(NodeModel node, String parent, Map<String, Boolean> visited) { visited.put(node.getLabel(), true); for (String outgoingNodeLabel : node.getOutgoingNodes()) { if (!visited.get(outgoingNodeLabel)) { DefaultNodeModel outgoingNode = findNodeByLabel(outgoingNodeLabel); if (isAcyclicHelper(outgoingNode, node.getLabel(), visited)) { return true; } } else if (outgoingNodeLabel != parent) { return true; } } return false; } public boolean isEmpty() { return nodes.size() == 0; } private boolean readOnly; public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; fireStateChanged(); } public boolean isReadOnly() { return readOnly; } protected void setNodesAsAdjacent(NodeModel from, NodeModel to, boolean directed) { NodeModel fromInNodes = findNodeByLabel(from.getLabel()); NodeModel toInNodes = findNodeByLabel(to.getLabel()); fromInNodes.addOutgoingNode(to.getLabel()); toInNodes.addIncomingNode(from.getLabel()); if (!directed) { fromInNodes.addIncomingNode(to.getLabel()); toInNodes.addOutgoingNode(from.getLabel()); } } protected void removeNodeFromAdjancet(NodeModel node) { for (String label : node.getIncomingNodes()) { NodeModel incomingNode = findNodeByLabel(label); incomingNode.removeOutgoingNode(node.getLabel()); incomingNode.removeIncomingNode(node.getLabel()); } } }
15,949
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
InfoTableUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/InfoTableUI.java
package com.aexiz.daviz.ui.swing.plaf; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JInfoTable; public abstract class InfoTableUI extends ComponentUI { public void configureLabelComponent(JLabel c) { } public void configureSimplePropertyComponent(JTextField c) { } public void configureNestedPlaceholderComponent(JComponent c) { } public void configureFillerComponent(JComponent c) { } public void addComponent(JInfoTable c, JComponent child) { c.add(child); } }
631
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
TimelineUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/TimelineUI.java
package com.aexiz.daviz.ui.swing.plaf; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JTimeline.JEvent; import com.aexiz.daviz.ui.swing.JTimeline.JMessage; import com.aexiz.daviz.ui.swing.JTimeline.JTimeRuler; public abstract class TimelineUI extends ComponentUI { public void configureEventComponent(JEvent c) { } public void configureMessageComponent(JMessage c) { } public void configureTimeRulerComponent(JTimeRuler c) { } }
487
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
CarouselUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/CarouselUI.java
package com.aexiz.daviz.ui.swing.plaf; import java.awt.Point; import java.awt.Rectangle; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JCarousel; public abstract class CarouselUI extends ComponentUI { public abstract int locationToIndex(JCarousel c, Point location); public abstract Point indexToLocation(JCarousel c, int index); public abstract Rectangle getCellBounds(JCarousel c, int from, int to); }
459
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
GraphUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/GraphUI.java
package com.aexiz.daviz.ui.swing.plaf; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JGraph.JEdge; import com.aexiz.daviz.ui.swing.JGraph.JNode; public abstract class GraphUI extends ComponentUI { public void configureNodeComponent(JNode c) { } public void configureEdgeComponent(JEdge c) { } }
347
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
BasicCarouselUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/basic/BasicCarouselUI.java
package com.aexiz.daviz.ui.swing.plaf.basic; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.CellRendererPane; import javax.swing.JComponent; import javax.swing.UIManager; import com.aexiz.daviz.ui.swing.CarouselCellRenderer; import com.aexiz.daviz.ui.swing.JCarousel; import com.aexiz.daviz.ui.swing.plaf.CarouselUI; public class BasicCarouselUI extends CarouselUI { CellRendererPane rendererPane = new CellRendererPane(); // Called by reflection code public static BasicCarouselUI createUI(JComponent c) { return new BasicCarouselUI(); } public void installUI(JComponent c) { JCarousel cc = (JCarousel) c; cc.setOpaque(true); cc.setFocusable(true); cc.setBackground(UIManager.getColor("List.background")); cc.setForeground(UIManager.getColor("List.foreground")); cc.setSelectionBackground(UIManager.getColor("List.selectionBackground")); cc.setSelectionForeground(UIManager.getColor("List.selectionForeground")); cc.setFont(UIManager.getFont("List.font")); cc.add(rendererPane); class Handler implements KeyListener, MouseListener, MouseMotionListener, FocusListener { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { int i = cc.locationToIndex(e.getPoint()); cc.requestFocusInWindow(); cc.setSelectedIndex(i); e.consume(); } public void mouseDragged(MouseEvent e) { int i = cc.locationToIndex(e.getPoint()); cc.requestFocusInWindow(); if (i >= 0) cc.ensureIndexIsVisible(i); cc.setSelectedIndex(i); e.consume(); } public void mouseReleased(MouseEvent e) { } public void focusGained(FocusEvent e) { cc.repaint(); } public void focusLost(FocusEvent e) { cc.repaint(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { int i = cc.getAnchorSelectionIndex() - 1; if (i < 0) i = 0; cc.setSelectedIndex(i); cc.ensureIndexIsVisible(i); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { int i = cc.getAnchorSelectionIndex() + 1, sz = cc.getValueCount(); if (i >= sz) i = sz - 1; cc.setSelectedIndex(i); cc.ensureIndexIsVisible(i); e.consume(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } } Handler h = new Handler(); c.addMouseListener(h); c.addMouseMotionListener(h); c.addFocusListener(h); c.addKeyListener(h); } public void uninstallUI(JComponent c) { c.removeAll(); // TODO unregister handler } public Dimension getMinimumSize(JComponent c) { JCarousel carousel = (JCarousel) c; CarouselCellRenderer r = carousel.getCellRenderer(); if (r == null) return new Dimension(0, 0); int width = 0; int height = 0; for (int i = 0, size = carousel.getValueCount(); i < size; i++) { Object o = carousel.getValue(i); Component ch = r.getCarouselCellRendererComponent(carousel, o, i, false, false); if (ch == null) continue; rendererPane.add(ch); Dimension dim = ch.getPreferredSize(); Dimension dim2 = ch.getMinimumSize(); width += dim.width; if (dim2.height > height) height = dim2.height; } rendererPane.removeAll(); return new Dimension(width, height); } public Dimension getPreferredSize(JComponent c) { return getMinimumSize(c); } public void paint(Graphics g, JComponent c) { JCarousel carousel = (JCarousel) c; Dimension d = carousel.getSize(); g.setColor(carousel.getBackground()); CarouselCellRenderer r = carousel.getCellRenderer(); int x = 0; for (int i = 0, size = carousel.getValueCount(); i < size; i++) { Object o = carousel.getValue(i); boolean isSelected = carousel.isSelectedIndex(i); boolean cellHasFocus = carousel.hasFocus() && carousel.getAnchorSelectionIndex() == i; Component ch = r.getCarouselCellRendererComponent(carousel, o, i, isSelected, cellHasFocus); if (ch == null) continue; Dimension dim = ch.getPreferredSize(); rendererPane.paintComponent(g, ch, carousel, x, 0, dim.width, d.height, true); x += dim.width; } rendererPane.removeAll(); } public int locationToIndex(JCarousel c, Point location) { Dimension d = c.getSize(); if (location.y < 0 || location.y >= d.height) return -1; CarouselCellRenderer r = c.getCellRenderer(); int x = 0; for (int i = 0, size = c.getValueCount(); i < size; i++) { Object o = c.getValue(i); Component ch = r.getCarouselCellRendererComponent(c, o, i, false, false); Dimension dim = ch.getPreferredSize(); if (location.x >= x && location.x < x + dim.width) return i; x += dim.width; } return -1; } public Point indexToLocation(JCarousel c, int index) { CarouselCellRenderer r = c.getCellRenderer(); int x = 0; for (int i = 0, size = c.getValueCount(); i < size; i++) { Object o = c.getValue(i); Component ch = r.getCarouselCellRendererComponent(c, o, i, false, false); Dimension dim = ch.getPreferredSize(); if (index == i) return new Point(x, 0); x += dim.width; } return null; } public Rectangle getCellBounds(JCarousel c, int from, int to) { CarouselCellRenderer r = c.getCellRenderer(); Dimension d = c.getSize(); Rectangle result = new Rectangle(); result.y = 0; result.height = d.height; int x = 0; for (int i = 0, size = c.getValueCount(); i < size; i++) { Object o = c.getValue(i); Component ch = r.getCarouselCellRendererComponent(c, o, i, false, false); Dimension dim = ch.getPreferredSize(); if (from == i) { result.x = x; } if (from <= i && i <= to) { result.width += dim.width; } x += dim.width; } return result; } }
6,340
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
BasicTimelineUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/basic/BasicTimelineUI.java
package com.aexiz.daviz.ui.swing.plaf.basic; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.util.EventObject; import java.util.IdentityHashMap; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JTimeline; import com.aexiz.daviz.ui.swing.ExecutionModel.TimeEventListener; import com.aexiz.daviz.ui.swing.JTimeline.JEvent; import com.aexiz.daviz.ui.swing.JTimeline.JMessage; import com.aexiz.daviz.ui.swing.JTimeline.JTimeRuler; import com.aexiz.daviz.ui.swing.plaf.TimelineUI; public class BasicTimelineUI extends TimelineUI { static final String INTERNAL_STRING = "i"; BasicEventUI basicEventUI = new BasicEventUI(); static class BasicEventUI extends ComponentUI { private IdentityHashMap<JComponent, Handler> state = new IdentityHashMap<>(); static class Handler implements ChangeListener, MouseListener, MouseMotionListener { JEvent event; boolean noClick; public void mouseClicked(MouseEvent e) { if (noClick) return; if (e.getClickCount() == 2) event.requestAllSelected(); else if (e.getClickCount() == 1) event.requestSingleSelected(); } public void mouseEntered(MouseEvent e) { event.setRollover(true); } public void mouseMoved(MouseEvent e) {} public void mouseExited(MouseEvent e) { event.setRollover(false); } int firstXOnScreen; public void mousePressed(MouseEvent e) { if (e.isControlDown()) { noClick = true; event.setSelected(!event.isSelected()); return; } else if (e.isShiftDown()) { noClick = true; event.setSelected(true); return; } else { noClick = false; } if (!event.isSelected()) event.requestClearSelection(); switch (event.getTimeline().getEditMode()) { case JTimeline.MODE_SELECTION: break; case JTimeline.MODE_SWAP: firstXOnScreen = e.getXOnScreen(); event.setPressed(true); break; } } public void mouseDragged(MouseEvent e) { if (!event.isPressed()) return; Rectangle visRect = new Rectangle(0, 0, event.getWidth(), event.getHeight()); Point offset = event.scrollRectToVisibleWithEffect(visRect); firstXOnScreen += offset.x; // adjust original screen position by amount that was scrolled int ex = e.getXOnScreen(); float delta = (ex - firstXOnScreen) / (float) EVENT_TIMEUNIT; event.setDelta(delta); } public void mouseReleased(MouseEvent e) { switch (event.getTimeline().getEditMode()) { case JTimeline.MODE_SELECTION: break; case JTimeline.MODE_SWAP: event.setPressed(false); } } public void stateChanged(ChangeEvent ce) { event.repaint(); } } public void installUI(JComponent c) { JEvent e = (JEvent) c; e.setOpaque(false); e.setBackground(UIManager.getColor("Tree.background")); e.setRolloverBackground(new Color(220, 220, 220)); e.setPressedBackground(new Color(200, 200, 220)); e.setForeground(UIManager.getColor("Tree.foreground")); e.setRolloverForeground(UIManager.getColor("Tree.foreground")); e.setPressedForeground(UIManager.getColor("Tree.foreground")); e.setSelectionBackground(UIManager.getColor("Tree.selectionBackground")); e.setSelectionForeground(UIManager.getColor("Tree.foreground")); Font o = UIManager.getFont("Tree.font"); e.setFont(o.deriveFont(9.0f)); Handler h = new Handler(); h.event = e; e.addMouseListener(h); e.addMouseMotionListener(h); e.addChangeListener(h); state.put(c, h); } @Override public void uninstallUI(JComponent c) { JEvent e = (JEvent) c; Handler h = state.remove(c); e.removeMouseListener(h); e.removeMouseMotionListener(h); e.removeChangeListener(h); } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JEvent e = (JEvent) c; Dimension dim = e.getSize(); if (e.isSelected()) { if (e.isPressed()) g.setColor(e.getSelectionPressedBackground()); else if (e.isRollover()) g.setColor(e.getSelectionRolloverBackground()); else g.setColor(e.getSelectionBackground()); } else { if (e.isPressed()) g.setColor(e.getPressedBackground()); else if (e.isRollover()) g.setColor(e.getRolloverBackground()); else g.setColor(e.getBackground()); } if (e.isReceiveEvent() || e.isSendEvent() || e.isInternalEvent()) { g.fillOval(0, 0, dim.width - 1, dim.height - 1); } else if (e.isDecideEvent()) { g.fillRect(0, 0, dim.width - 1, dim.height - 1); } else if ((e.isRollover() || e.isPressed() || e.isSelected()) && e.isTerminateEvent()) { g.fillRect(0, 0, dim.width, dim.height); } if (e.isSelected()) { if (e.isPressed()) g.setColor(e.getSelectionPressedForeground()); else if (e.isRollover()) g.setColor(e.getSelectionRolloverForeground()); else g.setColor(e.getSelectionForeground()); } else { if (e.isPressed()) g.setColor(e.getPressedForeground()); else if (e.isRollover()) g.setColor(e.getRolloverForeground()); else g.setColor(e.getForeground()); } if (e.isTerminateEvent()) { g.drawLine(0, 0, 0, dim.height - 1); } else if (e.isDecideEvent()) { g.drawRect(0, 0, dim.width - 1, dim.height - 1); } else { g.drawOval(0, 0, dim.width - 1, dim.height - 1); } if (e.isInternalEvent()) { g.setFont(e.getFont()); FontMetrics fm = g.getFontMetrics(e.getParent().getFont()); int h = fm.getAscent() - fm.getHeight() / 2; g.drawString(INTERNAL_STRING, (dim.width - 1) / 2, (dim.height - 1) / 2 + h); } } public boolean contains(JComponent c, int x, int y) { JEvent e = (JEvent) c; Dimension dim = e.getSize(); if (e.isTerminateEvent() || e.isDecideEvent()) { return x >= 0 && x < dim.width && y >= 0 && y < dim.height; } else { int q = dim.width / 2, r = (x - q) * (x - q) + (y - q) * (y - q); return r < q * q; } } public Dimension getPreferredSize(JComponent c) { return getMinimumSize(c); } public Dimension getMinimumSize(JComponent c) { return new Dimension(EVENT_DIAMETER, EVENT_DIAMETER); } } BasicMessageUI basicMessageUI = new BasicMessageUI(); static class BasicMessageUI extends ComponentUI { private Stroke stroke = new BasicStroke(7.0f); class Handler implements MouseListener, ChangeListener { JMessage message; boolean noClick; public void mouseClicked(MouseEvent e) { if (noClick) return; if (e.getClickCount() == 2) message.requestAllSelected(); else if (e.getClickCount() == 1) message.requestSingleSelected(); } public void mouseEntered(MouseEvent e) { message.setRollover(true); } public void mouseExited(MouseEvent e) { message.setRollover(false); } public void mousePressed(MouseEvent e) { if (e.isControlDown()) { noClick = true; message.setSelected(!message.isSelected()); return; } else if (e.isShiftDown()) { noClick = true; message.setSelected(true); return; } else { noClick = false; } if (!message.isSelected()) message.requestClearSelection(); message.setPressed(true); } public void mouseReleased(MouseEvent e) { message.setPressed(false); } public void stateChanged(ChangeEvent e) { message.repaint(); } } public void installUI(JComponent c) { JMessage m = (JMessage) c; m.setRolloverBackground(new Color(220, 220, 220)); m.setForeground(UIManager.getColor("Tree.foreground")); m.setRolloverForeground(UIManager.getColor("Tree.foreground")); m.setSelectionBackground(UIManager.getColor("Tree.selectionBackground")); m.setSelectionForeground(UIManager.getColor("Tree.foreground")); m.setErrorColor(Color.RED); Handler h = new Handler(); h.message = m; m.addMouseListener(h); m.addChangeListener(h); // TODO uninstall handler } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JMessage m = (JMessage) c; int dir = m.getDirection(); Dimension dim = c.getSize(); int fx, fy, tx, ty, ax, ay; if (dir == JMessage.DIR_NORTH_EAST) { fx = EVENT_DIAMETER / 2; fy = dim.height - 1 - EVENT_DIAMETER / 2; tx = dim.width - 1 - EVENT_DIAMETER / 2; ty = EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_SOUTH_WEST) { fx = dim.width - 1 - EVENT_DIAMETER / 2; fy = EVENT_DIAMETER / 2; tx = EVENT_DIAMETER / 2; ty = dim.height - 1 - EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_NORTH_WEST) { fx = dim.width - 1 - EVENT_DIAMETER / 2; fy = dim.height - 1 - EVENT_DIAMETER / 2; tx = EVENT_DIAMETER / 2; ty = EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_SOUTH_EAST) { fx = EVENT_DIAMETER / 2; fy = EVENT_DIAMETER / 2; tx = dim.width - 1 - EVENT_DIAMETER / 2; ty = dim.height - 1 - EVENT_DIAMETER / 2; } else throw new Error("Unexpected direction"); if (m.isSelected() || m.isRollover()) { if (m.isSelected()) { if (m.isRollover()) g.setColor(m.getSelectionRolloverBackground()); else g.setColor(m.getSelectionBackground()); } else { if (m.isRollover()) g.setColor(m.getRolloverBackground()); else throw new Error(); } if (g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(stroke); g.drawLine(fx, fy, tx, ty); g2d.setStroke(oldStroke); } } if (m.isConflicting()) g.setColor(m.getErrorColor()); else { if (m.isSelected()) { if (m.isRollover()) g.setColor(m.getSelectionRolloverForeground()); else g.setColor(m.getSelectionForeground()); } else { if (m.isRollover()) g.setColor(m.getRolloverForeground()); else g.setColor(m.getForeground()); } } if (m.isPending()) { Graphics2D g2d = (Graphics2D) g; Stroke dashed = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, new float[]{3f, 3f}, 0f); Stroke old = g2d.getStroke(); g2d.setStroke(dashed); g2d.drawLine(fx, fy, tx, ty); g2d.setStroke(old); } else { g.drawLine(fx, fy, tx, ty); } double rot = Math.atan2(ty - fy, tx - fx); ax = tx + (int) (EVENT_DIAMETER / -2.0 * Math.cos(rot)); ay = ty + (int) (EVENT_DIAMETER / -2.0 * Math.sin(rot)); if (!m.isPending()) GraphicsUtils.drawArrowHead(g, fx, fy, tx, ty, ax, ay); } public boolean contains(JComponent c, int x, int y) { JMessage m = (JMessage) c; int dir = m.getDirection(); Dimension dim = c.getSize(); int fx, fy, tx, ty; if (dir == JMessage.DIR_NORTH_EAST) { fx = EVENT_DIAMETER / 2; fy = dim.height - 1 - EVENT_DIAMETER / 2; tx = dim.width - 1 - EVENT_DIAMETER / 2; ty = EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_SOUTH_WEST) { fx = dim.width - 1 - EVENT_DIAMETER / 2; fy = EVENT_DIAMETER / 2; tx = EVENT_DIAMETER / 2; ty = dim.height - 1 - EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_NORTH_WEST) { fx = dim.width - 1 - EVENT_DIAMETER / 2; fy = dim.height - 1 - EVENT_DIAMETER / 2; tx = EVENT_DIAMETER / 2; ty = EVENT_DIAMETER / 2; } else if (dir == JMessage.DIR_SOUTH_EAST) { fx = EVENT_DIAMETER / 2; fy = EVENT_DIAMETER / 2; tx = dim.width - 1 - EVENT_DIAMETER / 2; ty = dim.height - 1 - EVENT_DIAMETER / 2; } else { // Layout manager may not have processed this one yet. // TODO compute direction statically, as in JGraph return true; } Shape line = new Line2D.Double(fx, fy, tx, ty); line = stroke.createStrokedShape(line); return line.contains(x, y); } static Rectangle findEnclosingRectangle(Rectangle from, Rectangle to) { int minx = Math.min(from.x, to.x); int miny = Math.min(from.y, to.y); int maxx = Math.max(from.x + from.width, to.x + to.width); int maxy = Math.max(from.y + from.height, to.y + to.height); return new Rectangle(minx, miny, maxx - minx, maxy - miny); } static int findDirection(Rectangle from, Rectangle to) { if (from.x > to.x) { if (from.y > to.y) { return JMessage.DIR_NORTH_WEST; } else { return JMessage.DIR_SOUTH_WEST; } } else { if (from.y > to.y) { return JMessage.DIR_NORTH_EAST; } else { return JMessage.DIR_SOUTH_EAST; } } } } BasicTimeRulerUI basicTimeRulerUI = new BasicTimeRulerUI(); static class BasicTimeRulerUI extends ComponentUI { private IdentityHashMap<JComponent, Handler> state = new IdentityHashMap<>(); static class Handler implements MouseListener, MouseMotionListener, TimeEventListener { JTimeRuler r; public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent me) {} public void mouseExited(MouseEvent me) {} public void mouseMoved(MouseEvent e) {} public void mouseReleased(MouseEvent me) { r.setPressed(false); } int firstXOnScreen; public void mousePressed(MouseEvent me) { r.setPressed(true); firstXOnScreen = me.getXOnScreen(); } public void mouseDragged(MouseEvent me) { int lastXOnScreen = me.getXOnScreen(); float delta = (lastXOnScreen - firstXOnScreen) / (float) EVENT_TIMEUNIT; r.setDelta(delta); } public void timeChanged(EventObject e) { if (r.getModel().getTemporaryMaxTime() > 0.0) return; SwingUtilities.invokeLater(() -> { r.invalidate(); r.validate(); Point offset = r.scrollRectToVisibleWithEffect(new Rectangle(0, 0, r.getWidth(), r.getHeight())); firstXOnScreen += offset.x; // adjust original screen position by amount that was scrolled }); } } public void installUI(JComponent c) { JTimeRuler r = (JTimeRuler) c; r.setOpaque(false); r.setForeground(Color.RED); r.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); Handler h = new Handler(); h.r = r; r.addMouseListener(h); r.addMouseMotionListener(h); r.addTimeEventListener(h); state.put(c, h); } public void uninstallUI(JComponent c) { JTimeRuler r = (JTimeRuler) c; Handler h = state.remove(c); r.removeMouseListener(h); r.removeMouseMotionListener(h); r.removeTimeEventListener(h); } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JTimeRuler r = (JTimeRuler) c; Dimension dim = r.getSize(); Color col = r.getForeground(); col = new Color(col.getRed(), col.getGreen(), col.getBlue(), 100); g.setColor(col); g.fillRect(0, 0, 1, dim.height); } @Override public Dimension getPreferredSize(JComponent c) { return new Dimension(EVENT_DIAMETER, 0); } } public void configureEventComponent(JEvent c) { c.setUI(basicEventUI); } public void configureMessageComponent(JMessage c) { c.setUI(basicMessageUI); } public void configureTimeRulerComponent(JTimeRuler c) { c.setUI(basicTimeRulerUI); } EventLayout layout = new EventLayout(); // Called by reflection code public static BasicTimelineUI createUI(JComponent c) { return new BasicTimelineUI(); } public void installUI(JComponent c) { JTimeline t = (JTimeline) c; t.setLayout(layout); t.setBackground(UIManager.getColor("control")); t.setInnerBackground(UIManager.getColor("Tree.background")); t.setAlternateBackground(new Color(245, 245, 255)); t.setInnerBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); t.setFont(UIManager.getFont("Tree.font")); Handler h = new Handler(); h.timeline = t; t.addMouseListener(h); t.addKeyListener(h); // TODO: remove handler at uninstall } public void uninstallUI(JComponent c) { } class Handler implements MouseListener, KeyListener { JTimeline timeline; Rectangle rulerKeyRect = new Rectangle(-200, 0, 400, 0); public void mouseClicked(MouseEvent me) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { boolean focus = timeline.hasFocus(); timeline.requestFocusInWindow(); Dimension within = timeline.getPreferredSize(); if (focus && !e.isControlDown() && !e.isShiftDown() && e.getY() < within.height) { timeline.clearSelection(); } e.consume(); } public void mouseReleased(MouseEvent me) {} public void keyPressed(KeyEvent e) { float time = timeline.getCurrentTime(); if (e.getKeyCode() == KeyEvent.VK_LEFT) { // Only consume if the current time is actually decreasable if (timeline.getCurrentTime() > 0.0f) { timeline.setCurrentTime(time - 1.0f); e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { if (timeline.getCurrentTime() < timeline.getModel().getMaxLastTime()) { timeline.setCurrentTime(time + 1.0f); e.consume(); } } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} } static final int PROCESS_HEIGHT = 57; static final int EVENT_DIAMETER = 15; static final int EVENT_TIMEUNIT = 22; static final int LABEL_LEFT = 10; static final int LABEL_RIGHT = 10; static int maxLabel(JTimeline t) { FontMetrics fm = t.getFontMetrics(t.getFont()); int n = t.getModel().getProcessCount(); int result = 0; for (int i = 0; i < n; i++) { String name = t.getModel().getProcessName(i); result = Math.max(result, fm.stringWidth(name)); } return result; } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JTimeline t = (JTimeline) c; Dimension dim = t.getSize(); Insets ii = t.getInnerInsets(); Border ib = t.getInnerBorder(); g.setColor(Color.RED); int n = t.getModel().getProcessCount(); int maxLabel = maxLabel(t); int y = 0; for (int i = 0; i < n; i++) { String name = t.getModel().getProcessName(i); if (ib != null) { ib.paintBorder(c, g, 0, y, dim.width, PROCESS_HEIGHT); } g.setColor(t.getInnerBackground()); int iwidth = dim.width - ii.left - ii.right, iheight = PROCESS_HEIGHT - ii.top - ii.bottom; g.fillRect(ii.left, y + ii.top, iwidth, iheight); float time = t.getModel().getProcessMaxTime(i); int mwidth = ii.left + LABEL_LEFT + maxLabel + LABEL_RIGHT; mwidth += time * EVENT_TIMEUNIT; mwidth -= ii.right; if (mwidth < iwidth) iwidth = mwidth; int i2height = (iheight - 1) / 2; int ma2 = g.getFontMetrics().getAscent() - g.getFontMetrics().getHeight() / 2; g.setColor(t.getForeground()); g.setFont(t.getFont()); g.drawString(name, LABEL_LEFT, y + ii.top + i2height + ma2); g.drawLine(ii.left + LABEL_LEFT + maxLabel + LABEL_RIGHT, y + ii.top + i2height, iwidth + 1, y + ii.top + i2height); y += PROCESS_HEIGHT - ii.bottom; } } static class EventLayout implements LayoutManager { public void addLayoutComponent(String arg, Component c) { } private int getProcessY(Container c, int index) { JTimeline t = (JTimeline) c; Insets ii = t.getInnerInsets(); int iheight = PROCESS_HEIGHT - ii.bottom - ii.top; int i2height = (iheight - 1) / 2; int y = (PROCESS_HEIGHT - ii.bottom) * index + ii.top + i2height; return y; } public void layoutContainer(Container c) { JTimeline t = (JTimeline) c; Insets ii = t.getInnerInsets(); int maxLabel = maxLabel(t); int n = t.getComponentCount(); for (int i = 0; i < n; i++) { Component child = t.getComponent(i); if (child instanceof JEvent) { JEvent event = (JEvent) child; Dimension dim = event.getPreferredSize(); int p = event.getProcessIndex(); int x, y; x = ii.left + LABEL_LEFT + maxLabel + LABEL_RIGHT; x += event.getTime() * EVENT_TIMEUNIT; y = getProcessY(t, p); y -= dim.height / 2; y -= event.getAscention() * EVENT_TIMEUNIT; child.setBounds(x, y, dim.width, dim.height); } } for (int i = 0; i < n; i++) { Component child = t.getComponent(i); if (child instanceof JMessage) { JMessage message = (JMessage) child; JEvent from = message.getFromEvent(); if (from == null) continue; if (message.isPending()) { int to = message.getToProcessIndex(); Rectangle rto = from.getBounds(); int ydiff = getProcessY(c, to) - (rto.y + rto.height / 2); rto.translate(0, ydiff); message.setBounds(BasicMessageUI.findEnclosingRectangle(from.getBounds(), rto)); if (ydiff <= 0) { message.setDirection(JMessage.DIR_NORTH_EAST); } else { message.setDirection(JMessage.DIR_SOUTH_EAST); } } else { JEvent to = message.getToEvent(); if (to == null) continue; message.setBounds(BasicMessageUI.findEnclosingRectangle(from.getBounds(), to.getBounds())); message.setDirection(BasicMessageUI.findDirection(from.getBounds(), to.getBounds())); } } } for (int i = 0; i < n; i++) { Component child = t.getComponent(i); if (child instanceof JTimeRuler) { JTimeRuler ruler = (JTimeRuler) child; Dimension pref = ruler.getPreferredSize(); Dimension dim = t.getSize(); Insets oi = t.getInsets(); int x; x = ii.left + LABEL_LEFT + maxLabel + LABEL_RIGHT; x += t.getCurrentTime() * EVENT_TIMEUNIT; ruler.setBounds(x, oi.top, pref.width, dim.height - oi.top - oi.bottom); } } } public Dimension minimumLayoutSize(Container c) { return new Dimension(100, 100); } public Dimension preferredLayoutSize(Container c) { JTimeline t = (JTimeline) c; Insets ii = t.getInnerInsets(); int n = t.getModel().getProcessCount(); float time = t.getModel().getMaxLastTimeWithoutDelta(); float temp = t.getModel().getTemporaryMaxTime(); if (temp > time) time = temp; int maxLabel = maxLabel(t); int mwidth = ii.left + LABEL_LEFT + maxLabel + LABEL_RIGHT; mwidth += time * EVENT_TIMEUNIT; mwidth += EVENT_TIMEUNIT; mwidth += LABEL_RIGHT; mwidth -= ii.right; return new Dimension(mwidth, (PROCESS_HEIGHT - ii.bottom) * n + ii.bottom); } public void removeLayoutComponent(Component c) { } } }
23,484
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
BasicGraphUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/basic/BasicGraphUI.java
package com.aexiz.daviz.ui.swing.plaf.basic; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.LayoutManager; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.font.LineMetrics; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ComponentUI; import com.aexiz.daviz.ui.swing.JGraph; import com.aexiz.daviz.ui.swing.JGraph.JEdge; import com.aexiz.daviz.ui.swing.JGraph.JNode; import com.aexiz.daviz.ui.swing.plaf.GraphUI; import com.aexiz.daviz.ui.swing.plaf.basic.BasicTimelineUI.BasicEventUI.Handler; public class BasicGraphUI extends GraphUI { BasicNodeUI basicNodeUI = new BasicNodeUI(); static class BasicNodeUI extends ComponentUI { public void installUI(JComponent c) { JNode node = (JNode) c; node.setOpaque(false); node.setRolloverBackground(new Color(220, 220, 220)); node.setRolloverForeground(UIManager.getColor("Tree.foreground")); node.setBackground(UIManager.getColor("Tree.background")); node.setForeground(UIManager.getColor("Tree.foreground")); node.setSelectionBackground(UIManager.getColor("Tree.selectionBackground")); node.setSelectionForeground(UIManager.getColor("Tree.selectionForeground")); Font o = UIManager.getFont("Tree.font"); node.setFont(o); class Handler implements ChangeListener, MouseListener, MouseMotionListener { int x, y; boolean noClick; JNode edgeTarget; public void mouseClicked(MouseEvent e) { JGraph g = node.getGraph(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: if (noClick) return; if (e.getClickCount() == 2) { node.requestAllSelected(); e.consume(); } else if (e.getClickCount() == 1) { node.requestSingleSelected(); e.consume(); } break; } } public void mouseEntered(MouseEvent e) { if (node.getGraph().getEditMode() == JGraph.MODE_ERASE && node.getGraph().isErasing()) { node.remove(); e.consume(); } else { node.setRollover(true); e.consume(); } } public void mouseExited(MouseEvent e) { node.setRollover(false); e.consume(); } public void mousePressed(MouseEvent me) { noClick = false; node.requestFocusInWindow(); JGraph g = node.getGraph(); ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: case JGraph.MODE_ERASE: if (me.isControlDown()) { noClick = true; node.setSelected(!node.isSelected()); me.consume(); return; } else if (me.isShiftDown()) { noClick = true; node.setSelected(true); me.consume(); return; } if (!node.isSelected()) node.requestClearSelection(); if (g.isReadOnly() || g.getEditMode() == JGraph.MODE_ERASE) break; case JGraph.MODE_VERTEX: x = me.getXOnScreen(); y = me.getYOnScreen(); node.setPressed(true); node.startMoving(); me.consume(); break; case JGraph.MODE_EDGE: float dx = cb.centerDeltaX(me.getX()); float dy = cb.centerDeltaY(me.getY()); dx += node.getModel().getX(); dy += node.getModel().getY(); edgeTarget = g.startCreatingEdge(node, dx, dy); x = me.getXOnScreen(); y = me.getYOnScreen(); edgeTarget.setPressed(true); edgeTarget.startMoving(); me.consume(); break; } } public void mouseReleased(MouseEvent me) { JGraph g = node.getGraph(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: case JGraph.MODE_VERTEX: case JGraph.MODE_ERASE: node.setPressed(false); if (!node.commitMoving()) { node.getToolkit().beep(); } me.consume(); break; case JGraph.MODE_EDGE: edgeTarget.setPressed(false); if (!g.commitCreatingEdge(edgeTarget)) { g.getToolkit().beep(); } edgeTarget = null; break; } if (g.getEditMode() == JGraph.MODE_ERASE) { node.remove(); g.requestFocusInWindow(); } } public void mouseMoved(MouseEvent e) {} public void mouseDragged(MouseEvent me) { int ex = me.getXOnScreen(); int ey = me.getYOnScreen(); JGraph g = node.getGraph(); ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); float deltaX = cb.deltaX(ex - x); float deltaY = cb.deltaY(ey - y); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: if (g.isReadOnly()) break; case JGraph.MODE_VERTEX: node.setDeltaX(deltaX); node.setDeltaY(deltaY); me.consume(); break; case JGraph.MODE_EDGE: edgeTarget.setDeltaX(deltaX); edgeTarget.setDeltaY(deltaY); me.consume(); break; } } public void stateChanged(ChangeEvent ce) { node.repaint(); } } Handler h = new Handler(); node.addMouseListener(h); node.addMouseMotionListener(h); node.addChangeListener(h); } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JNode node = (JNode) c; ComputeBounds cb = new ComputeBounds(); cb.g = node.getGraph(); cb.compute(); boolean temp = (Boolean) node.getClientProperty(JGraph.CLIENT_PROPERTY_TEMPORARY); Dimension dim = node.getSize(); if (temp) { g.setColor(node.getBackground()); g.fillOval(0, 0, dim.width - 1, dim.height - 1); Graphics2D g2d = (Graphics2D) g; Stroke old = g2d.getStroke(); float[] dash = new float[]{3.0f}; g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, dash, 0.0f)); g.setColor(node.getForeground()); g.drawOval(0, 0, dim.width - 1, dim.height - 1); g2d.setStroke(old); } else { if (node.isSelected()) { if (node.isRollover()) g.setColor(node.getSelectionRolloverBackground()); else g.setColor(node.getSelectionBackground()); } else { if (node.isRollover()) g.setColor(node.getRolloverBackground()); else g.setColor(node.getBackground()); } g.fillOval(0, 0, dim.width - 1, dim.height - 1); g.setColor(node.getForeground()); if (g instanceof Graphics2D) { Stroke normalStroke = new BasicStroke(1.0f * cb.zoom); Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(normalStroke); g2d.draw(new Ellipse2D.Float(cb.zoom / 2f, cb.zoom / 2f, dim.width - 1f - cb.zoom, dim.height - 1f - cb.zoom)); g2d.setStroke(oldStroke); } if (cb.zoom >= 1.0f) { Font f = node.getFont().deriveFont(10.0f * cb.zoom); g.setFont(f); FontMetrics fm = g.getFontMetrics(f); Rectangle2D dm = fm.getStringBounds(node.getLabel(), g); LineMetrics lm = fm.getLineMetrics(node.getLabel(), g); int x = (int) ((dim.width - dm.getWidth()) / 2.0); int y = (int) ((dim.height - dm.getHeight() - lm.getDescent()) / 2.0 - dm.getY()); g.drawString(node.getLabel(), x, y); } } } public boolean contains(JComponent c, int x, int y) { JNode node = (JNode) c; JGraph g = node.getGraph(); ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); int q = cb.getNodeRadius(), r = (x - q) * (x - q) + (y - q) * (y - q); return r < q * q; } public Dimension getPreferredSize(JComponent c) { return getMinimumSize(c); } public Dimension getMinimumSize(JComponent c) { JNode node = (JNode) c; JGraph g = node.getGraph(); ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); return new Dimension(cb.getNodeWidth(), cb.getNodeHeight()); } } BasicEdgeUI basicEdgeUI = new BasicEdgeUI(); static class BasicEdgeUI extends ComponentUI { private static final int DIR_NORTH_EAST = 1; private static final int DIR_SOUTH_EAST = 2; private static final int DIR_SOUTH_WEST = 3; private static final int DIR_NORTH_WEST = 4; public void installUI(JComponent c) { JEdge edge = (JEdge) c; edge.setOpaque(false); edge.setRolloverBackground(new Color(220, 220, 220)); edge.setRolloverForeground(UIManager.getColor("Tree.foreground")); edge.setForeground(UIManager.getColor("Tree.foreground")); edge.setSelectionBackground(UIManager.getColor("Tree.selectionBackground")); edge.setSelectionForeground(UIManager.getColor("Tree.foreground")); class Handler implements MouseListener, ChangeListener { boolean noClick; public void mouseClicked(MouseEvent e) { if (noClick) return; JGraph g = edge.getGraph(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: if (e.getClickCount() == 2) { edge.requestAllSelected(); e.consume(); } else if (e.getClickCount() == 1) { edge.requestSingleSelected(); e.consume(); } break; } } public void mouseEntered(MouseEvent e) { if (edge.getGraph().getEditMode() == JGraph.MODE_ERASE && edge.getGraph().isErasing()) { edge.remove(); e.consume(); } else { edge.setRollover(true); e.consume(); } } public void mouseExited(MouseEvent e) { edge.setRollover(false); } public void mousePressed(MouseEvent e) { edge.requestFocusInWindow(); JGraph g = edge.getGraph(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: if (e.isControlDown()) { noClick = true; edge.setSelected(!edge.isSelected()); return; } else if (e.isShiftDown()) { noClick = true; edge.setSelected(true); return; } else { noClick = false; } if (!edge.isSelected()) edge.requestClearSelection(); edge.setPressed(true); e.consume(); break; } } public void mouseReleased(MouseEvent me) { JGraph g = edge.getGraph(); switch (g.getEditMode()) { case JGraph.MODE_SELECTION: edge.setPressed(false); me.consume(); break; case JGraph.MODE_ERASE: edge.remove(); g.requestFocusInWindow(); me.consume(); break; } } public void stateChanged(ChangeEvent e) { edge.repaint(); } } Handler h = new Handler(); edge.addMouseListener(h); edge.addChangeListener(h); // TODO uninstall handler } public void paint(Graphics g, JComponent c) { GraphicsUtils.initializeGraphics(g); JEdge edge = (JEdge) c; ComputeBounds cb = new ComputeBounds(); cb.g = edge.getGraph(); cb.compute(); Dimension dim = c.getSize(); int fx, fy, tx, ty, ax, ay; switch (findDirection(edge)) { case DIR_NORTH_EAST: fx = cb.getNodeRadius(); fy = dim.height - cb.getNodeRadius() - 1; tx = dim.width - cb.getNodeRadius() - 1; ty = cb.getNodeRadius(); break; case DIR_SOUTH_WEST: fx = dim.width - cb.getNodeRadius() - 1; fy = cb.getNodeRadius(); tx = cb.getNodeRadius(); ty = dim.height - cb.getNodeRadius() - 1; break; case DIR_NORTH_WEST: fx = dim.width - cb.getNodeRadius() - 1; fy = dim.height - cb.getNodeRadius() - 1; tx = cb.getNodeRadius(); ty = cb.getNodeRadius(); break; case DIR_SOUTH_EAST: fx = cb.getNodeRadius(); fy = cb.getNodeRadius(); tx = dim.width - cb.getNodeRadius() - 1; ty = dim.height - cb.getNodeRadius() - 1; break; default: throw new RuntimeException(); } if (edge.isSelected() || edge.isRollover()) { if (edge.isSelected()) { if (edge.isRollover()) g.setColor(edge.getSelectionRolloverBackground()); else g.setColor(edge.getSelectionBackground()); } else { if (edge.isRollover()) g.setColor(edge.getRolloverBackground()); else throw new Error(); } if (g instanceof Graphics2D) { Stroke highlightStroke = new BasicStroke(7.0f * cb.zoom); Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(highlightStroke); g.drawLine(fx, fy, tx, ty); g2d.setStroke(oldStroke); } } g.setColor(edge.getForeground()); if (g instanceof Graphics2D) { Stroke normalStroke = new BasicStroke(1.0f * cb.zoom); Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = g2d.getStroke(); g2d.setStroke(normalStroke); g.drawLine(fx, fy, tx, ty); g2d.setStroke(oldStroke); } if (edge.isDirected()) { double rot = Math.atan2(ty - fy, tx - fx); ax = tx + (int) (-cb.getNodeRadius() * Math.cos(rot)); ay = ty + (int) (-cb.getNodeRadius() * Math.sin(rot)); GraphicsUtils.drawArrowHead(g, fx, fy, tx, ty, ax, ay); } } public boolean contains(JComponent c, int x, int y) { JEdge edge = (JEdge) c; ComputeBounds cb = new ComputeBounds(); cb.g = edge.getGraph(); cb.compute(); Dimension dim = c.getSize(); int fx, fy, tx, ty; switch (findDirection(edge)) { case DIR_NORTH_EAST: fx = cb.getNodeRadius(); fy = dim.height - cb.getNodeRadius() - 1; tx = dim.width - cb.getNodeRadius() - 1; ty = cb.getNodeRadius(); break; case DIR_SOUTH_WEST: fx = dim.width - cb.getNodeRadius() - 1; fy = cb.getNodeRadius(); tx = cb.getNodeRadius(); ty = dim.height - cb.getNodeRadius() - 1; break; case DIR_NORTH_WEST: fx = dim.width - cb.getNodeRadius() - 1; fy = dim.height - cb.getNodeRadius() - 1; tx = cb.getNodeRadius(); ty = cb.getNodeRadius(); break; case DIR_SOUTH_EAST: fx = cb.getNodeRadius(); fy = cb.getNodeRadius(); tx = dim.width - cb.getNodeRadius() - 1; ty = dim.height - cb.getNodeRadius() - 1; break; default: throw new RuntimeException(); } Stroke highlightStroke = new BasicStroke(7.0f * cb.zoom); Shape line = new Line2D.Double(fx, fy, tx, ty); line = highlightStroke.createStrokedShape(line); return line.contains(x, y); } // Assume that edge has two components (from, to) with bounds already set. static Rectangle findEnclosingRectangle(JEdge edge) { Rectangle from = edge.getFrom().getBounds(), to = edge.getTo().getBounds(); int minx = Math.min(from.x, to.x); int miny = Math.min(from.y, to.y); int maxx = Math.max(from.x + from.width, to.x + to.width); int maxy = Math.max(from.y + from.height, to.y + to.height); return new Rectangle(minx, miny, maxx - minx, maxy - miny); } // Assume that edge has two components (from, to) with bounds already set. private static int findDirection(JEdge edge) { Rectangle from = edge.getFrom().getBounds(); Rectangle to = edge.getTo().getBounds(); if (from.x > to.x) { if (from.y > to.y) { return DIR_NORTH_WEST; } else { return DIR_SOUTH_WEST; } } else { if (from.y > to.y) { return DIR_NORTH_EAST; } else { return DIR_SOUTH_EAST; } } } } public void configureEdgeComponent(JEdge c) { c.setUI(basicEdgeUI); } public void configureNodeComponent(JNode c) { c.setUI(basicNodeUI); } public static BasicGraphUI createUI(JComponent c) { return new BasicGraphUI(); } NodeLayout layout = new NodeLayout(); public void installUI(JComponent c) { JGraph g = (JGraph) c; g.setOpaque(true); g.setLayout(layout); g.setForeground(Color.GRAY); g.setBackground(UIManager.getColor("Tree.background")); g.setReadOnlyBackground(UIManager.getColor("Panel.background")); g.setFont(UIManager.getFont("Tree.font")); ComputeBounds cb = new ComputeBounds(); cb.g = g; class Handler implements MouseListener, MouseMotionListener, PropertyChangeListener { int x, y; JNode creatingNode; JNode edgeFromNode; JNode edgeToNode; public void mouseClicked(MouseEvent me) {} public void mouseEntered(MouseEvent e) {} public void mouseMoved(MouseEvent me) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent me) { boolean focus = g.hasFocus(); g.requestFocusInWindow(); int mode = g.getEditMode(); float mx, my; switch (mode) { case JGraph.MODE_VERTEX: case JGraph.MODE_EDGE: cb.compute(); mx = cb.centerComponentToModelX(me.getX()); my = cb.centerComponentToModelY(me.getY()); break; case JGraph.MODE_SELECTION: if (focus && !me.isControlDown() && !me.isShiftDown()) { g.clearSelection(); } default: mx = my = 0.0f; } switch (mode) { case JGraph.MODE_VERTEX: creatingNode = g.startCreatingNode(mx, my); creatingNode.setPressed(true); break; case JGraph.MODE_EDGE: edgeFromNode = g.startCreatingEdgeNode(mx, my); if (edgeFromNode != null) { edgeToNode = g.startCreatingEdge(edgeFromNode, mx, my); edgeToNode.setPressed(true); } break; case JGraph.MODE_ERASE: g.setErasing(true); default: creatingNode = null; } x = me.getX(); y = me.getY(); me.consume(); } public void mouseDragged(MouseEvent me) { int ex = me.getX(); int ey = me.getY(); ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); float deltaX = cb.deltaX(ex - x); float deltaY = cb.deltaY(ey - y); if (creatingNode != null) { creatingNode.setDeltaX(deltaX); creatingNode.setDeltaY(deltaY); me.consume(); } if (edgeToNode != null) { edgeToNode.setDeltaX(deltaX); edgeToNode.setDeltaY(deltaY); me.consume(); } } public void mouseReleased(MouseEvent me) { if (creatingNode != null) { creatingNode.setPressed(false); if (!g.commitCreatingNode(creatingNode)) { g.getToolkit().beep(); } creatingNode = null; me.consume(); } if (edgeToNode != null) { edgeToNode.setPressed(false); if (!g.commitCreatingEdge(edgeToNode)) { g.getToolkit().beep(); } edgeToNode = null; me.consume(); } if (g.isErasing()) { g.setErasing(false); } } public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("showGrid")) g.repaint(); } } Handler h = new Handler(); g.addMouseListener(h); g.addMouseMotionListener(h); g.addPropertyChangeListener(h); // TODO: remove handler at uninstall } public void paint(Graphics gg, JComponent c) { JGraph g = (JGraph) c; if (g.isReadOnly()) { gg.setColor(g.getReadOnlyBackground()); gg.fillRect(0, 0, c.getWidth(), c.getHeight()); } if (!g.getShowGrid()) return; ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); gg.setColor(g.getForeground()); // Draw origin gg.drawLine(cb.modelToCenterComponentX(0.0f), 0, cb.modelToCenterComponentX(0.0f), cb.actual.height); gg.drawLine(0, cb.modelToCenterComponentY(0.0f), cb.actual.width, cb.modelToCenterComponentY(0.0f)); // Draw around (debug) /*int tlX = cb.modelToCenterComponentX(cb.modelMinX); int tlY = cb.modelToCenterComponentY(cb.modelMinY); int brX = cb.modelToCenterComponentX(cb.modelMaxX); int brY = cb.modelToCenterComponentY(cb.modelMaxY); gg.drawRect(tlX, tlY, brX - tlX, brY - tlY);*/ // Draw grid (four quadrants) // Top-left float x = 0.0f; float y = 0.0f; while (true) { int cx = cb.modelToCenterComponentX(x); int cy = cb.modelToCenterComponentY(y); if (x == 0.0f || y == 0.0f) { gg.drawLine(cx - 1, cy, cx + 1, cy); gg.drawLine(cx, cy - 1, cx, cy + 1); } else { gg.drawLine(cx, cy, cx, cy); } if (cy < 0 || cy > cb.actual.height) { break; } if (cx < 0) { x = 0.0f; y -= 1.0f; continue; } else { x -= 1.0f; } } // Top-right x = 1.0f; y = 0.0f; while (true) { int cx = cb.modelToCenterComponentX(x); int cy = cb.modelToCenterComponentY(y); if (x == 0.0f || y == 0.0f) { gg.drawLine(cx - 1, cy, cx + 1, cy); gg.drawLine(cx, cy - 1, cx, cy + 1); } else { gg.drawLine(cx, cy, cx, cy); } if (cy < 0 || cy > cb.actual.height) { break; } if (cx > cb.actual.width) { x = 1.0f; y -= 1.0f; continue; } else { x += 1.0f; } } // Bottom-left x = 0.0f; y = 1.0f; while (true) { int cx = cb.modelToCenterComponentX(x); int cy = cb.modelToCenterComponentY(y); if (x == 0.0f) { gg.drawLine(cx - 1, cy, cx + 1, cy); gg.drawLine(cx, cy - 1, cx, cy + 1); } else { gg.drawLine(cx, cy, cx, cy); } if (cy < 0 || cy > cb.actual.height) { break; } if (cx < 0) { x = 0.0f; y += 1.0f; continue; } else { x -= 1.0f; } } // Bottom-right x = 1.0f; y = 1.0f; while (true) { int cx = cb.modelToCenterComponentX(x); int cy = cb.modelToCenterComponentY(y); gg.drawLine(cx, cy, cx, cy); if (cy < 0 || cy > cb.actual.height) { break; } if (cx > cb.actual.width) { x = 1.0f; y += 1.0f; continue; } else { x += 1.0f; } } } public void uninstallUI(JComponent c) { } static class NodeLayout implements LayoutManager { public void addLayoutComponent(String arg, Component c) { } public void layoutContainer(Container c) { JGraph g = (JGraph) c; ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); int n = g.getComponentCount(); for (int i = 0; i < n; i++) { Component child = g.getComponent(i); if (child instanceof JNode) { JNode node = (JNode) child; Dimension dim = node.getPreferredSize(); node.setBounds( cb.modelToComponentX(node.getModel().getX()), cb.modelToComponentY(node.getModel().getY()), dim.width, dim.height); } } for (int i = 0; i < n; i++) { Component child = g.getComponent(i); if (child instanceof JEdge) { JEdge edge = (JEdge) child; edge.setBounds(BasicEdgeUI.findEnclosingRectangle(edge)); } } } public Dimension minimumLayoutSize(Container c) { JGraph g = (JGraph) c; ComputeBounds cb = new ComputeBounds(); cb.g = g; cb.compute(); return new Dimension(cb.diffX, cb.diffY); } public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public void removeLayoutComponent(Component c) { } } } class ComputeBounds { static final int NODE_DIAMETER = 15; static final int NODE_GRIDUNIT = 22; JGraph g; float zoom; float modelMinX; float modelMaxX; float modelMinY; float modelMaxY; int maxX; int maxY; int minX; int minY; int diffX; int diffY; Dimension actual; int originX; int originY; int shiftX; int shiftY; float getXWithoutDelta(JNode node) { return node.getModel().getXWithoutDelta() * zoom; } float getYWithoutDelta(JNode node) { return node.getModel().getYWithoutDelta() * zoom; } int getScreenXWithoutDelta(JNode node) { return (int) (getXWithoutDelta(node) * NODE_GRIDUNIT); } int getScreenYWithoutDelta(JNode node) { return (int) (getYWithoutDelta(node) * NODE_GRIDUNIT); } int getNodeWidth() { // We need a special number, otherwise our edges are 1 pixel slanted int result = Math.round((float) NODE_DIAMETER * zoom * 2.0f) / 2; if (result - 1 - (result / 2) != (result / 2)) { result++; } return result; } int getNodeHeight() { // We need a special number, otherwise our edges are 1 pixel slanted return getNodeWidth(); } int getNodeRadius() { return getNodeWidth() / 2; } void compute() { zoom = g.getZoomLevel(); computeMin(); computeShift(); } private void computeMin() { maxX = Integer.MIN_VALUE; maxY = Integer.MIN_VALUE; minX = Integer.MAX_VALUE; minY = Integer.MAX_VALUE; modelMaxX = Float.NEGATIVE_INFINITY; modelMinX = Float.POSITIVE_INFINITY; modelMaxY = Float.NEGATIVE_INFINITY; modelMinY = Float.POSITIVE_INFINITY; int n = g.getComponentCount(), en = 0; for (int i = 0; i < n; i++) { Component child = g.getComponent(i); if (child instanceof JNode) { JNode node = (JNode) child; if ((Boolean) node.getClientProperty(JGraph.CLIENT_PROPERTY_TEMPORARY)) continue; en++; float mx, my; mx = getXWithoutDelta(node); my = getYWithoutDelta(node); if (mx > modelMaxX) modelMaxX = mx; if (mx < modelMinX) modelMinX = mx; if (my > modelMaxY) modelMaxY = my; if (my < modelMinY) modelMinY = my; int x, y; x = getScreenXWithoutDelta(node); y = getScreenYWithoutDelta(node); if (x > maxX) maxX = x; if (x < minX) minX = x; if (y > maxY) maxY = y; if (y < minY) minY = y; } } if (en == 0) { maxX = maxY = minX = minY = 0; } maxX += getNodeWidth(); maxY += getNodeHeight(); diffX = maxX - minX; diffY = maxY - minY; } private void computeShift() { actual = g.getSize(); originX = -minX; originY = -minY; if (diffX < actual.width) { shiftX = (actual.width - diffX) / 2; } else { shiftX = 0; } if (diffY < actual.height) { shiftY = (actual.height - diffY) / 2; } else { shiftY = 0; } } int modelToComponentX(float x) { return shiftX + originX + (int) ((x * zoom) * (float) NODE_GRIDUNIT); } int modelToCenterComponentX(float x) { return modelToComponentX(x) + getNodeWidth() / 2; } int modelToComponentY(float y) { return shiftY + originY + (int) ((y * zoom) * (float) NODE_GRIDUNIT); } int modelToCenterComponentY(float y) { return modelToComponentY(y) + getNodeHeight() / 2; } float componentToModelX(int x) { return ((x - modelToComponentX(0.0f)) / zoom) / (float) NODE_GRIDUNIT; } float componentToModelY(int y) { return ((y - modelToComponentY(0.0f)) / zoom) / (float) NODE_GRIDUNIT; } float centerComponentToModelX(int x) { return componentToModelX(x - getNodeWidth() / 2); } float centerComponentToModelY(int y) { return componentToModelY(y - getNodeHeight() / 2); } float deltaX(int dx) { return (dx / zoom) / (float) NODE_GRIDUNIT; } float deltaY(int dy) { return (dy / zoom) / (float) NODE_GRIDUNIT; } float centerDeltaX(int dx) { return deltaX(dx - getNodeWidth() / 2); } float centerDeltaY(int dy) { return deltaY(dy - getNodeHeight() / 2); } }
27,545
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
GraphicsUtils.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/basic/GraphicsUtils.java
package com.aexiz.daviz.ui.swing.plaf.basic; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; class GraphicsUtils { private static final Shape ARROW_HEAD = initArrowHead(); static void initializeGraphics(Graphics g) { if (g instanceof Graphics2D) { initializeGraphics((Graphics2D) g); } } static void initializeGraphics(Graphics2D g) { RenderingHints rh = new RenderingHints( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHints(rh); } static void drawArrowHead(Graphics g, int fx, int fy, int tx, int ty, int ax, int ay) { if (g instanceof Graphics2D) { drawArrowHead((Graphics2D) g, fx, fy, tx, ty, ax, ay); } } static void drawArrowHead(Graphics2D g, int fx, int fy, int tx, int ty, int ax, int ay) { double rot = Math.atan2(ty - fy, tx - fx); AffineTransform at = g.getTransform(); g.translate(ax, ay); g.rotate(rot); g.fill(ARROW_HEAD); g.setTransform(at); } private static Shape initArrowHead() { Path2D.Float path = new Path2D.Float(); path.moveTo(0.0f, 0.0f); path.lineTo(-4f, 5.0f); path.lineTo(-4f, -4.0f); path.closePath(); return path; } }
1,432
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
BasicInfoTableUI.java
/FileExtraction/Java_unseen/praalhans_DaViz/src/java/com/aexiz/daviz/ui/swing/plaf/basic/BasicInfoTableUI.java
package com.aexiz.daviz.ui.swing.plaf.basic; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIManager; import com.aexiz.daviz.ui.swing.JInfoTable; import com.aexiz.daviz.ui.swing.InfoModel.PropertyModel; import com.aexiz.daviz.ui.swing.plaf.InfoTableUI; public class BasicInfoTableUI extends InfoTableUI { static final int DEPTH_SIZE = 12; GridBagLayout layout = new GridBagLayout(); // Called by reflection code public static BasicInfoTableUI createUI(JComponent c) { return new BasicInfoTableUI(); } public void configureLabelComponent(JLabel c) { } public void configureSimplePropertyComponent(JTextField c) { c.setMinimumSize(new Dimension(20, 20)); c.setPreferredSize(new Dimension(20, 20)); } public void configureNestedPlaceholderComponent(JComponent c) { c.setMinimumSize(new Dimension(20, 20)); c.setPreferredSize(new Dimension(20, 20)); } public void installUI(JComponent c) { c.setOpaque(false); c.setLayout(layout); c.setBackground(UIManager.getColor("Control.background")); c.setFont(UIManager.getFont("Tree.font")); c.setBorder(BorderFactory.createEmptyBorder(3, 3, 4, 2)); } public void uninstallUI(JComponent c) { } private int computeDepth(PropertyModel model) { int result = 0; Object parent = model.getParent(); while (parent instanceof PropertyModel) { result++; parent = ((PropertyModel) parent).getParent(); } return result; } public void addComponent(JInfoTable c, JComponent child) { String kind = child.getClientProperty(JInfoTable.CLIENT_PROPERTY_KIND).toString(); GridBagConstraints con = new GridBagConstraints(); con.insets.top = 1; con.insets.left = 1; con.insets.right = 1; if (kind.equals(JInfoTable.KIND_LABEL)) { PropertyModel model = (PropertyModel) child.getClientProperty(JInfoTable.CLIENT_PROPERTY_MODEL); int y = c.getVisibleIndex(model); con.fill = GridBagConstraints.HORIZONTAL; con.anchor = GridBagConstraints.LINE_START; con.weightx = 0.1; con.gridy = y; con.gridx = 0; con.insets.left += computeDepth(model) * DEPTH_SIZE; } else if (kind.equals(JInfoTable.KIND_VALUE)) { PropertyModel model = (PropertyModel) child.getClientProperty(JInfoTable.CLIENT_PROPERTY_MODEL); int y = c.getVisibleIndex(model); con.fill = GridBagConstraints.HORIZONTAL; con.weightx = 1.0; con.gridy = y; con.gridx = 1; } else if (kind.equals(JInfoTable.KIND_FILLER)) { con.gridx = 0; con.gridy = c.getVisibleIndexCount(); con.gridwidth = 2; con.weightx = 1.0; con.weighty = 1.0; } else throw new Error(); c.add(child, con); } }
2,891
Java
.java
praalhans/DaViz
10
2
0
2019-12-09T10:03:20Z
2020-03-19T17:32:03Z
TestSignedness.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/test/java/org/phlo/audio/TestSignedness.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; import org.junit.*; public class TestSignedness { @Test public void testSignedInt() { Assert.assertEquals(0, Signedness.Signed.intToUnsignedInt(Integer.MIN_VALUE)); Assert.assertEquals(0x7fffffff, Signedness.Signed.intToUnsignedInt(-1)); Assert.assertEquals(0x80000000, Signedness.Signed.intToUnsignedInt(0)); Assert.assertEquals(0x80000001, Signedness.Signed.intToUnsignedInt(1)); Assert.assertEquals(0xffffffff, Signedness.Signed.intToUnsignedInt(Integer.MAX_VALUE)); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Signed.intToSignedInt(Integer.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.intToSignedInt(-1)); Assert.assertEquals(0, Signedness.Signed.intToSignedInt(0)); Assert.assertEquals(1, Signedness.Signed.intToSignedInt(1)); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Signed.intToSignedInt(Integer.MAX_VALUE)); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Signed.intFromUnsignedInt(0x0)); Assert.assertEquals(-1, Signedness.Signed.intFromUnsignedInt(0x7fffffff)); Assert.assertEquals(0, Signedness.Signed.intFromUnsignedInt(0x80000000)); Assert.assertEquals(1, Signedness.Signed.intFromUnsignedInt(0x80000001)); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Signed.intFromUnsignedInt(0xffffffff)); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Signed.intFromSignedInt(Integer.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.intFromSignedInt(-1)); Assert.assertEquals(0, Signedness.Signed.intFromSignedInt(0)); Assert.assertEquals(1, Signedness.Signed.intFromSignedInt(1)); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Signed.intFromSignedInt(Integer.MAX_VALUE)); Assert.assertEquals((float)Integer.MIN_VALUE, Signedness.Signed.intToFloat(Integer.MIN_VALUE), 0.0f); Assert.assertEquals(-1.0f, Signedness.Signed.intToFloat(-1), 0.0f); Assert.assertEquals(0.0f, Signedness.Signed.intToFloat(0), 0.0f); Assert.assertEquals(1.0f, Signedness.Signed.intToFloat(1), 0.0f); Assert.assertEquals((float)Integer.MAX_VALUE, Signedness.Signed.intToFloat(Integer.MAX_VALUE), 0.0f); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Signed.intFromFloat((float)Integer.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.intFromFloat(-1.0f)); Assert.assertEquals(0, Signedness.Signed.intFromFloat(0.0f)); Assert.assertEquals(1, Signedness.Signed.intFromFloat(1.0f)); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Signed.intFromFloat((float)Integer.MAX_VALUE)); Assert.assertEquals(-1.0f, Signedness.Signed.intToNormalizedFloat(Integer.MIN_VALUE), 0.0f); Assert.assertEquals(0.0f, Signedness.Signed.intToNormalizedFloat(0), 0.0f); Assert.assertEquals(1.0f, Signedness.Signed.intToNormalizedFloat(Integer.MAX_VALUE), 0.0f); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Signed.intFromNormalizedFloat(-1.0f)); Assert.assertEquals(Integer.MIN_VALUE + 128, Signedness.Signed.intFromNormalizedFloat(Math.nextUp(-1.0f))); Assert.assertEquals(0, Signedness.Signed.intFromNormalizedFloat(0.0f)); Assert.assertEquals(Integer.MAX_VALUE - 127, Signedness.Signed.intFromNormalizedFloat(-Math.nextUp(-1.0f))); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Signed.intFromNormalizedFloat(1.0f)); } @Test public void testSignedShort() { Assert.assertEquals((short)0, Signedness.Signed.shortToUnsignedShort(Short.MIN_VALUE)); Assert.assertEquals((short)0x7fff, Signedness.Signed.shortToUnsignedShort((short)-1)); Assert.assertEquals((short)0x8000, Signedness.Signed.shortToUnsignedShort((short)0)); Assert.assertEquals((short)0x8001, Signedness.Signed.shortToUnsignedShort((short)1)); Assert.assertEquals((short)0xffff, Signedness.Signed.shortToUnsignedShort(Short.MAX_VALUE)); Assert.assertEquals(Short.MIN_VALUE, Signedness.Signed.shortToSignedShort(Short.MIN_VALUE)); Assert.assertEquals((short)-1, Signedness.Signed.shortToSignedShort((short)-1)); Assert.assertEquals((short)0, Signedness.Signed.shortToSignedShort((short)0)); Assert.assertEquals((short)1, Signedness.Signed.shortToSignedShort((short)1)); Assert.assertEquals(Short.MAX_VALUE, Signedness.Signed.shortToSignedShort(Short.MAX_VALUE)); Assert.assertEquals(Short.MIN_VALUE, Signedness.Signed.shortFromUnsignedShort((short)0x0)); Assert.assertEquals((short)-1, Signedness.Signed.shortFromUnsignedShort((short)0x7fff)); Assert.assertEquals((short)0, Signedness.Signed.shortFromUnsignedShort((short)0x8000)); Assert.assertEquals((short)1, Signedness.Signed.shortFromUnsignedShort((short)0x8001)); Assert.assertEquals(Short.MAX_VALUE, Signedness.Signed.shortFromUnsignedShort((short)0xffff)); Assert.assertEquals(Short.MIN_VALUE, Signedness.Signed.shortFromSignedShort(Short.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.shortFromSignedShort((short)-1)); Assert.assertEquals(0, Signedness.Signed.shortFromSignedShort((short)0)); Assert.assertEquals(1, Signedness.Signed.shortFromSignedShort((short)1)); Assert.assertEquals(Short.MAX_VALUE, Signedness.Signed.shortFromSignedShort(Short.MAX_VALUE)); Assert.assertEquals((float)Short.MIN_VALUE, Signedness.Signed.shortToFloat(Short.MIN_VALUE), 0.0f); Assert.assertEquals(-1.0f, Signedness.Signed.shortToFloat((short)-1), 0.0f); Assert.assertEquals(0.0f, Signedness.Signed.shortToFloat((short)0), 0.0f); Assert.assertEquals(1.0f, Signedness.Signed.shortToFloat((short)1), 0.0f); Assert.assertEquals((float)Short.MAX_VALUE, Signedness.Signed.shortToFloat(Short.MAX_VALUE), 0.0f); Assert.assertEquals(Short.MIN_VALUE, Signedness.Signed.shortFromFloat((float)Short.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.shortFromFloat(-1.0f)); Assert.assertEquals(0, Signedness.Signed.shortFromFloat(0.0f)); Assert.assertEquals(1, Signedness.Signed.shortFromFloat(1.0f)); Assert.assertEquals(Short.MAX_VALUE, Signedness.Signed.shortFromFloat((float)Short.MAX_VALUE)); Assert.assertEquals(-1.0f, Signedness.Signed.shortToNormalizedFloat(Short.MIN_VALUE), 0.0f); Assert.assertEquals(Math.scalb(1.0f, -16), Signedness.Signed.shortToNormalizedFloat((short)0), 1e-8); Assert.assertEquals(1.0f, Signedness.Signed.shortToNormalizedFloat(Short.MAX_VALUE), 0.0f); Assert.assertEquals(Short.MIN_VALUE, Signedness.Signed.shortFromNormalizedFloat(-1.0f)); Assert.assertEquals(Short.MIN_VALUE + 1, Signedness.Signed.shortFromNormalizedFloat(-1.0f + Math.scalb(1.0f, -16))); Assert.assertEquals((short)0, Signedness.Signed.shortFromNormalizedFloat(-Math.scalb(1.0f, -17))); Assert.assertEquals((short)0, Signedness.Signed.shortFromNormalizedFloat(0.0f)); Assert.assertEquals((short)0, Signedness.Signed.shortFromNormalizedFloat(Math.scalb(1.0f, -17))); Assert.assertEquals(Short.MAX_VALUE - 1, Signedness.Signed.shortFromNormalizedFloat(1.0f - Math.scalb(1.0f, -16))); Assert.assertEquals(Short.MAX_VALUE, Signedness.Signed.shortFromNormalizedFloat(1.0f)); } @Test public void testSignedByte() { Assert.assertEquals((byte)0, Signedness.Signed.byteToUnsignedByte(Byte.MIN_VALUE)); Assert.assertEquals((byte)0x7f, Signedness.Signed.byteToUnsignedByte((byte)-1)); Assert.assertEquals((byte)0x80, Signedness.Signed.byteToUnsignedByte((byte)0)); Assert.assertEquals((byte)0x81, Signedness.Signed.byteToUnsignedByte((byte)1)); Assert.assertEquals((byte)0xff, Signedness.Signed.byteToUnsignedByte(Byte.MAX_VALUE)); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Signed.byteToSignedByte(Byte.MIN_VALUE)); Assert.assertEquals((byte)-1, Signedness.Signed.byteToSignedByte((byte)-1)); Assert.assertEquals((byte)0, Signedness.Signed.byteToSignedByte((byte)0)); Assert.assertEquals((byte)1, Signedness.Signed.byteToSignedByte((byte)1)); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Signed.byteToSignedByte(Byte.MAX_VALUE)); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Signed.byteFromUnsignedByte((byte)0x0)); Assert.assertEquals((byte)-1, Signedness.Signed.byteFromUnsignedByte((byte)0x7f)); Assert.assertEquals((byte)0, Signedness.Signed.byteFromUnsignedByte((byte)0x80)); Assert.assertEquals((byte)1, Signedness.Signed.byteFromUnsignedByte((byte)0x81)); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Signed.byteFromUnsignedByte((byte)0xff)); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Signed.byteFromSignedByte(Byte.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.byteFromSignedByte((byte)-1)); Assert.assertEquals(0, Signedness.Signed.byteFromSignedByte((byte)0)); Assert.assertEquals(1, Signedness.Signed.byteFromSignedByte((byte)1)); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Signed.byteFromSignedByte(Byte.MAX_VALUE)); Assert.assertEquals((float)Byte.MIN_VALUE, Signedness.Signed.byteToFloat(Byte.MIN_VALUE), 0.0f); Assert.assertEquals(-1.0f, Signedness.Signed.byteToFloat((byte)-1), 0.0f); Assert.assertEquals(0.0f, Signedness.Signed.byteToFloat((byte)0), 0.0f); Assert.assertEquals(1.0f, Signedness.Signed.byteToFloat((byte)1), 0.0f); Assert.assertEquals((float)Byte.MAX_VALUE, Signedness.Signed.byteToFloat(Byte.MAX_VALUE), 0.0f); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Signed.byteFromFloat((float)Byte.MIN_VALUE)); Assert.assertEquals(-1, Signedness.Signed.byteFromFloat(-1.0f)); Assert.assertEquals(0, Signedness.Signed.byteFromFloat(0.0f)); Assert.assertEquals(1, Signedness.Signed.byteFromFloat(1.0f)); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Signed.byteFromFloat((float)Byte.MAX_VALUE)); Assert.assertEquals(-1.0f, Signedness.Signed.byteToNormalizedFloat(Byte.MIN_VALUE), 0.0f); Assert.assertEquals(Math.scalb(1.0f, -8), Signedness.Signed.byteToNormalizedFloat((byte)0), 1e-4); Assert.assertEquals(1.0f, Signedness.Signed.byteToNormalizedFloat(Byte.MAX_VALUE), 0.0f); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Signed.byteFromNormalizedFloat(-1.0f)); Assert.assertEquals(Byte.MIN_VALUE + 1, Signedness.Signed.byteFromNormalizedFloat(-1.0f + Math.scalb(1.0f, -8))); Assert.assertEquals((byte)0, Signedness.Signed.byteFromNormalizedFloat(-Math.scalb(1.0f, -9))); Assert.assertEquals((byte)0, Signedness.Signed.byteFromNormalizedFloat(0.0f)); Assert.assertEquals((byte)0, Signedness.Signed.byteFromNormalizedFloat(Math.scalb(1.0f, -9))); Assert.assertEquals(Byte.MAX_VALUE - 1, Signedness.Signed.byteFromNormalizedFloat(1.0f - Math.scalb(1.0f, -8))); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Signed.byteFromNormalizedFloat(1.0f)); } @Test public void testUnsignedInt() { Assert.assertEquals(0x0, Signedness.Unsigned.intToUnsignedInt(0x0)); Assert.assertEquals(0x7fffffff, Signedness.Unsigned.intToUnsignedInt(0x7fffffff)); Assert.assertEquals(0x80000000, Signedness.Unsigned.intToUnsignedInt(0x80000000)); Assert.assertEquals(0x80000001, Signedness.Unsigned.intToUnsignedInt(0x80000001)); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intToUnsignedInt(0xffffffff)); Assert.assertEquals(Integer.MIN_VALUE, Signedness.Unsigned.intToSignedInt(0x0)); Assert.assertEquals(-1, Signedness.Unsigned.intToSignedInt(0x7fffffff)); Assert.assertEquals(0, Signedness.Unsigned.intToSignedInt(0x80000000)); Assert.assertEquals(1, Signedness.Unsigned.intToSignedInt(0x80000001)); Assert.assertEquals(Integer.MAX_VALUE, Signedness.Unsigned.intToSignedInt(0xffffffff)); Assert.assertEquals(0x0, Signedness.Unsigned.intFromUnsignedInt(0x0)); Assert.assertEquals(0x7fffffff, Signedness.Unsigned.intFromUnsignedInt(0x7fffffff)); Assert.assertEquals(0x80000000, Signedness.Unsigned.intFromUnsignedInt(0x80000000)); Assert.assertEquals(0x80000001, Signedness.Unsigned.intFromUnsignedInt(0x80000001)); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intFromUnsignedInt(0xffffffff)); Assert.assertEquals(0, Signedness.Unsigned.intFromSignedInt(Integer.MIN_VALUE)); Assert.assertEquals(0x7fffffff, Signedness.Unsigned.intFromSignedInt(-1)); Assert.assertEquals(0x80000000, Signedness.Unsigned.intFromSignedInt(0)); Assert.assertEquals(0x80000001, Signedness.Unsigned.intFromSignedInt(1)); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intFromSignedInt(Integer.MAX_VALUE)); Assert.assertEquals(0.0f, Signedness.Unsigned.intToFloat(0x0), 0.0f); Assert.assertEquals(2147483647.0f, Signedness.Unsigned.intToFloat(0x7fffffff), 0.0f); Assert.assertEquals(2147483648.0f, Signedness.Unsigned.intToFloat(0x80000000), 0.0f); Assert.assertEquals(2147483649.0f, Signedness.Unsigned.intToFloat(0x80000001), 0.0f); Assert.assertEquals(4294967295.0f, Signedness.Unsigned.intToFloat(0xffffffff), 0.0f); /* The cases 0x7fffffff and 0x80000001 would because floats store only 24 significant * digits, not 32. This is ok, so we simply leave these cases out */ Assert.assertEquals(0x0, Signedness.Unsigned.intFromFloat(0.0f)); Assert.assertEquals(0x80000000, Signedness.Unsigned.intFromFloat(2147483648.0f)); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intFromFloat(4294967295.0f)); Assert.assertEquals(-1.0f, Signedness.Unsigned.intToNormalizedFloat(0x0), 0.0f); Assert.assertEquals(0.0f, Signedness.Unsigned.intToNormalizedFloat(0x80000000), 0.0f); Assert.assertEquals(1.0f, Signedness.Unsigned.intToNormalizedFloat(0xffffffff), 0.0f); Assert.assertEquals(0x0, Signedness.Unsigned.intFromNormalizedFloat(-1.0f)); Assert.assertEquals(0x00000080, Signedness.Unsigned.intFromNormalizedFloat(Math.nextUp(-1.0f))); Assert.assertEquals(0x80000000, Signedness.Unsigned.intFromNormalizedFloat(0.0f)); Assert.assertEquals(0xffffff00, Signedness.Unsigned.intFromNormalizedFloat(-Math.nextUp(Math.nextUp(-1.0f)))); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intFromNormalizedFloat(-Math.nextUp(-1.0f))); Assert.assertEquals(0xffffffff, Signedness.Unsigned.intFromNormalizedFloat(1.0f)); } @Test public void testUnsignedShort() { Assert.assertEquals((short)0x0, Signedness.Unsigned.shortToUnsignedShort((short)0x0)); Assert.assertEquals((short)0x7fff, Signedness.Unsigned.shortToUnsignedShort((short)0x7fff)); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortToUnsignedShort((short)0x8000)); Assert.assertEquals((short)0x8001, Signedness.Unsigned.shortToUnsignedShort((short)0x8001)); Assert.assertEquals((short)0xffff, Signedness.Unsigned.shortToUnsignedShort((short)0xffff)); Assert.assertEquals(Short.MIN_VALUE, Signedness.Unsigned.shortToSignedShort((short)0x0)); Assert.assertEquals((short)-1, Signedness.Unsigned.shortToSignedShort((short)0x7fff)); Assert.assertEquals((short)0, Signedness.Unsigned.shortToSignedShort((short)0x8000)); Assert.assertEquals((short)1, Signedness.Unsigned.shortToSignedShort((short)0x8001)); Assert.assertEquals(Short.MAX_VALUE, Signedness.Unsigned.shortToSignedShort((short)0xffff)); Assert.assertEquals((short)0x0, Signedness.Unsigned.shortFromUnsignedShort((short)0x0)); Assert.assertEquals((short)0x7fff, Signedness.Unsigned.shortFromUnsignedShort((short)0x7fff)); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromUnsignedShort((short)0x8000)); Assert.assertEquals((short)0x8001, Signedness.Unsigned.shortFromUnsignedShort((short)0x8001)); Assert.assertEquals((short)0xffff, Signedness.Unsigned.shortFromUnsignedShort((short)0xffff)); Assert.assertEquals((short)0, Signedness.Unsigned.shortFromSignedShort(Short.MIN_VALUE)); Assert.assertEquals((short)0x7fff, Signedness.Unsigned.shortFromSignedShort((short)-1)); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromSignedShort((short)0)); Assert.assertEquals((short)0x8001, Signedness.Unsigned.shortFromSignedShort((short)1)); Assert.assertEquals((short)0xffff, Signedness.Unsigned.shortFromSignedShort(Short.MAX_VALUE)); Assert.assertEquals(0.0f, Signedness.Unsigned.shortToFloat((short)0x0), 0.0f); Assert.assertEquals(32767.0f, Signedness.Unsigned.shortToFloat((short)0x7fff), 0.0f); Assert.assertEquals(32768.0f, Signedness.Unsigned.shortToFloat((short)0x8000), 0.0f); Assert.assertEquals(32769.0f, Signedness.Unsigned.shortToFloat((short)0x8001), 0.0f); Assert.assertEquals(65535.0f, Signedness.Unsigned.shortToFloat((short)0xffff), 0.0f); Assert.assertEquals((short)0x0, Signedness.Unsigned.shortFromFloat(0.0f)); Assert.assertEquals((short)0x7fff, Signedness.Unsigned.shortFromFloat(32767.0f)); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromFloat(32768.0f)); Assert.assertEquals((short)0x8001, Signedness.Unsigned.shortFromFloat(32769.0f)); Assert.assertEquals((short)0xffff, Signedness.Unsigned.shortFromFloat(65535.0f)); Assert.assertEquals(-1.0f, Signedness.Unsigned.shortToNormalizedFloat((short)0x0), 0.0f); Assert.assertEquals(Math.scalb(1.0f, -16), Signedness.Unsigned.shortToNormalizedFloat((short)0x8000), 1e-8); Assert.assertEquals(1.0f, Signedness.Unsigned.shortToNormalizedFloat((short)0xffff), 0.0f); Assert.assertEquals(0x0, Signedness.Unsigned.shortFromNormalizedFloat(-1.0f)); Assert.assertEquals(0x1, Signedness.Unsigned.shortFromNormalizedFloat(-1.0f + Math.scalb(1.0f, -16))); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromNormalizedFloat(-Math.scalb(1.0f, -17))); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromNormalizedFloat(0.0f)); Assert.assertEquals((short)0x8000, Signedness.Unsigned.shortFromNormalizedFloat(Math.scalb(1.0f, -17))); Assert.assertEquals((short)0xfffe, Signedness.Unsigned.shortFromNormalizedFloat(1.0f - Math.scalb(1.0f, -16))); Assert.assertEquals((short)0xffff, Signedness.Unsigned.shortFromNormalizedFloat(1.0f)); } @Test public void testUnsignedByte() { Assert.assertEquals((byte)0x0, Signedness.Unsigned.byteToUnsignedByte((byte)0x0)); Assert.assertEquals((byte)0x7f, Signedness.Unsigned.byteToUnsignedByte((byte)0x7f)); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteToUnsignedByte((byte)0x80)); Assert.assertEquals((byte)0x81, Signedness.Unsigned.byteToUnsignedByte((byte)0x81)); Assert.assertEquals((byte)0xff, Signedness.Unsigned.byteToUnsignedByte((byte)0xff)); Assert.assertEquals(Byte.MIN_VALUE, Signedness.Unsigned.byteToSignedByte((byte)0x0)); Assert.assertEquals((byte)-1, Signedness.Unsigned.byteToSignedByte((byte)0x7f)); Assert.assertEquals((byte)0, Signedness.Unsigned.byteToSignedByte((byte)0x80)); Assert.assertEquals((byte)1, Signedness.Unsigned.byteToSignedByte((byte)0x81)); Assert.assertEquals(Byte.MAX_VALUE, Signedness.Unsigned.byteToSignedByte((byte)0xff)); Assert.assertEquals((byte)0x0, Signedness.Unsigned.byteFromUnsignedByte((byte)0x0)); Assert.assertEquals((byte)0x7f, Signedness.Unsigned.byteFromUnsignedByte((byte)0x7f)); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromUnsignedByte((byte)0x80)); Assert.assertEquals((byte)0x81, Signedness.Unsigned.byteFromUnsignedByte((byte)0x81)); Assert.assertEquals((byte)0xff, Signedness.Unsigned.byteFromUnsignedByte((byte)0xff)); Assert.assertEquals((byte)0, Signedness.Unsigned.byteFromSignedByte(Byte.MIN_VALUE)); Assert.assertEquals((byte)0x7f, Signedness.Unsigned.byteFromSignedByte((byte)-1)); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromSignedByte((byte)0)); Assert.assertEquals((byte)0x81, Signedness.Unsigned.byteFromSignedByte((byte)1)); Assert.assertEquals((byte)0xff, Signedness.Unsigned.byteFromSignedByte(Byte.MAX_VALUE)); Assert.assertEquals(0.0f, Signedness.Unsigned.byteToFloat((byte)0x0), 0.0f); Assert.assertEquals(127.0f, Signedness.Unsigned.byteToFloat((byte)0x7f), 0.0f); Assert.assertEquals(128.0f, Signedness.Unsigned.byteToFloat((byte)0x80), 0.0f); Assert.assertEquals(129.0f, Signedness.Unsigned.byteToFloat((byte)0x81), 0.0f); Assert.assertEquals(255.0f, Signedness.Unsigned.byteToFloat((byte)0xff), 0.0f); Assert.assertEquals((byte)0x0, Signedness.Unsigned.byteFromFloat(0.0f)); Assert.assertEquals((byte)0x7f, Signedness.Unsigned.byteFromFloat(127.0f)); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromFloat(128.0f)); Assert.assertEquals((byte)0x81, Signedness.Unsigned.byteFromFloat(129.0f)); Assert.assertEquals((byte)0xff, Signedness.Unsigned.byteFromFloat(255.0f)); Assert.assertEquals(-1.0f, Signedness.Unsigned.byteToNormalizedFloat((byte)0x0), 0.0f); Assert.assertEquals(Math.scalb(1.0f, -8), Signedness.Unsigned.byteToNormalizedFloat((byte)0x80), 1e-4); Assert.assertEquals(1.0f, Signedness.Unsigned.byteToNormalizedFloat((byte)0xff), 0.0f); Assert.assertEquals(0x0, Signedness.Unsigned.byteFromNormalizedFloat(-1.0f)); Assert.assertEquals(0x1, Signedness.Unsigned.byteFromNormalizedFloat(-1.0f + Math.scalb(1.0f, -8))); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromNormalizedFloat(-Math.scalb(1.0f, -9))); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromNormalizedFloat(0.0f)); Assert.assertEquals((byte)0x80, Signedness.Unsigned.byteFromNormalizedFloat(Math.scalb(1.0f, -9))); Assert.assertEquals((byte)0xfe, Signedness.Unsigned.byteFromNormalizedFloat(1.0f - Math.scalb(1.0f, -8))); Assert.assertEquals((byte)0xff, Signedness.Unsigned.byteFromNormalizedFloat(1.0f)); } }
21,735
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
TestSampleBuffer.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/test/java/org/phlo/audio/TestSampleBuffer.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import org.junit.*; public class TestSampleBuffer { @Test public void testInterleavedBigEndianUnsignedInteger16() { SampleDimensions byteDimensions = new SampleDimensions(4, 3); SampleDimensions sampleDimensions = new SampleDimensions(2, 4); SampleByteBufferFormat byteFormat = new SampleByteBufferFormat(SampleBufferLayout.Interleaved, ByteOrder.BIG_ENDIAN, SampleByteFormat.UnsignedInteger16); byte[] bytes = { /* channel 0 */ /* channel 1 */ /* channel 2 */ /* channel 3 */ (byte)0x00, (byte) 0x00, (byte)0x80, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte) 0x00, (byte)0xff, (byte)0xfe, (byte)0x80, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte) 0x00, (byte)0x00, (byte)0x01, (byte)0xff, (byte)0xfe, (byte)0x00, (byte)0x00, }; int[] ints = { /* channel 0 */ /* channel 1 */ /* channel 2 */ /* channel 3 */ 0x0000, 0x8000, 0x0001, 0x0000, 0x0000, 0xfffe, 0x8000, 0x0000, 0x0000, 0x0001, 0xfffe, 0x0000 }; ByteBuffer bytesWrapped = byteFormat.wrapBytes(bytes); IntBuffer intsWrapped = IntBuffer.wrap(ints); float U = Math.scalb(1.0f, -15); float[][] values = { /* channel 0 */ { 0.0f, U * 0.5f, 1.0f - U, -1.0f + U }, /* channel 1 */ { 0.0f, -1.0f + U, U * 0.5f, 1.0f - U }, }; SampleBuffer sampleBufferFromBytes = new SampleBuffer(sampleDimensions); sampleBufferFromBytes.slice(new SampleOffset(0, 1), null).copyFrom( bytesWrapped, byteDimensions, new SampleRange(new SampleOffset(1, 0), new SampleDimensions(2, 3)), byteFormat ); SampleBuffer sampleBufferFromInts = new SampleBuffer(sampleDimensions); sampleBufferFromInts.slice(new SampleOffset(0, 1), null).copyFrom( intsWrapped, byteDimensions, new SampleRange(new SampleOffset(1, 0), new SampleDimensions(2, 3)), byteFormat.layout, byteFormat.sampleFormat.getSignedness() ); for(int c=0; c < sampleDimensions.channels; ++c) { for(int s=0; s < sampleDimensions.samples; ++s) { Assert.assertEquals("[" + c + "," + s + "]", values[c][s], sampleBufferFromBytes.getSample(c,s), 1e-8); Assert.assertEquals("[" + c + "," + s + "]", values[c][s], sampleBufferFromInts.getSample(c,s), 1e-8); } } ByteBuffer byteBuffer = byteFormat.allocateBuffer(byteDimensions); sampleBufferFromBytes.slice(new SampleOffset(0, 1), new SampleDimensions(2, 3)).copyTo( byteBuffer, byteDimensions, new SampleOffset(1, 0), byteFormat ); Assert.assertEquals(bytesWrapped.capacity(), byteBuffer.capacity()); Assert.assertEquals(0, byteBuffer.compareTo(bytesWrapped)); } @Test public void testBandedLittleEndianSignedInteger16() { SampleDimensions byteDimensions = new SampleDimensions(4, 3); SampleDimensions sampleDimensions = new SampleDimensions(2, 4); SampleByteBufferFormat byteFormat = new SampleByteBufferFormat(SampleBufferLayout.Banded, ByteOrder.LITTLE_ENDIAN, SampleByteFormat.SignedInteger16); byte[] bytes = { /* channel 0 */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, /* channel 1 */ (byte)0x00, (byte)0x80, (byte)0xfe, (byte)0xff, (byte)0x01, (byte)0x00, /* channel 2 */ (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x80, (byte)0xfe, (byte)0xff, /* channel 3 */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }; int[] ints = { /* channel 0 */ 0x0000, 0x0000, 0x0000, /* channel 1 */ 0x8000, 0xfffe, 0x0001, /* channel 2 */ 0x0001, 0x8000, 0xfffe, /* channel 3 */ 0x0000, 0x0000, 0x0000, }; ByteBuffer bytesWrapped = byteFormat.wrapBytes(bytes); IntBuffer intsWrapped = IntBuffer.wrap(ints); float U = Math.scalb(1.0f, -15); float[][] values = { /* channel 1 */ { 0.0f, -1.0f + 0, -U * 1.5f, U * 1.5f }, /* channel 2 */ { 0.0f, U * 1.5f, -1.0f + 0, -U * 1.5f }, }; SampleBuffer sampleBufferFromBytes = new SampleBuffer(sampleDimensions); sampleBufferFromBytes.slice(new SampleOffset(0, 1), null).copyFrom( bytesWrapped, byteDimensions, new SampleRange(new SampleOffset(1, 0), new SampleDimensions(2, 3)), byteFormat ); SampleBuffer sampleBufferFromInts = new SampleBuffer(sampleDimensions); sampleBufferFromInts.slice(new SampleOffset(0, 1), null).copyFrom( intsWrapped, byteDimensions, new SampleRange(new SampleOffset(1, 0), new SampleDimensions(2, 3)), byteFormat.layout, byteFormat.sampleFormat.getSignedness() ); for(int c=0; c < sampleDimensions.channels; ++c) { for(int s=0; s < sampleDimensions.samples; ++s) { Assert.assertEquals("[" + c + "," + s + "]", values[c][s], sampleBufferFromBytes.getSample(c,s), 1e-8); Assert.assertEquals("[" + c + "," + s + "]", values[c][s], sampleBufferFromInts.getSample(c,s), 1e-8); } } ByteBuffer byteBuffer = byteFormat.allocateBuffer(byteDimensions); sampleBufferFromBytes.slice(new SampleOffset(0, 1), new SampleDimensions(2, 3)).copyTo( byteBuffer, byteDimensions, new SampleOffset(1, 0), byteFormat ); Assert.assertEquals(bytesWrapped.capacity(), byteBuffer.capacity()); Assert.assertEquals(0, byteBuffer.compareTo(bytesWrapped)); } }
6,057
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
TestJavaSoundSink.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/test/java/org/phlo/audio/TestJavaSoundSink.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; public class TestJavaSoundSink { public static void main(String[] args) throws Exception { final double sampleRate = 44100; final double frequencyLeft = 500; final double frequencyRight = frequencyLeft * 1.01; final SampleBuffer sine = new SampleBuffer(new SampleDimensions(2, (int)(sampleRate / 10))); JavaSoundSink sink = new JavaSoundSink(44100, 2, new SampleSource() { @Override public SampleBuffer getSampleBuffer(double timeStamp) { timeStamp -= 0.01; for(int i=0; i < sine.getDimensions().samples; ++i) { sine.setSample(0, i, (float)Math.sin(2.0 * Math.PI * frequencyLeft * (timeStamp + (double)i / sampleRate))); sine.setSample(1, i, (float)Math.sin(2.0 * Math.PI * frequencyRight * (timeStamp + (double)i / sampleRate))); } sine.setTimeStamp(timeStamp); return sine; } }); sink.setStartTime(sink.getNextTime() + 1.0); Thread.sleep(Math.round(1.5e4)); sink.close(); } }
1,662
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
TestFunctions.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/test/java/org/phlo/audio/TestFunctions.java
package org.phlo.audio; import org.junit.*; public class TestFunctions { public float resultFloat; public double resultDouble; @Test public void testSincDouble() { double x = Double.MIN_VALUE; Assert.assertEquals(Functions.sinc(x), 1.0, 0.0); while (x < 1.0) { Assert.assertEquals("x=" + x, Taylor.sinc(x), Functions.sinc(x), 1e-15); x = x * 1.1 + Math.ulp(x); } } @Test public void testSincFloat() { float x = Float.MIN_VALUE; Assert.assertEquals(Functions.sinc(x), 1.0f, 0.0); while (x < 1.0f) { Assert.assertEquals("x=" + x, (float)Taylor.sinc(x), Functions.sinc(x), 1e-7f); x = x * 1.1f + Math.ulp(x); } } private static final int TestSincPerformanceN = 100000; @Test public void testSincFloatPerformance() { double sincOverhead = Float.POSITIVE_INFINITY; double sincWithOverhead = Float.POSITIVE_INFINITY; for(int n=0; n < 10; ++n) { resultDouble = 0; long startNanos = System.nanoTime(); for(int i=2; i <= (TestSincPerformanceN + 1); ++i) { resultFloat += 1.0f / (float)i; } long overheadNanos = System.nanoTime(); for(int i=2; i <= (TestSincPerformanceN + 1); ++i) { resultFloat += Functions.sinc(1.0f / (float)i); } long endNanos = System.nanoTime(); sincOverhead = Math.min(sincOverhead, 1e-9 * (double)(overheadNanos - startNanos) / (double)TestSincPerformanceN); sincWithOverhead = Math.min(sincWithOverhead, 1e-9 * (double)(endNanos - overheadNanos) / (double)TestSincPerformanceN); } System.out.println("sinc(float x) takes " + (sincWithOverhead - sincOverhead) + " seconds (accounted for overhead of " + sincOverhead + " seconds)"); } @Test public void testSincDoublePerformance() { double sincOverhead = Float.POSITIVE_INFINITY; double sincWithOverhead = Float.POSITIVE_INFINITY; for(int n=0; n < 10; ++n) { resultDouble = 0; long startNanos = System.nanoTime(); for(int i=2; i <= (TestSincPerformanceN + 1); ++i) { resultDouble += 1.0 / (double)i; } long overheadNanos = System.nanoTime(); for(int i=2; i <= (TestSincPerformanceN + 1); ++i) { resultDouble += Functions.sinc(1.0 / (double)i); } long endNanos = System.nanoTime(); sincOverhead = Math.min(sincOverhead, 1e-9 * (double)(overheadNanos - startNanos) / (double)TestSincPerformanceN); sincWithOverhead = Math.min(sincWithOverhead, 1e-9 * (double)(endNanos - overheadNanos) / (double)TestSincPerformanceN); } System.out.println("sinc(double x) takes " + (sincWithOverhead - sincOverhead) + " seconds (accounted for overhead of " + sincOverhead + " seconds)"); } }
2,608
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpRetransmitRequestHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpRetransmitRequestHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.*; import java.util.logging.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles packet retransmissions. * <p> * Sends {@link RaopRtpPacket.RetransmitRequest} packet in response to missing packets, * and resends those requests after a timeout period until the packet arrives. * <p> * Uses an {@link AudioClock} as it's time source, any thus only re-requests packets * which can reasonably be expected to arrive before their play back time. * */ public class RaopRtpRetransmitRequestHandler extends SimpleChannelUpstreamHandler { private static Logger s_logger = Logger.getLogger(RaopRtpRetransmitRequestHandler.class.getName()); /** * Maximal number of in-flight (i.e. not yet fulfilled) retransmit requests */ private static final double RetransmitInFlightLimit = 128; /** * Maximum number of retransmit requests sent per packet */ private static final int RetransmitAttempts = 2; /** * Represents a missing packet */ private class MissingPacket { /** * Packet's sequence number */ public final int sequence; /** * Packet must be placed on the audio output queue no later than this frame time */ public final long requiredUntilFrameTime; /** * Packet must be placed on the audio output queue no later than this seconds time */ public final double requiredUntilSecondsTime; /** * Number of retransmit requests already sent for the packet */ public int retransmitRequestCount = 0; /** * Packet expected to arrive until this seconds time. If not, a retransmit request * is sent. */ public double expectedUntilSecondsTime; /** * Creates a MissingPacket instance for a given sequence, using the provided * time to compute the times at which the packet is expected. * * @param _sequence sequence number * @param nextSecondsTime next possible play back time */ public MissingPacket(final int _sequence, final double nextSecondsTime) { sequence = _sequence; requiredUntilFrameTime = convertSequenceToFrameTime(_sequence); requiredUntilSecondsTime = m_audioClock.convertFrameToSecondsTime(requiredUntilFrameTime); computeExpectedUntil(nextSecondsTime); } /** * Updates the state after a retransmit request has been sent. * @param nextSecondsTime next possible play back time */ public void sentRetransmitRequest(final double nextSecondsTime) { ++retransmitRequestCount; computeExpectedUntil(nextSecondsTime); } /** * Updates the time until which we expect the packet to arrive. * @param nextSecondsTime next possible play back time */ private void computeExpectedUntil(final double nextSecondsTimee) { expectedUntilSecondsTime = 0.5 * nextSecondsTimee + 0.5 * m_audioClock.convertFrameToSecondsTime(requiredUntilFrameTime); } } /** * Time source */ private final AudioClock m_audioClock; /** * Frames per packet. Used to interpolate the * RTP time stamps of missing packets. */ private final long m_framesPerPacket; /** * Latest sequence number received so far */ private int m_latestReceivedSequence = -1; /** * RTP frame time corresponding to packet * with the latest sequence number. */ private long m_latestReceivedSequenceFrameTime; /** * List of in-flight retransmit requests */ private static final List<MissingPacket> m_missingPackets = new java.util.LinkedList<MissingPacket>(); /** * Header sequence number for retransmit requests */ private int m_retransmitRequestSequence = 0; public RaopRtpRetransmitRequestHandler(final AudioStreamInformationProvider streamInfoProvider, final AudioClock audioClock) { m_framesPerPacket = streamInfoProvider.getFramesPerPacket(); m_audioClock = audioClock; } /** * Mark the packet as retransmitted, i.e. remove it from the list of * in-flight retransmit requests. * * @param sequence sequence number of packet * @param nextSecondsTime next possible play back time */ private void markRetransmitted(final int sequence, final double nextSecondsTimee) { final Iterator<MissingPacket> i = m_missingPackets.iterator(); while (i.hasNext()) { final MissingPacket missingPacket = i.next(); if (missingPacket.sequence == sequence) { s_logger.fine("Packet " + sequence + " arrived " + (missingPacket.expectedUntilSecondsTime - nextSecondsTimee) + " seconds before it was due"); i.remove(); } } } /** * Mark the packet is missing, i.e. add an entry to the list of * in-flight retransmit requests. * * @param sequence sequence number of packet * @param nextSecondsTime next possible play back time */ private void markMissing(final int sequence, final double nextSecondsTime) { /* Add packet to list of in-flight retransmit requests */ final MissingPacket missingPacket = new MissingPacket(sequence, nextSecondsTime); if (missingPacket.requiredUntilSecondsTime > nextSecondsTime) { s_logger.fine("Packet " + sequence + " expected to arive in " + (missingPacket.expectedUntilSecondsTime - nextSecondsTime) + " seconds"); m_missingPackets.add(missingPacket); } else { s_logger.warning("Packet " + sequence + " was required " + (nextSecondsTime - missingPacket.expectedUntilSecondsTime ) + " seconds ago, not requesting retransmit"); } /* Forget about old missing packets if we exceeded the number * of in-flight retransmit requests */ while (m_missingPackets.size() > RetransmitInFlightLimit) { final MissingPacket m = m_missingPackets.get(0); m_missingPackets.remove(0); s_logger.warning("Packet " + sequence + " overflowed in-flight retransmit count, giving up on old packet " + m.sequence); } } /** * Scan the list of in-flight retransmit requests and send * {@link RetransmitRequest} packets if it's past the time * at which we expected the packet to arrive * * @param channel channel used to send retransmit requests * @param nextSecondsTime */ private synchronized void requestRetransmits(final Channel channel, final double nextSecondsTime) { /* The retransmit request we're currently building */ RaopRtpPacket.RetransmitRequest retransmitRequest = null; /* Run through open retransmit requests */ final Iterator<MissingPacket> missingPacketIterator = m_missingPackets.iterator(); while (missingPacketIterator.hasNext()) { final MissingPacket missingPacket = missingPacketIterator.next(); /* If it's past the time at which the packet would have needed to be queued, * warn and forget about it */ if (missingPacket.requiredUntilSecondsTime <= nextSecondsTime) { s_logger.warning("Packet " + missingPacket.sequence + " was required " + (nextSecondsTime - missingPacket.requiredUntilSecondsTime) + " secons ago, giving up"); missingPacketIterator.remove(); continue; } /* If the packet isn't expected until later, * skip it for now */ if (missingPacket.expectedUntilSecondsTime > nextSecondsTime) continue; /* Ok, the packet is overdue */ if (missingPacket.retransmitRequestCount >= RetransmitAttempts) { /* If the packet was already requests too often, * warn and forget about it */ s_logger.warning("Packet " + missingPacket.sequence + " overdue " + (nextSecondsTime - missingPacket.expectedUntilSecondsTime) + " seconds after " + missingPacket.retransmitRequestCount + " retransmit requests, giving up"); missingPacketIterator.remove(); continue; } else { /* Log that we're about to request retransmission */ final int retransmitRequestCountPrevious = missingPacket.retransmitRequestCount; final double expectedUntilSecondsTimePrevious = missingPacket.expectedUntilSecondsTime; missingPacket.sentRetransmitRequest(nextSecondsTime); s_logger.fine("Packet " + missingPacket.sequence + " overdue " + (nextSecondsTime - expectedUntilSecondsTimePrevious) + " seconds after " + retransmitRequestCountPrevious + " retransmit requests, requesting again expecting response in " + (missingPacket.expectedUntilSecondsTime - nextSecondsTime) + " seconds"); } /* Ok, really request re-transmission */ if ( (retransmitRequest != null) && (sequenceAdd(retransmitRequest.getSequenceFirst(), retransmitRequest.getSequenceCount()) != missingPacket.sequence) ) { /* There is a current retransmit request, but the sequence cannot be appended. * We transmit the current request and start building a new one */ if (channel.isOpen() && channel.isWritable()) channel.write(retransmitRequest); retransmitRequest = null; } /* If there still is a current retransmit request, the sequence can be appended */ if (retransmitRequest == null) { /* Create new retransmit request */ m_retransmitRequestSequence = sequenceSuccessor(m_retransmitRequestSequence); retransmitRequest = new RaopRtpPacket.RetransmitRequest(); retransmitRequest.setSequence(m_retransmitRequestSequence); retransmitRequest.setSequenceFirst(missingPacket.sequence); retransmitRequest.setSequenceCount(1); } else { /* Append sequnce to current retransmit request */ retransmitRequest.setSequenceCount(retransmitRequest.getSequenceCount() + 1); } } if (retransmitRequest != null) { /* Send the retransmit request we were building when the loop ended */ if (channel.isOpen() && channel.isWritable()) channel.write(retransmitRequest); } } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { if (evt.getMessage() instanceof RaopRtpPacket.AudioTransmit) audioTransmitReceived(ctx, (RaopRtpPacket.AudioTransmit)evt.getMessage()); else if (evt.getMessage() instanceof RaopRtpPacket.AudioRetransmit) audioRetransmitReceived(ctx, (RaopRtpPacket.AudioRetransmit)evt.getMessage()); super.messageReceived(ctx, evt); /* Request retransmits if necessary */ requestRetransmits(ctx.getChannel(), m_audioClock.getNextSecondsTime()); } private synchronized void audioRetransmitReceived(final ChannelHandlerContext ctx, final RaopRtpPacket.AudioRetransmit audioPacket) { final double nextSecondsTime = m_audioClock.getNextSecondsTime(); /* Mark packet as retransmitted */ markRetransmitted(audioPacket.getOriginalSequence(), nextSecondsTime); } private synchronized void audioTransmitReceived(final ChannelHandlerContext ctx, final RaopRtpPacket.AudioTransmit audioPacket) { final double nextSecondsTime = m_audioClock.getNextSecondsTime(); /* Mark packet as retransmitted. * Doing this here prevents sending out further retransmit requests for packets * which simply were delayed */ markRetransmitted(audioPacket.getSequence(), nextSecondsTime); /* Compute delta between the last and the current Sequence */ final long delta; if (m_latestReceivedSequence < 0) delta = 1; else delta = sequenceDelta(m_latestReceivedSequence, audioPacket.getSequence()); /* Remember the sequence we expected, then update the latest received sequence * and it's frame time iff the new sequence is larger than the old one */ final int expectedSequence = sequenceSuccessor(m_latestReceivedSequence); if (delta > 0) { m_latestReceivedSequence = audioPacket.getSequence(); m_latestReceivedSequenceFrameTime = audioPacket.getTimeStamp(); } if (delta == 1) { /* No reordered or missing packets */ } else if ((delta > 1) && (delta <= RetransmitInFlightLimit)) { /* Previous packet reordered/delayed or missing */ s_logger.fine("Packet sequence number increased by " + delta + ", " + (delta-1) + " packet(s) missing,"); for(int s = expectedSequence; s != audioPacket.getSequence(); s = sequenceSuccessor(s)) markMissing(s, nextSecondsTime); } else if (delta < 0) { /* Delayed packet */ s_logger.fine("Packet sequence number decreased by " + (-delta) + ", assuming delayed packet"); } else { /* Unsynchronized sequences */ s_logger.warning("Packet sequence number jumped to " + audioPacket.getSequence() + ", assuming sequences number are out of sync"); m_missingPackets.clear(); } } /** * Interpolate RTP frame time of missing packet * @param sequence sequence of missing packet * @return interpolated frame time of missing packet */ private long convertSequenceToFrameTime(final int sequence) { return m_latestReceivedSequenceFrameTime + sequenceDelta(m_latestReceivedSequence, sequence) * m_framesPerPacket; } /** * Returns the number of sequences between from and to, including * to. * * @param from first sequence * @param to seconds sequence * @return number of intermediate sequences */ private static long sequenceDistance(final int from, final int to) { assert (from & 0xffff) == from; assert (to & 0xffff) == to; return (0x10000 + to - from) % 0x10000; } /** * Returns the difference between to sequences. Since sequences * are circular, they're not totally ordered, and hence it's * ambiguous whether the delta is positive or negative. We return * the number with the smaller <b>absolute</b> value. * * @param a first sequence * @param b second sequence * @return the delta between a and b */ private static long sequenceDelta(final int a, final int b) { final long d = sequenceDistance(a, b); if (d < 0x8000) return d; else return (d - 0x10000); } /** * Adds a delta to a given sequence and returns the resulting * sequence. * * @param seq sequence * @param delta delta to add * @return sequence incremented or decremented by delta */ private static int sequenceAdd(final int seq, final long delta) { return (0x10000 + seq + (int)(delta % 0x10000L)) % 0x10000; } /** * Returns the immediate successor sequence of the given sequence * @param seq sequence * @return successor of sequence */ private static int sequenceSuccessor(final int seq) { return sequenceAdd(seq, 1); } /** * Returns the immediate predecessor sequence of the given sequence * @param seq sequence * @return predecessor of sequence */ @SuppressWarnings("unused") private static int sequencePredecessor(final int seq) { return sequenceAdd(seq, -1); } }
15,087
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RunningExponentialAverage.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RunningExponentialAverage.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; /** * Computes an exponential running average * over a series of values. */ public class RunningExponentialAverage { public double m_value = Double.NaN; /** * Create an exponential average without an initial value */ public RunningExponentialAverage() { m_value = Double.NaN; } /** * Create an exponential average with the given initial value */ public RunningExponentialAverage(final double initialValue) { m_value = initialValue; } /** * Add the value to the average, weighting it with the giveen weight. * * @param value the value to add * @param weight the value's weight between 0 and 1. */ public void add(final double value, final double weight) { if (Double.isNaN(m_value)) { m_value = value; } else { m_value = value * weight + m_value * (1.0 - weight); } } /** * Return true until {@link #add(double, double)} has been called * at least once for instances initialized without an initial value. * Otherwise, always returns false. */ public boolean isEmpty() { return Double.isNaN(m_value); } /** * Returns the current exponential average * @return exponential average */ public double get() { return m_value; } }
1,920
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpAudioAlacDecodeHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpAudioAlacDecodeHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.Arrays; import java.util.logging.*; import javax.sound.sampled.AudioFormat; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; import com.beatofthedrum.alacdecoder.*; /** * Decodes the ALAC audio data in incoming audio packets to big endian unsigned PCM. * Also serves as an {@link AudioStreamInformationProvider} * * This class assumes that ALAC requires no inter-packet state - it doesn't make * any effort to feed the packets to ALAC in the correct order. */ public class RaopRtpAudioAlacDecodeHandler extends OneToOneDecoder implements AudioStreamInformationProvider { private static Logger s_logger = Logger.getLogger(RaopRtpAudioAlacDecodeHandler.class.getName()); /* There are the indices into the SDP format options at which * the sessions appear */ public static final int FormatOptionSamplesPerFrame = 0; public static final int FormatOption7a = 1; public static final int FormatOptionBitsPerSample = 2; public static final int FormatOptionRiceHistoryMult = 3; public static final int FormatOptionRiceInitialHistory = 4; public static final int FormatOptionRiceKModifier = 5; public static final int FormatOption7f = 6; public static final int FormatOption80 = 7; public static final int FormatOption82 = 8; public static final int FormatOption86 = 9; public static final int FormatOption8a_rate = 10; /** * The {@link AudioFormat} that corresponds to the output produced by the decoder */ private static final AudioFormat AudioOutputFormat = new AudioFormat( 44100 /* sample rate */, 16 /* bits per sample */, 2 /* number of channels */, false /* unsigned */, true /* big endian */ ); /** * Number of samples per ALAC frame (packet). * One sample here means *two* amplitues, one * for the left channel and one for the right */ private final int m_samplesPerFrame; /** * Decoder state */ private final AlacFile m_alacFile; /** * Creates an ALAC decoder instance from a list of format options as * they appear in the SDP session announcement. * * @param formatOptions list of format options * @throws ProtocolException if the format options are invalid for ALAC */ public RaopRtpAudioAlacDecodeHandler(final String[] formatOptions) throws ProtocolException { m_samplesPerFrame = Integer.valueOf(formatOptions[FormatOptionSamplesPerFrame]); /* We support only 16-bit ALAC */ final int bitsPerSample = Integer.valueOf(formatOptions[FormatOptionBitsPerSample]); if (bitsPerSample != 16) throw new ProtocolException("Sample size must be 16, but was " + bitsPerSample); /* We support only 44100 kHz */ final int sampleRate = Integer.valueOf(formatOptions[FormatOption8a_rate]); if (sampleRate != 44100) throw new ProtocolException("Sample rate must be 44100, but was " + sampleRate); m_alacFile = AlacDecodeUtils.create_alac(bitsPerSample, 2); m_alacFile.setinfo_max_samples_per_frame = m_samplesPerFrame; m_alacFile.setinfo_7a = Integer.valueOf(formatOptions[FormatOption7a]); m_alacFile.setinfo_sample_size = bitsPerSample; m_alacFile.setinfo_rice_historymult = Integer.valueOf(formatOptions[FormatOptionRiceHistoryMult]); m_alacFile.setinfo_rice_initialhistory = Integer.valueOf(formatOptions[FormatOptionRiceInitialHistory]); m_alacFile.setinfo_rice_kmodifier = Integer.valueOf(formatOptions[FormatOptionRiceKModifier]); m_alacFile.setinfo_7f = Integer.valueOf(formatOptions[FormatOption7f]); m_alacFile.setinfo_80 = Integer.valueOf(formatOptions[FormatOption80]); m_alacFile.setinfo_82 = Integer.valueOf(formatOptions[FormatOption82]); m_alacFile.setinfo_86 = Integer.valueOf(formatOptions[FormatOption86]); m_alacFile.setinfo_8a_rate = sampleRate; s_logger.info("Created ALAC decode for options " + Arrays.toString(formatOptions)); } @Override protected synchronized Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (!(msg instanceof RaopRtpPacket.Audio)) return msg; final RaopRtpPacket.Audio alacPacket = (RaopRtpPacket.Audio)msg; /* The ALAC decode sometimes reads beyond the input's bounds * (but later discards the data). To alleviate, we allocate * 3 spare bytes at input buffer's end. */ final byte[] alacBytes = new byte[alacPacket.getPayload().capacity() + 3]; alacPacket.getPayload().getBytes(0, alacBytes, 0, alacPacket.getPayload().capacity()); /* Decode ALAC to PCM */ final int[] pcmSamples = new int[m_samplesPerFrame * 2]; final int pcmSamplesBytes = AlacDecodeUtils.decode_frame(m_alacFile, alacBytes, pcmSamples, m_samplesPerFrame); /* decode_frame() returns the number of *bytes*, not samples! */ final int pcmSamplesLength = pcmSamplesBytes / 4; final Level level = Level.FINEST; if (s_logger.isLoggable(level)) s_logger.log(level, "Decoded " + alacBytes.length + " bytes of ALAC audio data to " + pcmSamplesLength + " PCM samples"); /* Complain if the sender doesn't honour it's commitment */ if (pcmSamplesLength != m_samplesPerFrame) throw new ProtocolException("Frame declared to contain " + m_samplesPerFrame + ", but contained " + pcmSamplesLength); /* Assemble PCM audio packet from original packet header and decoded data. * The ALAC decode emits signed PCM samples as integers. We store them as * as unsigned big endian integers in the packet. */ RaopRtpPacket.Audio pcmPacket; if (alacPacket instanceof RaopRtpPacket.AudioTransmit) { pcmPacket = new RaopRtpPacket.AudioTransmit(pcmSamplesLength * 4); alacPacket.getBuffer().getBytes(0, pcmPacket.getBuffer(), 0, RaopRtpPacket.AudioTransmit.Length); } else if (alacPacket instanceof RaopRtpPacket.AudioRetransmit) { pcmPacket = new RaopRtpPacket.AudioRetransmit(pcmSamplesLength * 4); alacPacket.getBuffer().getBytes(0, pcmPacket.getBuffer(), 0, RaopRtpPacket.AudioRetransmit.Length); } else throw new ProtocolException("Packet type " + alacPacket.getClass() + " is not supported by the ALAC decoder"); for(int i=0; i < pcmSamples.length; ++i) { /* Convert sample to big endian unsigned integer PCM */ final int pcmSampleUnsigned = pcmSamples[i] + 0x8000; pcmPacket.getPayload().setByte(2*i, (pcmSampleUnsigned & 0xff00) >> 8); pcmPacket.getPayload().setByte(2*i + 1, pcmSampleUnsigned & 0x00ff); } return pcmPacket; } @Override public AudioFormat getAudioFormat() { return AudioOutputFormat; } @Override public int getFramesPerPacket() { return m_samplesPerFrame; } @Override public double getPacketsPerSecond() { return getAudioFormat().getSampleRate() / (double)getFramesPerPacket(); } }
7,397
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtpEncodeHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtpEncodeHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * Converts outgoing RTP packets into a sequence of bytes */ public class RtpEncodeHandler extends OneToOneEncoder { @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (msg instanceof RtpPacket) return ((RtpPacket)msg).getBuffer(); else return msg; } }
1,167
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtpLoggingHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtpLoggingHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; /** * Logs incoming and outgoing RTP packets */ public class RtpLoggingHandler extends SimpleChannelHandler { private static final Logger s_logger = Logger.getLogger(RtpLoggingHandler.class.getName()); @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { if (evt.getMessage() instanceof RtpPacket) { final RtpPacket packet = (RtpPacket)evt.getMessage(); final Level level = getPacketLevel(packet); if (s_logger.isLoggable(level)) s_logger.log(level, evt.getRemoteAddress() + "> " + packet.toString()); } super.messageReceived(ctx, evt); } @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { if (evt.getMessage() instanceof RtpPacket) { final RtpPacket packet = (RtpPacket)evt.getMessage(); final Level level = getPacketLevel(packet); if (s_logger.isLoggable(level)) s_logger.log(level, evt.getRemoteAddress() + "< " + packet.toString()); } super.writeRequested(ctx, evt); } private Level getPacketLevel(final RtpPacket packet) { if (packet instanceof RaopRtpPacket.Audio) return Level.FINEST; else if (packet instanceof RaopRtpPacket.RetransmitRequest) return Level.FINEST; else if (packet instanceof RaopRtpPacket.Timing) return Level.FINEST; else return Level.FINE; } }
2,313
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtspPipelineFactory.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtspPipelineFactory.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.rtsp.*; /** * Factory for AirTunes/RAOP RTSP channels */ public class RaopRtspPipelineFactory implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { final ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("executionHandler", AirReceiver.ChannelExecutionHandler); pipeline.addLast("closeOnShutdownHandler", AirReceiver.CloseChannelOnShutdownHandler); pipeline.addLast("exceptionLogger", new ExceptionLoggingHandler()); pipeline.addLast("decoder", new RtspRequestDecoder()); pipeline.addLast("encoder", new RtspResponseEncoder()); pipeline.addLast("logger", new RtspLoggingHandler()); pipeline.addLast("errorResponse", new RtspErrorResponseHandler()); pipeline.addLast("challengeResponse", new RaopRtspChallengeResponseHandler(AirReceiver.HardwareAddressBytes)); pipeline.addLast("header", new RaopRtspHeaderHandler()); pipeline.addLast("options", new RaopRtspOptionsHandler()); pipeline.addLast("audio", new RaopAudioHandler(AirReceiver.ExecutorService)); pipeline.addLast("unsupportedResponse", new RtspUnsupportedResponseHandler()); return pipeline; } }
1,943
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtspLoggingHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtspLoggingHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.nio.charset.Charset; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; /** * Logs RTSP requests and responses. */ public class RtspLoggingHandler extends SimpleChannelHandler { private static final Logger s_logger = Logger.getLogger(RtspLoggingHandler.class.getName()); @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { s_logger.info("Client " + e.getChannel().getRemoteAddress() + " connected on " + e.getChannel().getLocalAddress()); } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); final Level level = Level.FINE; if (s_logger.isLoggable(level)) { final String content = req.getContent().toString(Charset.defaultCharset()); final StringBuilder s = new StringBuilder(); s.append(">"); s.append(req.getMethod()); s.append(" "); s.append(req.getUri()); s.append("\n"); for(final Map.Entry<String, String> header: req.getHeaders()) { s.append(" "); s.append(header.getKey()); s.append(": "); s.append(header.getValue()); s.append("\n"); } s.append(content); s_logger.log(Level.FINE, s.toString()); } super.messageReceived(ctx, evt); } @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpResponse resp = (HttpResponse)evt.getMessage(); final Level level = Level.FINE; if (s_logger.isLoggable(level)) { final StringBuilder s = new StringBuilder(); s.append("<"); s.append(resp.getStatus().getCode()); s.append(" "); s.append(resp.getStatus().getReasonPhrase()); s.append("\n"); for(final Map.Entry<String, String> header: resp.getHeaders()) { s.append(" "); s.append(header.getKey()); s.append(": "); s.append(header.getValue()); s.append("\n"); } s_logger.log(Level.FINE, s.toString()); } super.writeRequested(ctx, evt); } }
2,885
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
AirTunesCrytography.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/AirTunesCrytography.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.*; import java.security.interfaces.*; import java.security.spec.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; import javax.crypto.CipherSpi; public final class AirTunesCrytography { /** * Class is not meant to be instantiated */ private AirTunesCrytography() { throw new RuntimeException(); } private static final Logger s_logger = Logger.getLogger(AirTunesCrytography.class.getName()); /** * The JCA/JCE Provider who supplies the necessary cryptographic algorithms */ private static final Provider Provider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); /** * The AirTunes private key in PEM-encoded PKCS#8 format. * Original Key from shairport was in PEM-encoded PKCS#1 format */ private static final String PrivateKeyData = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDn10TyouJ4i2wf\n" + "VaCOtwVEqPp5RaqL5sYs5fUcvdTcaEL+PRCD3S7ewb/UJS3ALm85i98OYUjqhIVe\n" + "LkQtptYmZPZ0ofMEkpreT2iT7y325xGox3oNkcnZgIIuUNEpIq/qQOqfDhTA92k4\n" + "xfOIL8AyPdn+VRVfUbtZIcIBYp/XM1LV4u+qv5ugSNe4E6K2dn9sPM8etM5nPQN7\n" + "DS6jDF//6wb40Ird5AlXGpxon+8QcohV3Yz7movvXIlD7ztfqhXd5pi+3fNZlgPr\n" + "Pm9hNyu2KPZVn1maeL9QBoeqf0l2wFYtQSlW+JieGKY1W9gVl4JeD8h1ND7HghF2\n" + "Jc2/mER7AgMBAAECggEBAOXwDHL1d9YEuaTOQSKqhLAXQ+yZWs/Mf0qyfAsYf5Bm\n" + "W+NZ3xJZgY3u7XnTse+EXk3d2smhVTc7XicNjhMVABouUn1UzfkACldovJjURGs3\n" + "u70Asp3YtTBiEzsqbnf07jJQViKQTacg+xwSwDmW2nE6BQYJjtvt7Pk20PqcvVkp\n" + "q7Dto1eZUC+YlNy4/FaaiS0XeAMkorbDFm40ZwkTS4VAQbhncGtY/vKg25Ird2KL\n" + "aOaWk8evQ78qc9C3Mjd6C6F7RPBR6b95hJ3LMzJXH9inCTPC1gvexHmTSj2spAu2\n" + "8vN8Cp0HEG6tyLNpoD8vQciACY6K3UYkDaxozFNU82ECgYEA9+C/Wh5nGDGai2IJ\n" + "wxcURARZ+XOFZhOxeuFQi7PmMW5rf0YtL31kQSuEt2vCPysMNWJFUnmyQ6n3MW+V\n" + "gAezTGH3aOLUTtX/KycoF+wys+STkpIo+ueOd0yg9169adWSAnmPEW42DGQ4sy4b\n" + "2LncHjIy8NMJGIg8xD743aIsNpECgYEA72//+ZTx5WRBqgA1/RmgyNbwI3jHBYDZ\n" + "xIQgeR30B8WR+26/yjIsMIbdkB/S+uGuu2St9rt5/4BRvr0M2CCriYdABgGnsv6T\n" + "kMrMmsq47Sv5HRhtj2lkPX7+D11W33V3otA16lQT/JjY8/kI2gWaN52kscw48V1W\n" + "CoPMMXFTyEsCgYEA0OuvvEAluoGMdXAjNDhOj2lvgE16oOd2TlB7t9Pf78fWeMZo\n" + "LT+tcTRBvurnJKCewJvcO8BwnJEz1Ins4qUa3QUxJ0kPkobRc8ikBU3CCldcfkwM\n" + "mDT0od6HSRej5ADq+IUGLbXLfjQ2iecR91/ng9fhkZL9dpzVQr6kuQEH7NECgYB/\n" + "QBjcfeopLaUwQjhvMQWgd4rcbz3mkNordMUFWYPt9XRmGi/Xt96AU8zA4gjwyKxi\n" + "b1l9PZnSzlGjezmuS36e8sB18L89g8rNMtqWkZLCiZI1glwH0c0yWaGQbNzUmcth\n" + "PiLJTLHqlxkGYJ3xsPSLBj8XNyA0NpSZtf35cO9EDQKBgQCQTukg+UTvWq98lCCg\n" + "D16bSAgsC4Tg+7XdoqImd9+3uEiNsr7mTJvdPKxm+jIOdvcc4q8icru9dsq5TghK\n" + "DEHZsHcdxjNAwazPWonaAbQ3mG8mnPDCFuFeoUoDjNppKvDrbbAOeIArkyUgTS0g\n" + "Aoo/jLE0aOgPZBiOEEa6G+RYpg==\n" + ""; /** * The AirTunes private key as an instance of {@link java.security.interfaces.RSAPrivateKey} */ public static final RSAPrivateKey PrivateKey = rsaPrivateKeyDecode(PrivateKeyData); static final Pattern s_transformation_pattern = Pattern.compile("^([A-Za-z0-9_.-]+)(/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+))?"); /** * Replacement for JCA/JCE's {@link javax.crypto.Cipher#getInstance}. * The original method only accepts JCE providers from signed jars, * which prevents us from bundling our cryptography provider Bouncy Caster * with the application. * * @param transformation the transformation to find an implementation for */ public static Cipher getCipher(final String transformation) { try { /* Split the transformation into algorithm, mode and padding */ final Matcher transformation_matcher = s_transformation_pattern.matcher(transformation.toUpperCase()); if (!transformation_matcher.matches()) throw new RuntimeException("Transformation " + transformation + " is invalid"); final String algorithm = transformation_matcher.group(1); final String mode = transformation_matcher.group(3); final String padding = transformation_matcher.group(4); final boolean isBareAlgorithm = (mode == null) && (padding == null); /* Build the property values we need to search for. */ final String algorithmModePadding = !isBareAlgorithm ? algorithm + "/" + mode + "/" + padding : null; final String algorithmMode = !isBareAlgorithm ? algorithm + "/" + mode : null; final String algorithmPadding = !isBareAlgorithm ? algorithm + "//" + padding : null; /* Search the provider for implementations. We ask for more specific (i.e matching * the requested mode and or padding) implementation first, then fall back to more * generals ones which we then must configure for the mode and padding. */ final CipherSpi cipherSpi; if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmModePadding) != null)) { @SuppressWarnings("unchecked") final Class<? extends CipherSpi> cipherSpiClass = (Class<? extends CipherSpi>)Class.forName(resolveProperty(Provider, "Cipher", algorithmModePadding)); cipherSpi = cipherSpiClass.newInstance(); } else if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmMode) != null)) { @SuppressWarnings("unchecked") final Class<? extends CipherSpi> cipherSpiClass = (Class<? extends CipherSpi>)Class.forName(resolveProperty(Provider, "Cipher", algorithmMode)); cipherSpi = cipherSpiClass.newInstance(); if (!isBareAlgorithm) cipherSpiSetPadding(cipherSpi, padding); } else if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmPadding) != null)) { @SuppressWarnings("unchecked") final Class<? extends CipherSpi> cipherSpiClass = (Class<? extends CipherSpi>)Class.forName(resolveProperty(Provider, "Cipher", algorithmPadding)); cipherSpi = cipherSpiClass.newInstance(); if (!isBareAlgorithm) cipherSpiSetMode(cipherSpi, mode); } else if (resolveProperty(Provider, "Cipher", algorithm) != null) { @SuppressWarnings("unchecked") final Class<? extends CipherSpi> cipherSpiClass = (Class<? extends CipherSpi>)Class.forName(resolveProperty(Provider, "Cipher", algorithm)); cipherSpi = cipherSpiClass.newInstance(); if (!isBareAlgorithm) { cipherSpiSetMode(cipherSpi, mode); cipherSpiSetPadding(cipherSpi, padding); } } else { throw new RuntimeException("Provider " + Provider.getName() + " (" + Provider.getClass() + ") does not implement " + transformation); } /* Create a {@link javax.crypto.Cipher} instance from the {@link javax.crypto.CipherSpi} the provider gave us */ s_logger.info("Using SPI " + cipherSpi.getClass() + " for " + transformation); return getCipher(cipherSpi, transformation.toUpperCase()); } catch (final RuntimeException e) { throw e; } catch (final Error e) { throw e; } catch (final Throwable e) { throw new RuntimeException("Provider " + Provider.getName() + " (" + Provider.getClass() + ") failed to instanciate " + transformation, e); } } /** * Converts a PEM-encoded PKCS#8 private key into an RSAPrivateKey instance * useable with JCE * * @param privateKey private key in PKCS#8 format and PEM-encoded * @return RSAPrivateKey instance containing the key */ private static RSAPrivateKey rsaPrivateKeyDecode(final String privateKey) { try { final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodePadded(privateKey)); return (RSAPrivateKey)keyFactory.generatePrivate(ks); } catch (final Exception e) { throw new RuntimeException("Failed to decode built-in private key", e); } } /** * Creates a {@link javax.crypto.Cipher} instance from a {@link javax.crypto.CipherSpi}. * * @param cipherSpi the {@link javax.cyrpto.CipherSpi} instance * @param transformation the transformation cipherSpi was obtained for * @return a {@link javax.crypto.Cipher} instance * @throws Throwable in case of an error */ private static Cipher getCipher(final CipherSpi cipherSpi, final String transformation) throws Throwable { /* This API isn't public - usually you're expected to simply use Cipher.getInstance(). * Due to the signed-jar restriction for JCE providers that is not an option, so we * use one of the private constructors of Cipher. */ final Class<Cipher> cipherClass = Cipher.class; final Constructor<Cipher> cipherConstructor = cipherClass.getDeclaredConstructor(CipherSpi.class, String.class); cipherConstructor.setAccessible(true); try { return cipherConstructor.newInstance(cipherSpi, transformation); } catch (final InvocationTargetException e) { throw e.getCause(); } } /** * Get the reflection of a private and protected method. * * Required since {@link java.lang.Class#getMethod(String, Class...) * only find public method * * @param clazz the class to search in * @param name the method name * @param parameterTypes the method's parameter types * @return the method reflection * @throws NoSuchMethodException */ private static Method getMethod(final Class<?> clazz, final String name, final Class<?>... parameterTypes) throws NoSuchMethodException { try { /* Try to fetch the method reflection */ return clazz.getDeclaredMethod(name, parameterTypes); } catch (final NoSuchMethodException e1) { /* No such method. Search base class if there is one, * otherwise complain */ if (clazz.getSuperclass() != null) { try { /* Try to fetch the method from the base class */ return getMethod(clazz.getSuperclass(), name, parameterTypes); } catch (final NoSuchMethodException e2) { /* We don't want the exception to indicate that the * *base* class didn't contain a matching method, but * rather that the subclass didn't. */ final StringBuilder s = new StringBuilder(); s.append(clazz.getName()); s.append("("); boolean first = true; for(final Class<?> parameterType: parameterTypes) { if (!first) s.append(", "); first = false; s.append(parameterType); } s.append(")"); throw new NoSuchMethodException(s.toString()); } } else { /* No base class, complain */ throw e1; } } } /** * Sets the padding of a {@link javax.crypto.CipherSpi} instance. * * Like {@link #getCipher(String)}, we're accessing a private API * here, so me must work around the access restrictions * * @param cipherSpi the {@link javax.crypto.CipherSpi} instance * @param padding the padding to set * @throws Throwable if {@link javax.crypto.CipherSpi#engineSetPadding} throws */ private static void cipherSpiSetPadding(final CipherSpi cipherSpi, final String padding) throws Throwable { final Method engineSetPadding = getMethod(cipherSpi.getClass(), "engineSetPadding", String.class); engineSetPadding.setAccessible(true); try { engineSetPadding.invoke(cipherSpi, padding); } catch (final InvocationTargetException e) { throw e.getCause(); } } /** * Sets the mode of a {@link javax.crypto.CipherSpi} instance. * * Like {@link #getCipher(String)}, we're accessing a private API * here, so me must work around the access restrictions * * @param cipherSpi the {@link javax.crypto.CipherSpi} instance * @param mode the mode to set * @throws Throwable if {@link javax.crypto.CipherSpi#engineSetPadding} throws */ private static void cipherSpiSetMode(final CipherSpi cipherSpi, final String mode) throws Throwable { final Method engineSetMode = getMethod(cipherSpi.getClass(), "engineSetMode", String.class); engineSetMode.setAccessible(true); try { engineSetMode.invoke(cipherSpi, mode); } catch (final InvocationTargetException e) { throw e.getCause(); } } /** * Returns the value attached to a provider property. * * Supports aliases, i.e. if there is no property named * type.name but one named Alg.Alias.type.name, the value * of Alg.Alias.type.name is assumed to be the <b>name</b> * of the actual property. * * @param provider JCE provider * @param type type (Cipher, Algorithm, ...) * @param name transformation * @return the properties value which usually is the implementing class'es name */ private static String resolveProperty(final Provider provider, final String type, final String name) { if (Provider.getProperty(type + "." + name) != null) return Provider.getProperty(type + "." + name); else if (Provider.getProperty("Alg.Alias." + type + "." + name) != null) return resolveProperty(provider, type, Provider.getProperty("Alg.Alias." + type + "." + name)); else return null; } }
13,414
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
ExceptionLoggingHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/ExceptionLoggingHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.*; /** * Logs exceptions thrown by other channel handlers */ public class ExceptionLoggingHandler extends SimpleChannelHandler { private static Logger s_logger = Logger.getLogger(ExceptionLoggingHandler.class.getName()); @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent evt) throws Exception { super.exceptionCaught(ctx, evt); s_logger.log(Level.WARNING, "Handler raised exception", evt.getCause()); } }
1,274
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpDecodeHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpDecodeHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.logging.Logger; import org.jboss.netty.buffer.*; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; /** * Decodes incoming packets, emitting instances of {@link RaopRtpPacket} */ public class RaopRtpDecodeHandler extends OneToOneDecoder { private static final Logger s_logger = Logger.getLogger(RaopRtpDecodeHandler.class.getName()); @Override protected Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (msg instanceof ChannelBuffer) { final ChannelBuffer buffer = (ChannelBuffer)msg; try { return RaopRtpPacket.decode(buffer); } catch (final InvalidPacketException e1) { s_logger.warning(e1.getMessage()); return buffer; } } else { return msg; } } }
1,542
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
InvalidPacketException.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/InvalidPacketException.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; @SuppressWarnings("serial") public class InvalidPacketException extends ProtocolException { public InvalidPacketException(final String message) { super(message); } }
888
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtspMethods.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtspMethods.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.*; /** * The RTSP methods required for RAOP/AirTunes */ public final class RaopRtspMethods { public static final HttpMethod ANNOUNCE = RtspMethods.ANNOUNCE; public static final HttpMethod GET_PARAMETER = RtspMethods.GET_PARAMETER; public static final HttpMethod FLUSH = new HttpMethod("FLUSH"); public static final HttpMethod OPTIONS = RtspMethods.OPTIONS; public static final HttpMethod PAUSE = RtspMethods.PAUSE; public static final HttpMethod RECORD = RtspMethods.RECORD; public static final HttpMethod SETUP = RtspMethods.SETUP; public static final HttpMethod SET_PARAMETER = RtspMethods.SET_PARAMETER; public static final HttpMethod TEARDOWN = RtspMethods.TEARDOWN; }
1,490
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpAudioDecryptionHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpAudioDecryptionHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import org.jboss.netty.buffer.*; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; /** * De-crypt AES encoded audio data */ public class RaopRtpAudioDecryptionHandler extends OneToOneDecoder { /** * The AES cipher. We request no padding because RAOP/AirTunes only encrypts full * block anyway and leaves the trailing byte unencrypted */ private final Cipher m_aesCipher = AirTunesCrytography.getCipher("AES/CBC/NoPadding"); /** * AES key */ private final SecretKey m_aesKey; /** * AES initialization vector */ private final IvParameterSpec m_aesIv; public RaopRtpAudioDecryptionHandler(final SecretKey aesKey, final IvParameterSpec aesIv) { m_aesKey = aesKey; m_aesIv = aesIv; } @Override protected synchronized Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (msg instanceof RaopRtpPacket.Audio) { final RaopRtpPacket.Audio audioPacket = (RaopRtpPacket.Audio)msg; final ChannelBuffer audioPayload = audioPacket.getPayload(); /* Cipher is restarted for every packet. We simply overwrite the * encrypted data with the corresponding plain text */ m_aesCipher.init(Cipher.DECRYPT_MODE, m_aesKey, m_aesIv); for(int i=0; (i + 16) <= audioPayload.capacity(); i += 16) { byte[] block = new byte[16]; audioPayload.getBytes(i, block); block = m_aesCipher.update(block); audioPayload.setBytes(i, block); } } return msg; } }
2,332
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpTimingHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpTimingHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.logging.Logger; import org.jboss.netty.channel.*; /** * Handles RTP timing. * <p> * Keeps track of the offset between the local audio clock and the remote clock, * and uses the information to re-sync the audio output queue upon receiving a * sync packet. */ public class RaopRtpTimingHandler extends SimpleChannelHandler { private static Logger s_logger = Logger.getLogger(RaopRtpTimingHandler.class.getName()); /** * Number of seconds between {@link TimingRequest}s. */ public static final double TimeRequestInterval = 0.2; /** * Thread which sends out {@link TimingRequests}s. */ private class TimingRequester implements Runnable { private final Channel m_channel; public TimingRequester(final Channel channel) { m_channel = channel; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { final RaopRtpPacket.TimingRequest timingRequestPacket = new RaopRtpPacket.TimingRequest(); timingRequestPacket.getReceivedTime().setDouble(0); /* Set by the source */ timingRequestPacket.getReferenceTime().setDouble(0); /* Set by the source */ timingRequestPacket.getSendTime().setDouble(m_audioClock.getNowSecondsTime()); m_channel.write(timingRequestPacket); try { Thread.sleep(Math.round(TimeRequestInterval * 1000)); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } } } /** * Audio time source */ private final AudioClock m_audioClock; /** * Exponential averager used to smooth the remote seconds offset */ private final RunningExponentialAverage m_remoteSecondsOffset = new RunningExponentialAverage(); /** * The {@link TimingRequester} thread. */ private Thread m_synchronizationThread; public RaopRtpTimingHandler(final AudioClock audioClock) { m_audioClock = audioClock; } @Override public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent evt) throws Exception { channelClosed(ctx, evt); /* Start synchronization thread if it isn't already running */ if (m_synchronizationThread == null) { m_synchronizationThread = new Thread(new TimingRequester(ctx.getChannel())); m_synchronizationThread.setDaemon(true); m_synchronizationThread.setName("Time Synchronizer"); m_synchronizationThread.start(); s_logger.fine("Time synchronizer started"); } super.channelOpen(ctx, evt); } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent evt) throws Exception { synchronized(this) { if (m_synchronizationThread != null) m_synchronizationThread.interrupt(); } } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { if (evt.getMessage() instanceof RaopRtpPacket.Sync) syncReceived((RaopRtpPacket.Sync)evt.getMessage()); else if (evt.getMessage() instanceof RaopRtpPacket.TimingResponse) timingResponseReceived((RaopRtpPacket.TimingResponse)evt.getMessage()); super.messageReceived(ctx, evt); } private synchronized void timingResponseReceived(final RaopRtpPacket.TimingResponse timingResponsePacket) { final double localReceiveSecondsTime = m_audioClock.getNowSecondsTime(); /* Compute remove seconds offset, assuming that the transmission times of * the timing requests and the timing response are equal */ final double localSecondsTime = localReceiveSecondsTime * 0.5 + timingResponsePacket.getReferenceTime().getDouble() * 0.5; final double remoteSecondsTime = timingResponsePacket.getReceivedTime().getDouble() * 0.5 + timingResponsePacket.getSendTime().getDouble() * 0.5; final double remoteSecondsOffset = remoteSecondsTime - localSecondsTime; /* * Compute the overall transmission time, and use that to compute * a weight of the remoteSecondsOffset we just computed. The idea * here is that the quality of the estimate depends on the difference * between the transmission times of request and response. We cannot * measure those independently, but since they're obviously bound * by the total transmission time (request + response), which we * <b>can</b> measure, we can use that to judge the quality. * * The constants are picked such that the weight is never larger than * 1e-3, and starts to decrease rapidly for transmission times significantly * larger than 1ms. */ final double localInterval = localReceiveSecondsTime - timingResponsePacket.getReferenceTime().getDouble(); final double remoteInterval = timingResponsePacket.getSendTime().getDouble() - timingResponsePacket.getReceivedTime().getDouble(); final double transmissionTime = Math.max(localInterval - remoteInterval, 0); final double weight = 1e-6 / (transmissionTime + 1e-3); /* Update exponential average */ final double remoteSecondsOffsetPrevious = (!m_remoteSecondsOffset.isEmpty() ? m_remoteSecondsOffset.get() : 0.0); m_remoteSecondsOffset.add(remoteSecondsOffset, weight); final double secondsTimeAdjustment = m_remoteSecondsOffset.get() - remoteSecondsOffsetPrevious; s_logger.finest("Timing response with weight " + weight + " indicated offset " + remoteSecondsOffset + " thereby adjusting the averaged offset by " + secondsTimeAdjustment + " leading to the new averaged offset " + m_remoteSecondsOffset.get()); } private synchronized void syncReceived(final RaopRtpPacket.Sync syncPacket) { if (!m_remoteSecondsOffset.isEmpty()) { /* If the times are synchronized, we can correct for the transmission * time of the sync packet since it contains the time it was sent as * a source's NTP time. */ m_audioClock.setFrameTime( syncPacket.getTimeStampMinusLatency(), convertRemoteToLocalSecondsTime(syncPacket.getTime().getDouble()) ); } else { /* If the times aren't yet synchronized, we simply assume the sync * packet's transmission time is zero. */ m_audioClock.setFrameTime( syncPacket.getTimeStampMinusLatency(), 0.0 ); s_logger.warning("Times synchronized, cannot correct latency of sync packet"); } } /** * Convert remote NTP time (in seconds) to local NTP time (in seconds), * using the offset obtain from the TimingRequest/TimingResponse packets. * * @param remoteSecondsTime remote NTP time * @return local NTP time */ private double convertRemoteToLocalSecondsTime(final double remoteSecondsTime) { return remoteSecondsTime - m_remoteSecondsOffset.get(); } }
7,238
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
LogFormatter.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/LogFormatter.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.io.PrintWriter; import java.io.StringWriter; import java.text.*; import java.util.Date; import java.util.logging.*; /** * Java.util.logging single-line log formatter */ public class LogFormatter extends Formatter { static final DateFormat DateFormater = new SimpleDateFormat("yyyy.MM.dd HH:mm.ss.SSS"); @Override public String format(final LogRecord record) { final StringBuilder s = new StringBuilder(); s.append(DateFormater.format(new Date(record.getMillis()))); s.append(" "); s.append(record.getLevel() != null ? record.getLevel().getName() : "?"); s.append(" "); s.append(record.getLoggerName() != null ? record.getLoggerName() : ""); s.append(" "); s.append(record.getMessage() != null ? record.getMessage() : ""); if (record.getThrown() != null) { String stackTrace; { final Throwable throwable = record.getThrown(); final StringWriter stringWriter = new StringWriter(); final PrintWriter stringPrintWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stringPrintWriter); stringPrintWriter.flush(); stackTrace = stringWriter.toString(); } s.append(String.format("%n")); s.append(stackTrace); } s.append(String.format("%n")); return s.toString(); } }
1,979
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
AirReceiver.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/AirReceiver.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.List; import java.util.Properties; import java.util.concurrent.*; import java.util.logging.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.jmdns.*; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.group.*; import org.jboss.netty.channel.socket.nio.*; import org.jboss.netty.handler.execution.*; public class AirReceiver { /* Load java.util.logging configuration */ static { final InputStream loggingPropertiesStream = AirReceiver.class.getClassLoader().getResourceAsStream("logging.properties"); try { LogManager.getLogManager().readConfiguration(loggingPropertiesStream); } catch (final IOException e) { throw new RuntimeException(e.getMessage(), e); } } private static final Logger s_logger = Logger.getLogger(AirReceiver.class.getName()); public static final String Version = getVersion(); /** * The hardware (MAC) address of the emulated Airport Express */ public static final byte[] HardwareAddressBytes = getHardwareAddress(); /** * The hardware (MAC) address as a hexadecimal string */ public static final String HardwareAddressString = toHexString(HardwareAddressBytes); /** * The hostname of the emulated Airport Express */ public static final String HostName = getHostName(); /** * The AirTunes/RAOP service type */ public static final String AirtunesServiceType = "_raop._tcp.local."; /** * The AirTunes/RAOP RTSP port */ public static final short AirtunesServiceRTSPPort = 5000; /** * The AirTunes/RAOP M-DNS service properties (TXT record) */ public static final Map<String, String> AirtunesServiceProperties = map( "txtvers", "1", "tp", "UDP", "ch", "2", "ss", "16", "sr", "44100", "pw", "false", "sm", "false", "sv", "false", "ek", "1", "et", "0,1", "cn", "0,1", "vn", "3" ); /** * Global executor service. Used e.g. to initialize the various netty channel factories */ public static final ExecutorService ExecutorService = Executors.newCachedThreadPool(); /** * Channel execution handler. Spreads channel message handling over multiple threads */ public static final ExecutionHandler ChannelExecutionHandler = new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor(4, 0, 0) ); /** * Message dispayed in the "About" dialog */ private static final String AboutMessage = " * AirReceiver " + Version + " *\n" + "\n" + "Copyright (c) 2011 Florian G. Pflug\n" + "\n" + "AirReceiver is free software: you can redistribute it and/or modify\n" + "it under the terms of the GNU General Public License as published by\n" + "the Free Software Foundation, either version 3 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "AirReceiver is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU General Public License for more details.\n" + "\n" + "You should have received a copy of the GNU General Public License\n" + "along with AirReceiver. If not, see <http://www.gnu.org/licenses/>." + "\n\n" + " * Java ALAC Decoder *\n" + "\n" + "Copyright (c) 2011 Peter McQuillan"; /** * JmDNS instances (one per IP address). Used to unregister the mDNS services * during shutdown. */ private static final List<JmDNS> s_jmDNSInstances = new java.util.LinkedList<JmDNS>(); /** * All open RTSP channels. Used to close all open challens during shutdown. */ private static ChannelGroup s_allChannels = new DefaultChannelGroup(); /** * Channel handle that registeres the channel to be closed on shutdown */ public static final ChannelHandler CloseChannelOnShutdownHandler = new SimpleChannelUpstreamHandler() { @Override public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { s_allChannels.add(e.getChannel()); super.channelOpen(ctx, e); } }; /** * Map factory. Creates a Map from a list of keys and values * * @param keys_values key1, value1, key2, value2, ... * @return a map mapping key1 to value1, key2 to value2, ... */ private static Map<String, String> map(final String... keys_values) { assert keys_values.length % 2 == 0; final Map<String, String> map = new java.util.HashMap<String, String>(keys_values.length / 2); for(int i=0; i < keys_values.length; i+=2) map.put(keys_values[i], keys_values[i+1]); return Collections.unmodifiableMap(map); } /** * Decides whether or nor a given MAC address is the address of some * virtual interface, like e.g. VMware's host-only interface (server-side). * * @param addr a MAC address * @return true if the MAC address is unsuitable as the device's hardware address */ public static boolean isBlockedHardwareAddress(final byte[] addr) { if ((addr[0] & 0x02) != 0) /* Locally administered */ return true; else if ((addr[0] == 0x00) && (addr[1] == 0x50) && (addr[2] == 0x56)) /* VMware */ return true; else if ((addr[0] == 0x00) && (addr[1] == 0x1C) && (addr[2] == 0x42)) /* Parallels */ return true; else if ((addr[0] == 0x00) && (addr[1] == 0x25) && (addr[2] == (byte)0xAE)) /* Microsoft */ return true; else return false; } /** * Reads the version from the version.properties file * @return the version */ private static String getVersion() { Properties versionProperties = new Properties(); final InputStream versionPropertiesStream = AirReceiver.class.getClassLoader().getResourceAsStream("version.properties"); try { versionProperties.load(versionPropertiesStream); } catch (final IOException e) { throw new RuntimeException(e.getMessage(), e); } return versionProperties.getProperty("org.phlo.AirReceiver.version"); } /** * Returns a suitable hardware address. * * @return a MAC address */ private static byte[] getHardwareAddress() { try { /* Search network interfaces for an interface with a valid, non-blocked hardware address */ for(final NetworkInterface iface: Collections.list(NetworkInterface.getNetworkInterfaces())) { if (iface.isLoopback()) continue; if (iface.isPointToPoint()) continue; try { final byte[] ifaceMacAddress = iface.getHardwareAddress(); if ((ifaceMacAddress != null) && (ifaceMacAddress.length == 6) && !isBlockedHardwareAddress(ifaceMacAddress)) { s_logger.info("Hardware address is " + toHexString(ifaceMacAddress) + " (" + iface.getDisplayName() + ")"); return Arrays.copyOfRange(ifaceMacAddress, 0, 6); } } catch (final Throwable e) { /* Ignore */ } } } catch (final Throwable e) { /* Ignore */ } /* Fallback to the IP address padded to 6 bytes */ try { final byte[] hostAddress = Arrays.copyOfRange(InetAddress.getLocalHost().getAddress(), 0, 6); s_logger.info("Hardware address is " + toHexString(hostAddress) + " (IP address)"); return hostAddress; } catch (final Throwable e) { /* Ignore */ } /* Fallback to a constant */ s_logger.info("Hardware address is 00DEADBEEF00 (last resort)"); return new byte[] {(byte)0x00, (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF, (byte)0x00}; } /** * Returns the machine's host name * * @return the host name */ private static String getHostName() { try { return InetAddress.getLocalHost().getHostName().split("\\.")[0]; } catch (final Throwable e) { return "AirReceiver"; } } /** * Converts an array of bytes to a hexadecimal string * * @param bytes array of bytes * @return hexadecimal representation */ private static String toHexString(final byte[] bytes) { final StringBuilder s = new StringBuilder(); for(final byte b: bytes) { final String h = Integer.toHexString(0x100 | b); s.append(h.substring(h.length() - 2, h.length()).toUpperCase()); } return s.toString(); } /** * Shuts the AirReceiver down gracefully */ public static void onShutdown() { /* Close channels */ final ChannelGroupFuture allChannelsClosed = s_allChannels.close(); /* Stop all mDNS responders */ synchronized(s_jmDNSInstances) { for(final JmDNS jmDNS: s_jmDNSInstances) { try { jmDNS.unregisterAllServices(); s_logger.info("Unregistered all services on " + jmDNS.getInterface()); } catch (final IOException e) { s_logger.info("Failed to unregister some services"); } } } /* Wait for all channels to finish closing */ allChannelsClosed.awaitUninterruptibly(); /* Stop the ExecutorService */ ExecutorService.shutdown(); /* Release the OrderedMemoryAwareThreadPoolExecutor */ ChannelExecutionHandler.releaseExternalResources(); } public static void main(final String[] args) throws Exception { /* Make sure AirReceiver shuts down gracefully */ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { onShutdown(); } })); /* Create about dialog */ final Dialog aboutDialog = new Dialog((Dialog)null); final GridBagLayout aboutLayout = new GridBagLayout(); aboutDialog.setLayout(aboutLayout); aboutDialog.setVisible(false); aboutDialog.setTitle("About AirReceiver"); aboutDialog.setResizable(false); { /* Message */ final TextArea title = new TextArea(AboutMessage.split("\n").length + 1, 64); title.setText(AboutMessage); title.setEditable(false); final GridBagConstraints titleConstraints = new GridBagConstraints(); titleConstraints.gridx = 1; titleConstraints.gridy = 1; titleConstraints.fill = GridBagConstraints.HORIZONTAL; titleConstraints.insets = new Insets(0,0,0,0); aboutLayout.setConstraints(title, titleConstraints); aboutDialog.add(title); } { /* Done button */ final Button aboutDoneButton = new Button("Done"); aboutDoneButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { aboutDialog.setVisible(false); } }); final GridBagConstraints aboutDoneConstraints = new GridBagConstraints(); aboutDoneConstraints.gridx = 1; aboutDoneConstraints.gridy = 2; aboutDoneConstraints.anchor = GridBagConstraints.PAGE_END; aboutDoneConstraints.fill = GridBagConstraints.NONE; aboutDoneConstraints.insets = new Insets(0,0,0,0); aboutLayout.setConstraints(aboutDoneButton, aboutDoneConstraints); aboutDialog.add(aboutDoneButton); } aboutDialog.setVisible(false); aboutDialog.setLocationByPlatform(true); aboutDialog.pack(); /* Create tray icon */ final URL trayIconUrl = AirReceiver.class.getClassLoader().getResource("icon_32.png"); final TrayIcon trayIcon = new TrayIcon((new ImageIcon(trayIconUrl, "AirReceiver").getImage())); trayIcon.setToolTip("AirReceiver"); trayIcon.setImageAutoSize(true); final PopupMenu popupMenu = new PopupMenu(); final MenuItem aboutMenuItem = new MenuItem("About"); aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { aboutDialog.setLocationByPlatform(true); aboutDialog.setVisible(true); } }); popupMenu.add(aboutMenuItem); final MenuItem exitMenuItem = new MenuItem("Quit"); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { onShutdown(); System.exit(0); } }); popupMenu.add(exitMenuItem); trayIcon.setPopupMenu(popupMenu); SystemTray.getSystemTray().add(trayIcon); /* Create AirTunes RTSP server */ final ServerBootstrap airTunesRtspBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(ExecutorService, ExecutorService)); airTunesRtspBootstrap.setPipelineFactory(new RaopRtspPipelineFactory()); airTunesRtspBootstrap.setOption("reuseAddress", true); airTunesRtspBootstrap.setOption("child.tcpNoDelay", true); airTunesRtspBootstrap.setOption("child.keepAlive", true); s_allChannels.add(airTunesRtspBootstrap.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), AirtunesServiceRTSPPort))); s_logger.info("Launched RTSP service on port " + AirtunesServiceRTSPPort); /* Create mDNS responders. */ synchronized(s_jmDNSInstances) { for(final NetworkInterface iface: Collections.list(NetworkInterface.getNetworkInterfaces())) { if (iface.isLoopback()) continue; if (iface.isPointToPoint()) continue; if (!iface.isUp()) continue; for(final InetAddress addr: Collections.list(iface.getInetAddresses())) { if (!(addr instanceof Inet4Address) && !(addr instanceof Inet6Address)) continue; try { /* Create mDNS responder for address */ final JmDNS jmDNS = JmDNS.create(addr, HostName + "-jmdns"); s_jmDNSInstances.add(jmDNS); /* Publish RAOP service */ final ServiceInfo airTunesServiceInfo = ServiceInfo.create( AirtunesServiceType, HardwareAddressString + "@" + HostName + " (" + iface.getName() + ")", AirtunesServiceRTSPPort, 0 /* weight */, 0 /* priority */, AirtunesServiceProperties ); jmDNS.registerService(airTunesServiceInfo); s_logger.info("Registered AirTunes service '" + airTunesServiceInfo.getName() + "' on " + addr); } catch (final Throwable e) { s_logger.log(Level.SEVERE, "Failed to publish service on " + addr, e); } } } } } }
14,695
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
ProtocolException.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/ProtocolException.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; @SuppressWarnings("serial") public class ProtocolException extends Exception { ProtocolException(final String message) { super(message); } }
863
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
AudioOutputQueue.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/AudioOutputQueue.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.Arrays; import java.util.concurrent.ConcurrentSkipListMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.*; /** * Audio output queue. * * Serves an an {@link AudioClock} and allows samples to be queued * for playback at a specific time. */ public class AudioOutputQueue implements AudioClock { private static Logger s_logger = Logger.getLogger(AudioOutputQueue.class.getName()); private static final double QueueLengthMaxSeconds = 10; private static final double BufferSizeSeconds = 0.05; private static final double TimingPrecision = 0.001; /** * Signals that the queue is being closed. * Never transitions from true to false! */ private volatile boolean m_closing = false; /** * The line's audio format */ private final AudioFormat m_format; /** * True if the line's audio format is signed but * the requested format was unsigned */ private final boolean m_convertUnsignedToSigned; /** * Bytes per frame, i.e. number of bytes * per sample times the number of channels */ private final int m_bytesPerFrame; /** * Sample rate */ private final double m_sampleRate; /** * Average packet size in frames. * We use this as the number of silence frames * to write on a queue underrun */ private final int m_packetSizeFrames; /** * JavaSounds audio output line */ private final SourceDataLine m_line; /** * The last frame written to the line. * Used to generate filler data */ private final byte[] m_lineLastFrame; /** * Packet queue, indexed by playback time */ private final ConcurrentSkipListMap<Long, byte[]> m_queue = new ConcurrentSkipListMap<Long, byte[]>(); /** * Enqueuer thread */ private final Thread m_queueThread = new Thread(new EnQueuer()); /** * Number of frames appended to the line */ private long m_lineFramesWritten = 0; /** * Largest frame time seen so far */ private long m_latestSeenFrameTime = 0; /** * The frame time corresponding to line time zero */ private long m_frameTimeOffset = 0; /** * The seconds time corresponding to line time zero */ private final double m_secondsTimeOffset; /** * Requested line gain */ private float m_requestedGain = 0.0f; /** * Enqueuer thread */ private class EnQueuer implements Runnable { /** * Enqueuer thread main method */ @Override public void run() { try { /* Mute line initially to prevent clicks */ setLineGain(Float.NEGATIVE_INFINITY); /* Start the line */ m_line.start(); boolean lineMuted = true; boolean didWarnGap = false; while (!m_closing) { if (!m_queue.isEmpty()) { /* Queue filled */ /* If the gap between the next packet and the end of line is * negligible (less than one packet), we write it to the line. * Otherwise, we fill the line buffer with silence and hope for * further packets to appear in the queue */ final long entryFrameTime = m_queue.firstKey(); final long entryLineTime = convertFrameToLineTime(entryFrameTime); final long gapFrames = entryLineTime - getNextLineTime(); if (gapFrames < -m_packetSizeFrames) { /* Too late for playback */ s_logger.warning("Audio data was scheduled for playback " + (-gapFrames) + " frames ago, skipping"); m_queue.remove(entryFrameTime); continue; } else if (gapFrames < m_packetSizeFrames) { /* Negligible gap between packet and line end. Prepare packet for playback */ didWarnGap = false; /* Unmute line in case it was muted previously */ if (lineMuted) { s_logger.info("Audio data available, un-muting line"); lineMuted = false; applyGain(); } else if (getLineGain() != m_requestedGain) { applyGain(); } /* Get sample data and do sanity checks */ final byte[] nextPlaybackSamples = m_queue.remove(entryFrameTime); int nextPlaybackSamplesLength = nextPlaybackSamples.length; if (nextPlaybackSamplesLength % m_bytesPerFrame != 0) { s_logger.severe("Audio data contains non-integral number of frames, ignore last " + (nextPlaybackSamplesLength % m_bytesPerFrame) + " bytes"); nextPlaybackSamplesLength -= nextPlaybackSamplesLength % m_bytesPerFrame; } /* Append packet to line */ s_logger.finest("Audio data containing " + nextPlaybackSamplesLength / m_bytesPerFrame + " frames for playback time " + entryFrameTime + " found in queue, appending to the output line"); appendFrames(nextPlaybackSamples, 0, nextPlaybackSamplesLength, entryLineTime); continue; } else { /* Gap between packet and line end. Warn */ if (!didWarnGap) { didWarnGap = true; s_logger.warning("Audio data missing for frame time " + getNextLineTime() + " (currently " + gapFrames + " frames), writing " + m_packetSizeFrames + " frames of silence"); } } } else { /* Queue empty */ if (!lineMuted) { lineMuted = true; setLineGain(Float.NEGATIVE_INFINITY); s_logger.fine("Audio data ended at frame time " + getNextLineTime() + ", writing " + m_packetSizeFrames + " frames of silence and muted line"); } } appendSilence(m_packetSizeFrames); } /* Before we exit, we fill the line's buffer with silence. This should prevent * noise from being output while the line is being stopped */ appendSilence(m_line.available() / m_bytesPerFrame); } catch (final Throwable e) { s_logger.log(Level.SEVERE, "Audio output thread died unexpectedly", e); } finally { setLineGain(Float.NEGATIVE_INFINITY); m_line.stop(); m_line.close(); } } /** * Append the range [off,off+len) from the provided sample data to the line. * If the requested playback time does not match the line end time, samples are * skipped or silence is inserted as necessary. If the data is marked as being * just a filler, some warnings are suppressed. * * @param samples sample data * @param off sample data offset * @param len sample data length * @param time playback time * @param warnNonContinous warn about non-continous samples */ private void appendFrames(final byte[] samples, int off, final int len, long lineTime) { assert off % m_bytesPerFrame == 0; assert len % m_bytesPerFrame == 0; while (true) { /* Fetch line end time only once per iteration */ final long endLineTime = getNextLineTime(); final long timingErrorFrames = lineTime - endLineTime; final double timingErrorSeconds = timingErrorFrames / m_sampleRate; if (Math.abs(timingErrorSeconds) <= TimingPrecision) { /* Samples to append scheduled exactly at line end. Just append them and be done */ appendFrames(samples, off, len); break; } else if (timingErrorFrames > 0) { /* Samples to append scheduled after the line end. Fill the gap with silence */ s_logger.warning("Audio output non-continous (gap of " + timingErrorFrames + " frames), filling with silence"); appendSilence((int)(lineTime - endLineTime)); } else if (timingErrorFrames < 0) { /* Samples to append scheduled before the line end. Remove the overlapping * part and retry */ s_logger.warning("Audio output non-continous (overlap of " + (-timingErrorFrames) + "), skipping overlapping frames"); off += (endLineTime - lineTime) * m_bytesPerFrame; lineTime += endLineTime - lineTime; } else { /* Strange universe... */ assert false; } } } private void appendSilence(final int frames) { final byte[] silenceFrames = new byte[frames * m_bytesPerFrame]; for(int i = 0; i < silenceFrames.length; ++i) silenceFrames[i] = m_lineLastFrame[i % m_bytesPerFrame]; appendFrames(silenceFrames, 0, silenceFrames.length); } /** * Append the range [off,off+len) from the provided sample data to the line. * * @param samples sample data * @param off sample data offset * @param len sample data length */ private void appendFrames(final byte[] samples, int off, int len) { assert off % m_bytesPerFrame == 0; assert len % m_bytesPerFrame == 0; /* Make sure that [off,off+len) does not exceed sample's bounds */ off = Math.min(off, (samples != null) ? samples.length : 0); len = Math.min(len, (samples != null) ? samples.length - off : 0); if (len <= 0) return; /* Convert samples if necessary */ final byte[] samplesConverted = Arrays.copyOfRange(samples, off, off+len); if (m_convertUnsignedToSigned) { /* The line expects signed PCM samples, so we must * convert the unsigned PCM samples to signed. * Note that this only affects the high bytes! */ for(int i=0; i < samplesConverted.length; i += 2) samplesConverted[i] = (byte)((samplesConverted[i] & 0xff) - 0x80); } /* Write samples to line */ final int bytesWritten = m_line.write(samplesConverted, 0, samplesConverted.length); if (bytesWritten != len) s_logger.warning("Audio output line accepted only " + bytesWritten + " bytes of sample data while trying to write " + samples.length + " bytes"); /* Update state */ synchronized(AudioOutputQueue.this) { m_lineFramesWritten += bytesWritten / m_bytesPerFrame; for(int b=0; b < m_bytesPerFrame; ++b) m_lineLastFrame[b] = samples[off + len - (m_bytesPerFrame - b)]; s_logger.finest("Audio output line end is now at " + getNextLineTime() + " after writing " + len / m_bytesPerFrame + " frames"); } } } AudioOutputQueue(final AudioStreamInformationProvider streamInfoProvider) throws LineUnavailableException { final AudioFormat audioFormat = streamInfoProvider.getAudioFormat(); /* OSX does not support unsigned PCM lines. We thust always request * a signed line, and convert from unsigned to signed if necessary */ if (AudioFormat.Encoding.PCM_SIGNED.equals(audioFormat.getEncoding())) { m_format = audioFormat; m_convertUnsignedToSigned = false; } else if (AudioFormat.Encoding.PCM_UNSIGNED.equals(audioFormat.getEncoding())) { m_format = new AudioFormat( audioFormat.getSampleRate(), audioFormat.getSampleSizeInBits(), audioFormat.getChannels(), true, audioFormat.isBigEndian() ); m_convertUnsignedToSigned = true; } else { throw new LineUnavailableException("Audio encoding " + audioFormat.getEncoding() + " is not supported"); } /* Audio format-dependent stuff */ m_packetSizeFrames = streamInfoProvider.getFramesPerPacket(); m_bytesPerFrame = m_format.getChannels() * m_format.getSampleSizeInBits() / 8; m_sampleRate = m_format.getSampleRate(); m_lineLastFrame = new byte[m_bytesPerFrame]; for(int b=0; b < m_lineLastFrame.length; ++b) m_lineLastFrame[b] = (b % 2 == 0) ? (byte)-128 : (byte)0; /* Compute desired line buffer size and obtain a line */ final int desiredBufferSize = (int)Math.pow(2, Math.ceil(Math.log(BufferSizeSeconds * m_sampleRate * m_bytesPerFrame) / Math.log(2.0))); final DataLine.Info lineInfo = new DataLine.Info( SourceDataLine.class, m_format, desiredBufferSize ); m_line = (SourceDataLine)AudioSystem.getLine(lineInfo); m_line.open(m_format, desiredBufferSize); s_logger.info("Audio output line created and openend. Requested buffer of " + desiredBufferSize / m_bytesPerFrame + " frames, got " + m_line.getBufferSize() / m_bytesPerFrame + " frames"); /* Start enqueuer thread and wait for the line to start. * The wait guarantees that the AudioClock functions return * sensible values right after construction */ m_queueThread.setDaemon(true); m_queueThread.setName("Audio Enqueuer"); m_queueThread.setPriority(Thread.MAX_PRIORITY); m_queueThread.start(); while (m_queueThread.isAlive() && !m_line.isActive()) Thread.yield(); /* Initialize the seconds time offset now that the line is running. */ m_secondsTimeOffset = 2208988800.0 + System.currentTimeMillis() * 1e-3; } /** * Sets the line's MASTER_GAIN control to the provided value, * or complains to the log of the line does not support a MASTER_GAIN control * * @param gain gain to set */ private void setLineGain(final float gain) { if (m_line.isControlSupported(FloatControl.Type.MASTER_GAIN)) { /* Bound gain value by min and max declared by the control */ final FloatControl gainControl = (FloatControl)m_line.getControl(FloatControl.Type.MASTER_GAIN); if (gain < gainControl.getMinimum()) gainControl.setValue(gainControl.getMinimum()); else if (gain > gainControl.getMaximum()) gainControl.setValue(gainControl.getMaximum()); else gainControl.setValue(gain); } else s_logger.severe("Audio output line doesn not support volume control"); } /** * Returns the line's MASTER_GAIN control's value. */ private float getLineGain() { if (m_line.isControlSupported(FloatControl.Type.MASTER_GAIN)) { /* Bound gain value by min and max declared by the control */ final FloatControl gainControl = (FloatControl)m_line.getControl(FloatControl.Type.MASTER_GAIN); return gainControl.getValue(); } else { s_logger.severe("Audio output line doesn not support volume control"); return 0.0f; } } private synchronized void applyGain() { setLineGain(m_requestedGain); } /** * Sets the desired output gain. * * @param gain desired gain */ public synchronized void setGain(final float gain) { m_requestedGain = gain; } /** * Returns the desired output gain. * * @param gain desired gain */ public synchronized float getGain() { return m_requestedGain; } /** * Stops audio output */ public void close() { m_closing = true; m_queueThread.interrupt(); } /** * Adds sample data to the queue * * @param playbackRemoteStartFrameTime start time of sample data * @param playbackSamples sample data * @return true if the sample data was added to the queue */ public synchronized boolean enqueue(final long frameTime, final byte[] frames) { /* Playback time of packet */ final double packetSeconds = (double)frames.length / (double)(m_bytesPerFrame * m_sampleRate); /* Compute playback delay, i.e., the difference between the last sample's * playback time and the current line time */ final double delay = (convertFrameToLineTime(frameTime) + frames.length / m_bytesPerFrame - getNextLineTime()) / m_sampleRate; m_latestSeenFrameTime = Math.max(m_latestSeenFrameTime, frameTime); if (delay < -packetSeconds) { /* The whole packet is scheduled to be played in the past */ s_logger.warning("Audio data arrived " + -(delay) + " seconds too late, dropping"); return false; } else if (delay > QueueLengthMaxSeconds) { /* The packet extends further into the future that our maximum queue size. * We reject it, since this is probably the result of some timing discrepancies */ s_logger.warning("Audio data arrived " + delay + " seconds too early, dropping"); return false; } m_queue.put(frameTime, frames); return true; } /** * Removes all currently queued sample data */ public void flush() { m_queue.clear(); } @Override public synchronized void setFrameTime(final long frameTime, final double secondsTime) { final double ageSeconds = getNowSecondsTime() - secondsTime; final long lineTime = Math.round((secondsTime - m_secondsTimeOffset) * m_sampleRate); final long frameTimeOffsetPrevious = m_frameTimeOffset; m_frameTimeOffset = frameTime - lineTime; s_logger.fine("Frame time adjusted by " + (m_frameTimeOffset - frameTimeOffsetPrevious) + " based on timing information " + ageSeconds + " seconds old and " + (m_latestSeenFrameTime - frameTime) + " frames before latest seen frame time"); } @Override public double getNowSecondsTime() { return m_secondsTimeOffset + getNowLineTime() / m_sampleRate; } @Override public long getNowFrameTime() { return m_frameTimeOffset + getNowLineTime(); } @Override public double getNextSecondsTime() { return m_secondsTimeOffset + getNextLineTime() / m_sampleRate; } @Override public long getNextFrameTime() { return m_frameTimeOffset + getNextLineTime(); } @Override public double convertFrameToSecondsTime(final long frameTime) { return m_secondsTimeOffset + (frameTime - m_frameTimeOffset) / m_sampleRate; } private synchronized long getNextLineTime() { return m_lineFramesWritten; } private long getNowLineTime() { return m_line.getLongFramePosition(); } private synchronized long convertFrameToLineTime(final long entryFrameTime) { return entryFrameTime - m_frameTimeOffset; } }
17,495
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RunningWeightedAverage.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RunningWeightedAverage.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; public class RunningWeightedAverage { public final int m_length; public final double m_values[]; public final double m_weights[]; public boolean m_empty = true; public int m_index = 0; public double m_average = Double.NaN; RunningWeightedAverage(final int windowLength) { m_length = windowLength; m_values = new double[m_length]; m_weights = new double[m_length]; } public boolean isEmpty() { return m_empty; } public void add(final double value, final double weight) { m_values[m_index] = value; m_weights[m_index] = weight; m_index = (m_index + 1) % m_length; m_average = Double.NaN; m_empty = false; } public double get() { if (!m_empty && Double.isNaN(m_average)) { double vsum = 0; double wsum = 0; for(int i=0; i < m_length; ++i) { vsum += m_values[i] * m_weights[i]; wsum += m_weights[i]; } if (wsum != 0.0) m_average = vsum / wsum; } return m_average; } }
1,652
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtspErrorResponseHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtspErrorResponseHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.*; /** * Sends an RTSP error response if one of the channel handlers * throws an exception. */ public class RtspErrorResponseHandler extends SimpleChannelHandler { /** * Prevents an infinite loop that otherwise occurs if * write()ing the exception response itself triggers * an exception (which we will then attempt to write(), * triggering the same exception, ...) * We avoid that loop by dropping all exception events * after the first one. */ private boolean m_messageTriggeredException = false; @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { synchronized(this) { m_messageTriggeredException = false; } super.messageReceived(ctx, evt); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent evt) throws Exception { synchronized(this) { if (m_messageTriggeredException) return; m_messageTriggeredException = true; } if (ctx.getChannel().isConnected()) { final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.INTERNAL_SERVER_ERROR); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } } }
2,074
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopAudioHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopAudioHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.net.*; import java.nio.charset.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.*; import javax.crypto.*; import javax.crypto.spec.*; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; import org.jboss.netty.channel.group.*; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.*; /** * Handles the configuration, creation and destruction of RTP channels. */ public class RaopAudioHandler extends SimpleChannelUpstreamHandler { private static Logger s_logger = Logger.getLogger(RaopAudioHandler.class.getName()); /** * The RTP channel type */ static enum RaopRtpChannelType { Audio, Control, Timing }; private static final String HeaderTransport = "Transport"; private static final String HeaderSession = "Session"; /** * Routes incoming packets from the control and timing channel to * the audio channel */ private class RaopRtpInputToAudioRouterUpstreamHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { /* Get audio channel from the enclosing RaopAudioHandler */ Channel audioChannel = null; synchronized(RaopAudioHandler.this) { audioChannel = m_audioChannel; } if ((m_audioChannel != null) && m_audioChannel.isOpen() && m_audioChannel.isReadable()) { audioChannel.getPipeline().sendUpstream(new UpstreamMessageEvent( audioChannel, evt.getMessage(), evt.getRemoteAddress()) ); } } } /** * Routes outgoing packets on audio channel to the control or timing * channel if appropriate */ private class RaopRtpAudioToOutputRouterDownstreamHandler extends SimpleChannelDownstreamHandler { @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final RaopRtpPacket packet = (RaopRtpPacket)evt.getMessage(); /* Get control and timing channel from the enclosing RaopAudioHandler */ Channel controlChannel = null; Channel timingChannel = null; synchronized(RaopAudioHandler.this) { controlChannel = m_controlChannel; timingChannel = m_timingChannel; } if (packet instanceof RaopRtpPacket.RetransmitRequest) { if ((controlChannel != null) && controlChannel.isOpen() && controlChannel.isWritable()) controlChannel.write(evt.getMessage()); } else if (packet instanceof RaopRtpPacket.TimingRequest) { if ((timingChannel != null) && timingChannel.isOpen() && timingChannel.isWritable()) timingChannel.write(evt.getMessage()); } else { super.writeRequested(ctx, evt); } } } /** * Places incoming audio data on the audio output queue * */ public class RaopRtpAudioEnqueueHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { if (!(evt.getMessage() instanceof RaopRtpPacket.Audio)) { super.messageReceived(ctx, evt); return; } final RaopRtpPacket.Audio audioPacket = (RaopRtpPacket.Audio)evt.getMessage(); /* Get audio output queue from the enclosing RaopAudioHandler */ AudioOutputQueue audioOutputQueue; synchronized(RaopAudioHandler.this) { audioOutputQueue = m_audioOutputQueue; } if (audioOutputQueue != null) { final byte[] samples = new byte[audioPacket.getPayload().capacity()]; audioPacket.getPayload().getBytes(0, samples); m_audioOutputQueue.enqueue(audioPacket.getTimeStamp(), samples); if (s_logger.isLoggable(Level.FINEST)) s_logger.finest("Packet with sequence " + audioPacket.getSequence() + " for playback at " + audioPacket.getTimeStamp() + " submitted to audio output queue"); } else { s_logger.warning("No audio queue available, dropping packet"); } super.messageReceived(ctx, evt); } } /** * RSA cipher used to decrypt the AES session key */ private final Cipher m_rsaPkCS1OaepCipher = AirTunesCrytography.getCipher("RSA/None/OAEPWithSHA1AndMGF1Padding"); /** * Executor service used for the RTP channels */ private final ExecutorService m_rtpExecutorService; private final ChannelHandler m_exceptionLoggingHandler = new ExceptionLoggingHandler(); private final ChannelHandler m_decodeHandler = new RaopRtpDecodeHandler(); private final ChannelHandler m_encodeHandler = new RtpEncodeHandler(); private final ChannelHandler m_packetLoggingHandler = new RtpLoggingHandler(); private final ChannelHandler m_inputToAudioRouterDownstreamHandler = new RaopRtpInputToAudioRouterUpstreamHandler(); private final ChannelHandler m_audioToOutputRouterUpstreamHandler = new RaopRtpAudioToOutputRouterDownstreamHandler(); private ChannelHandler m_decryptionHandler; private ChannelHandler m_audioDecodeHandler; private ChannelHandler m_resendRequestHandler; private ChannelHandler m_timingHandler; private final ChannelHandler m_audioEnqueueHandler = new RaopRtpAudioEnqueueHandler(); private AudioStreamInformationProvider m_audioStreamInformationProvider; private AudioOutputQueue m_audioOutputQueue; /** * All RTP channels belonging to this RTSP connection */ private final ChannelGroup m_rtpChannels = new DefaultChannelGroup(); private Channel m_audioChannel; private Channel m_controlChannel; private Channel m_timingChannel; /** * Creates an instance, using the ExecutorService for the RTP channel's datagram socket factory * @param rtpExecutorService */ public RaopAudioHandler(final ExecutorService rtpExecutorService) { m_rtpExecutorService = rtpExecutorService; reset(); } /** * Resets stream-related data (i.e. undoes the effect of ANNOUNCE, SETUP and RECORD */ private void reset() { if (m_audioOutputQueue != null) m_audioOutputQueue.close(); m_rtpChannels.close(); m_decryptionHandler = null; m_audioDecodeHandler = null; m_resendRequestHandler = null; m_timingHandler = null; m_audioStreamInformationProvider = null; m_audioOutputQueue = null; m_audioChannel = null; m_controlChannel = null; m_timingChannel = null; } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent evt) throws Exception { s_logger.info("RTSP connection was shut down, closing RTP channels and audio output queue"); synchronized(this) { reset(); } super.channelClosed(ctx, evt); } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); final HttpMethod method = req.getMethod(); if (RaopRtspMethods.ANNOUNCE.equals(method)) { announceReceived(ctx, req); return; } else if (RaopRtspMethods.SETUP.equals(method)) { setupReceived(ctx, req); return; } else if (RaopRtspMethods.RECORD.equals(method)) { recordReceived(ctx, req); return; } else if (RaopRtspMethods.FLUSH.equals(method)) { flushReceived(ctx, req); return; } else if (RaopRtspMethods.TEARDOWN.equals(method)) { teardownReceived(ctx, req); return; } else if (RaopRtspMethods.SET_PARAMETER.equals(method)) { setParameterReceived(ctx, req); return; } else if (RaopRtspMethods.GET_PARAMETER.equals(method)) { getParameterReceived(ctx, req); return; } super.messageReceived(ctx, evt); } /** * SDP line. Format is * <br> * {@code * <attribute>=<value> * } */ private static Pattern s_pattern_sdp_line = Pattern.compile("^([a-z])=(.*)$"); /** * SDP attribute {@code m}. Format is * <br> * {@code * <media> <port> <transport> <formats> * } * <p> * RAOP/AirTunes always required {@code <media>=audio, <transport>=RTP/AVP} * and only a single format is allowed. The port is ignored. */ private static Pattern s_pattern_sdp_m = Pattern.compile("^audio ([^ ]+) RTP/AVP ([0-9]+)$"); /** * SDP attribute {@code a}. Format is * <br> * {@code <flag>} * <br> * or * <br> * {@code <attribute>:<value>} * <p> * RAOP/AirTunes uses only the second case, with the attributes * <ul> * <li> {@code <attribute>=rtpmap} * <li> {@code <attribute>=fmtp} * <li> {@code <attribute>=rsaaeskey} * <li> {@code <attribute>=aesiv} * </ul> */ private static Pattern s_pattern_sdp_a = Pattern.compile("^([a-z]+):(.*)$"); /** * SDP {@code a} attribute {@code rtpmap}. Format is * <br> * {@code <format> <encoding>} * for RAOP/AirTunes instead of {@code <format> <encoding>/<clock rate>}. * <p> * RAOP/AirTunes always uses encoding {@code AppleLossless} */ private static Pattern s_pattern_sdp_a_rtpmap = Pattern.compile("^([0-9]+) (.*)$"); /** * Handles ANNOUNCE requests and creates an {@link AudioOutputQueue} and * the following handlers for RTP channels * <ul> * <li>{@link RaopRtpTimingHandler} * <li>{@link RaopRtpRetransmitRequestHandler} * <li>{@link RaopRtpAudioDecryptionHandler} * <li>{@link RaopRtpAudioAlacDecodeHandler} * </ul> */ public synchronized void announceReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception { /* ANNOUNCE must contain stream information in SDP format */ if (!req.containsHeader("Content-Type")) throw new ProtocolException("No Content-Type header"); if (!"application/sdp".equals(req.getHeader("Content-Type"))) throw new ProtocolException("Invalid Content-Type header, expected application/sdp but got " + req.getHeader("Content-Type")); reset(); /* Get SDP stream information */ final String dsp = req.getContent().toString(Charset.forName("ASCII")).replace("\r", ""); SecretKey aesKey = null; IvParameterSpec aesIv = null; int alacFormatIndex = -1; int audioFormatIndex = -1; int descriptionFormatIndex = -1; String[] formatOptions = null; for(final String line: dsp.split("\n")) { /* Split SDP line into attribute and setting */ final Matcher line_matcher = s_pattern_sdp_line.matcher(line); if (!line_matcher.matches()) throw new ProtocolException("Cannot parse SDP line " + line); final char attribute = line_matcher.group(1).charAt(0); final String setting = line_matcher.group(2); /* Handle attributes */ switch (attribute) { case 'm': /* Attribute m. Maps an audio format index to a stream */ final Matcher m_matcher = s_pattern_sdp_m.matcher(setting); if (!m_matcher.matches()) throw new ProtocolException("Cannot parse SDP " + attribute + "'s setting " + setting); audioFormatIndex = Integer.valueOf(m_matcher.group(2)); break; case 'a': /* Attribute a. Defines various session properties */ final Matcher a_matcher = s_pattern_sdp_a.matcher(setting); if (!a_matcher.matches()) throw new ProtocolException("Cannot parse SDP " + attribute + "'s setting " + setting); final String key = a_matcher.group(1); final String value = a_matcher.group(2); if ("rtpmap".equals(key)) { /* Sets the decoder for an audio format index */ final Matcher a_rtpmap_matcher = s_pattern_sdp_a_rtpmap.matcher(value); if (!a_rtpmap_matcher.matches()) throw new ProtocolException("Cannot parse SDP " + attribute + "'s rtpmap entry " + value); final int formatIdx = Integer.valueOf(a_rtpmap_matcher.group(1)); final String format = a_rtpmap_matcher.group(2); if ("AppleLossless".equals(format)) alacFormatIndex = formatIdx; } else if ("fmtp".equals(key)) { /* Sets the decoding parameters for a audio format index */ final String[] parts = value.split(" "); if (parts.length > 0) descriptionFormatIndex = Integer.valueOf(parts[0]); if (parts.length > 1) formatOptions = Arrays.copyOfRange(parts, 1, parts.length); } else if ("rsaaeskey".equals(key)) { /* Sets the AES key required to decrypt the audio data. The key is * encrypted wih the AirTunes private key */ byte[] aesKeyRaw; m_rsaPkCS1OaepCipher.init(Cipher.DECRYPT_MODE, AirTunesCrytography.PrivateKey); aesKeyRaw = m_rsaPkCS1OaepCipher.doFinal(Base64.decodeUnpadded(value)); aesKey = new SecretKeySpec(aesKeyRaw, "AES"); } else if ("aesiv".equals(key)) { /* Sets the AES initialization vector */ aesIv = new IvParameterSpec(Base64.decodeUnpadded(value)); } break; default: /* Ignore */ break; } } /* Validate SDP information */ /* The format index of the stream must match the format index from the rtpmap attribute */ if (alacFormatIndex != audioFormatIndex) throw new ProtocolException("Audio format " + audioFormatIndex + " not supported"); /* The format index from the rtpmap attribute must match the format index from the fmtp attribute */ if (audioFormatIndex != descriptionFormatIndex) throw new ProtocolException("Auido format " + audioFormatIndex + " lacks fmtp line"); /* The fmtp attribute must have contained format options */ if (formatOptions == null) throw new ProtocolException("Auido format " + audioFormatIndex + " incomplete, format options not set"); /* Create decryption handler if an AES key and IV was specified */ if ((aesKey != null) && (aesIv != null)) m_decryptionHandler = new RaopRtpAudioDecryptionHandler(aesKey, aesIv); /* Create an ALAC decoder. The ALAC decoder is our stream information provider */ final RaopRtpAudioAlacDecodeHandler handler = new RaopRtpAudioAlacDecodeHandler(formatOptions); m_audioStreamInformationProvider = handler; m_audioDecodeHandler = handler; /* Create audio output queue with the format information provided by the ALAC decoder */ m_audioOutputQueue = new AudioOutputQueue(m_audioStreamInformationProvider); /* Create timing handle, using the AudioOutputQueue as time source */ m_timingHandler = new RaopRtpTimingHandler(m_audioOutputQueue); /* Create retransmit request handler using the audio output queue as time source */ m_resendRequestHandler = new RaopRtpRetransmitRequestHandler(m_audioStreamInformationProvider, m_audioOutputQueue); final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); ctx.getChannel().write(response); } /** * {@code Transport} header option format. Format of a single option is * <br> * {@code <name>=<value>} * <br> * format of the {@code Transport} header is * <br> * {@code <protocol>;<name1>=<value1>;<name2>=<value2>;...} * <p> * For RAOP/AirTunes, {@code <protocol>} is always {@code RTP/AVP/UDP}. */ private static Pattern s_pattern_transportOption = Pattern.compile("^([A-Za-z0-9_-]+)(=(.*))?$"); /** * Handles SETUP requests and creates the audio, control and timing RTP channels */ public synchronized void setupReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException { /* Request must contain a Transport header */ if (!req.containsHeader(HeaderTransport)) throw new ProtocolException("No Transport header"); /* Split Transport header into individual options and prepare reponse options list */ final Deque<String> requestOptions = new java.util.LinkedList<String>(Arrays.asList(req.getHeader(HeaderTransport).split(";"))); final List<String> responseOptions = new java.util.LinkedList<String>(); /* Transport header. Protocol must be RTP/AVP/UDP */ final String requestProtocol = requestOptions.removeFirst(); if (!"RTP/AVP/UDP".equals(requestProtocol)) throw new ProtocolException("Transport protocol must be RTP/AVP/UDP, but was " + requestProtocol); responseOptions.add(requestProtocol); /* Parse incoming transport options and build response options */ for(final String requestOption: requestOptions) { /* Split option into key and value */ final Matcher m_transportOption = s_pattern_transportOption.matcher(requestOption); if (!m_transportOption.matches()) throw new ProtocolException("Cannot parse Transport option " + requestOption); final String key = m_transportOption.group(1); final String value = m_transportOption.group(3); if ("interleaved".equals(key)) { /* Probably means that two channels are interleaved in the stream. Included in the response options */ if (!"0-1".equals(value)) throw new ProtocolException("Unsupported Transport option, interleaved must be 0-1 but was " + value); responseOptions.add("interleaved=0-1"); } else if ("mode".equals(key)) { /* Means the we're supposed to receive audio data, not send it. Included in the response options */ if (!"record".equals(value)) throw new ProtocolException("Unsupported Transport option, mode must be record but was " + value); responseOptions.add("mode=record"); } else if ("control_port".equals(key)) { /* Port number of the client's control socket. Response includes port number of *our* control port */ final int clientControlPort = Integer.valueOf(value); m_controlChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 0), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientControlPort), RaopRtpChannelType.Control ); s_logger.info("Launched RTP control service on " + m_controlChannel.getLocalAddress()); responseOptions.add("control_port=" + ((InetSocketAddress)m_controlChannel.getLocalAddress()).getPort()); } else if ("timing_port".equals(key)) { /* Port number of the client's timing socket. Response includes port number of *our* timing port */ final int clientTimingPort = Integer.valueOf(value); m_timingChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 0), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientTimingPort), RaopRtpChannelType.Timing ); s_logger.info("Launched RTP timing service on " + m_timingChannel.getLocalAddress()); responseOptions.add("timing_port=" + ((InetSocketAddress)m_timingChannel.getLocalAddress()).getPort()); } else { /* Ignore unknown options */ responseOptions.add(requestOption); } } /* Create audio socket and include it's port in our response */ m_audioChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 0), null, RaopRtpChannelType.Audio ); s_logger.info("Launched RTP audio service on " + m_audioChannel.getLocalAddress()); responseOptions.add("server_port=" + ((InetSocketAddress)m_audioChannel.getLocalAddress()).getPort()); /* Build response options string */ final StringBuilder transportResponseBuilder = new StringBuilder(); for(final String responseOption: responseOptions) { if (transportResponseBuilder.length() > 0) transportResponseBuilder.append(";"); transportResponseBuilder.append(responseOption); } /* Send response */ final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.addHeader(HeaderTransport, transportResponseBuilder.toString()); response.addHeader(HeaderSession, "DEADBEEEF"); ctx.getChannel().write(response); } /** * Handles RECORD request. We did all the work during ANNOUNCE and SETUP, so there's nothing * more to do. * * iTunes reports the initial RTP sequence and playback time here, which would actually be * helpful. But iOS doesn't, so we ignore it all together. */ public synchronized void recordReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception { if (m_audioStreamInformationProvider == null) throw new ProtocolException("Audio stream not configured, cannot start recording"); s_logger.info("Client started streaming"); final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); ctx.getChannel().write(response); } /** * Handle FLUSH requests. * * iTunes reports the last RTP sequence and playback time here, which would actually be * helpful. But iOS doesn't, so we ignore it all together. */ private synchronized void flushReceived(final ChannelHandlerContext ctx, final HttpRequest req) { if (m_audioOutputQueue != null) m_audioOutputQueue.flush(); s_logger.info("Client paused streaming, flushed audio output queue"); final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); ctx.getChannel().write(response); } /** * Handle TEARDOWN requests. */ private synchronized void teardownReceived(final ChannelHandlerContext ctx, final HttpRequest req) { final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); ctx.getChannel().setReadable(false); ctx.getChannel().write(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { future.getChannel().close(); s_logger.info("RTSP connection closed after client initiated teardown"); } }); } /** * SET_PARAMETER syntax. Format is * <br> * {@code <parameter>: <value>} * <p> */ private static Pattern s_pattern_parameter = Pattern.compile("^([A-Za-z0-9_-]+): *(.*)$"); /** * Handle SET_PARAMETER request. Currently only {@code volume} is supported */ public synchronized void setParameterReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException { /* Body in ASCII encoding with unix newlines */ final String body = req.getContent().toString(Charset.forName("ASCII")).replace("\r", ""); /* Handle parameters */ for(final String line: body.split("\n")) { try { /* Split parameter into name and value */ final Matcher m_parameter = s_pattern_parameter.matcher(line); if (!m_parameter.matches()) throw new ProtocolException("Cannot parse line " + line); final String name = m_parameter.group(1); final String value = m_parameter.group(2); if ("volume".equals(name)) { /* Set output gain */ if (m_audioOutputQueue != null) m_audioOutputQueue.setGain(Float.parseFloat(value)); } } catch (final Throwable e) { throw new ProtocolException("Unable to parse line " + line); } } final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); ctx.getChannel().write(response); } /** * Handle GET_PARAMETER request. Currently only {@code volume} is supported */ public synchronized void getParameterReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException { final StringBuilder body = new StringBuilder(); if (m_audioOutputQueue != null) { /* Report output gain */ body.append("volume: "); body.append(m_audioOutputQueue.getGain()); body.append("\r\n"); } final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.setContent(ChannelBuffers.wrappedBuffer(body.toString().getBytes(Charset.forName("ASCII")))); ctx.getChannel().write(response); } /** * Creates an UDP socket and handler pipeline for RTP channels * * @param local local end-point address * @param remote remote end-point address * @param channelType channel type. Determines which handlers are put into the pipeline * @return open data-gram channel */ private Channel createRtpChannel(final SocketAddress local, final SocketAddress remote, final RaopRtpChannelType channelType) { /* Create bootstrap helper for a data-gram socket using NIO */ final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory(m_rtpExecutorService)); /* Set the buffer size predictor to 1500 bytes to ensure that * received packets will fit into the buffer. Packets are * truncated if they are larger than that! */ bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(1500)); /* Set the socket's receive buffer size. We set it to 1MB */ bootstrap.setOption("receiveBufferSize", 1024*1024); /* Set pipeline factory for the RTP channel */ bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { final ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("executionHandler", AirReceiver.ChannelExecutionHandler); pipeline.addLast("exceptionLogger", m_exceptionLoggingHandler); pipeline.addLast("decoder", m_decodeHandler); pipeline.addLast("encoder", m_encodeHandler); /* We pretend that all communication takes place on the audio channel, * and simply re-route packets from and to the control and timing channels */ if (!channelType.equals(RaopRtpChannelType.Audio)) { pipeline.addLast("inputToAudioRouter", m_inputToAudioRouterDownstreamHandler); /* Must come *after* the router, otherwise incoming packets are logged twice */ pipeline.addLast("packetLogger", m_packetLoggingHandler); } else { /* Must come *before* the router, otherwise outgoing packets are logged twice */ pipeline.addLast("packetLogger", m_packetLoggingHandler); pipeline.addLast("audioToOutputRouter", m_audioToOutputRouterUpstreamHandler); pipeline.addLast("timing", m_timingHandler); pipeline.addLast("resendRequester", m_resendRequestHandler); if (m_decryptionHandler != null) pipeline.addLast("decrypt", m_decryptionHandler); if (m_audioDecodeHandler != null) pipeline.addLast("audioDecode", m_audioDecodeHandler); pipeline.addLast("enqueue", m_audioEnqueueHandler); } return pipeline; } }); Channel channel = null; boolean didThrow = true; try { /* Bind to local address */ channel = bootstrap.bind(local); /* Add to group of RTP channels beloging to this RTSP connection */ m_rtpChannels.add(channel); /* Connect to remote address if one was provided */ if (remote != null) channel.connect(remote); didThrow = false; return channel; } finally { if (didThrow && (channel != null)) channel.close(); } } /** * Modifies the port component of an {@link InetSocketAddress} while * leaving the other parts unmodified. * * @param address socket address * @param port new port * @return socket address with port substitued */ private InetSocketAddress substitutePort(final InetSocketAddress address, final int port) { /* * The more natural way of doing this would be * new InetSocketAddress(address.getAddress(), port), * but this leads to a JVM crash on Windows when the * new socket address is used to connect() an NIO socket. * * According to * http://stackoverflow.com/questions/1512578/jvm-crash-on-opening-a-return-socketchannel * converting to address to a string first fixes the problem. */ return new InetSocketAddress(address.getAddress().getHostAddress(), port); } }
27,995
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtpPacket.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtpPacket.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.buffer.*; /** * Basic RTP packet as described by RFC 3550 */ public class RtpPacket { public static final int Length = 4; final private ChannelBuffer m_buffer; protected RtpPacket(final int size) { assert size >= Length; m_buffer = ChannelBuffers.buffer(size); m_buffer.writeZero(size); setVersion((byte)2); } public RtpPacket(final ChannelBuffer buffer) throws ProtocolException { m_buffer = buffer; } public RtpPacket(final ChannelBuffer buffer, final int minimumSize) throws ProtocolException { this(buffer); if (buffer.capacity() < minimumSize) throw new InvalidPacketException("Packet had invalid size " + buffer.capacity() + " instead of at least " + minimumSize); } public ChannelBuffer getBuffer() { return m_buffer; } public int getLength() { return m_buffer.capacity(); } /** * Get the RTP version number. Always 2. * @return RTP version number */ public byte getVersion() { return (byte)((m_buffer.getByte(0) & (0xC0)) >> 6); } /** * Sets the RTP version number. Should be 2. * @param version RTP version number */ public void setVersion(final byte version) { assert (version & ~0x03) == 0; m_buffer.setByte(0, (m_buffer.getByte(0) & ~(0xC0)) | (version << 6)); } /** * Gets the RTP padding flag * @return RTP padding flag */ public boolean getPadding() { return (m_buffer.getByte(0) & (0x20)) != 0; } /** * Sets the RTP padding flag * @param padding RTP padding flag */ public void setPadding(final boolean padding) { m_buffer.setByte(0, (m_buffer.getByte(0) & ~0x20) | (padding ? 0x20 : 0x00)); } /** * Gets the RTP padding flag * @return RTP padding flag */ public boolean getExtension() { return (m_buffer.getByte(0) & (0x10)) != 0; } /** * Sets the RTP padding flag * @param padding RTP padding flag */ public void setExtension(final boolean extension) { m_buffer.setByte(0, (m_buffer.getByte(0) & ~0x10) | (extension ? 0x10 : 0x00)); } /** * Gets the number of CSRC (contributing source) * identifiers included in the packet header. * <p> * @return nubmer of CSRC ids */ public byte getCsrcCount() { return (byte)(m_buffer.getByte(0) & (0x0f)); } /** * Sets the number of CSRC (contributing source) * identifiers included in the packet header. * Should be zero. * <p> * @param csrcCount nubmer of CSRC ids */ public void setCsrcCount(final byte csrcCount) { assert (csrcCount & ~0x0f) == 0; m_buffer.setByte(0, (m_buffer.getByte(0) & ~0x0f) | csrcCount); } /** * Sets the RTP marker flag * @param marker RTP marker flag */ public boolean getMarker() { return (m_buffer.getByte(1) & (0x80)) != 0; } /** * Sets the RTP marker flag * @param marker RTP marker flag */ public void setMarker(final boolean marker) { m_buffer.setByte(1, (m_buffer.getByte(1) & ~0x80) | (marker ? 0x80 : 0x00)); } /** * Gets the packet's payload type * @return packet's payload type */ public byte getPayloadType() { return (byte)(m_buffer.getByte(1) & (0x7f)); } /** * Sets the packet's payload type * @param payloadType packet's payload type */ public void setPayloadType(final byte payloadType) { assert (payloadType & ~0x7f) == 0; m_buffer.setByte(1, (m_buffer.getByte(1) & ~0x7f) | payloadType); } /** * Gets the packet's sequence number * @return packet's sequence number */ public int getSequence() { return ( ((m_buffer.getByte(2) & 0xff) << 8) | ((m_buffer.getByte(3) & 0xff) << 0) ); } /** * Sets the packet's sequence number * @param value packet's sequence number */ public void setSequence(final int sequence) { assert (sequence & ~0xffff) == 0; m_buffer.setByte(2, (sequence & 0xff00) >> 8); m_buffer.setByte(3, (sequence & 0x00ff) >> 0); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(this.getClass().getSimpleName()); s.append("("); s.append(Integer.toHexString(getPayloadType())); s.append(")"); s.append(" "); s.append("ver="); s.append(getVersion()); s.append(" "); s.append("pad="); s.append(getPadding()); s.append(" "); s.append("ext="); s.append(getExtension()); s.append(" "); s.append("csrcc="); s.append(getCsrcCount()); s.append(" "); s.append("marker="); s.append(getMarker()); s.append(" "); s.append("seq="); s.append(getSequence()); return s.toString(); } }
5,137
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
Base64.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/Base64.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.io.IOException; public final class Base64 { /** * Decodes Base64 data that is correctly padded with "=" * * @param str base64 data * @return bytes * @throws IOException if the data is invalid */ public static byte[] decodePadded(final String str) throws IOException { return net.iharder.Base64.decode(str); } /** * Decodes Base64 data that is not padded with "=" * * @param str base64 data * @return bytes * @throws IOException if the data is invalid */ public static byte[] decodeUnpadded(String base64) throws IOException { while (base64.length() % 4 != 0) base64 = base64.concat("="); return net.iharder.Base64.decode(base64); } /** * Encodes data to Base64 and padds with "=" * * @param data data to encode * @return base64 encoded string */ public static String encodePadded(final byte[] data) { return net.iharder.Base64.encodeBytes(data); } /** * Encodes data to Base64 but doesn't pad with "=" * * @param data data to encode * @return base64 encoded string */ public static String encodeUnpadded(final byte[] data) { String str = net.iharder.Base64.encodeBytes(data); final int pad = str.indexOf('='); if (pad >= 0) str = str.substring(0, pad); return str; } }
1,996
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtspChallengeResponseHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtspChallengeResponseHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.net.*; import java.nio.ByteBuffer; import javax.crypto.*; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; /** * Adds an {@code Apple-Response} header to a response if the request contain * an {@code Apple-Request} header. */ public class RaopRtspChallengeResponseHandler extends SimpleChannelHandler { private static final String HeaderChallenge = "Apple-Challenge"; private static final String HeaderSignature = "Apple-Response"; private final byte[] m_hwAddress; private final Cipher m_rsaPkCS1PaddingCipher = AirTunesCrytography.getCipher("RSA/None/PKCS1Padding"); private byte[] m_challenge; private InetAddress m_localAddress; public RaopRtspChallengeResponseHandler(final byte[] hwAddress) { assert hwAddress.length == 6; m_hwAddress = hwAddress; } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); synchronized(this) { if (req.containsHeader(HeaderChallenge)) { /* The challenge is sent without padding! */ final byte[] challenge = Base64.decodeUnpadded(req.getHeader(HeaderChallenge)); /* Verify that we got 16 bytes */ if (challenge.length != 16) throw new ProtocolException("Invalid Apple-Challenge header, " + challenge.length + " instead of 16 bytes"); /* Remember challenge and local address. * Both are required to compute the response */ m_challenge = challenge; m_localAddress = ((InetSocketAddress)ctx.getChannel().getLocalAddress()).getAddress(); } else { /* Forget last challenge */ m_challenge = null; m_localAddress = null; } } super.messageReceived(ctx, evt); } @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpResponse resp = (HttpResponse)evt.getMessage(); synchronized(this) { if (m_challenge != null) { try { /* Get appropriate response to challenge and * add to the response base-64 encoded. XXX */ final String sig = Base64.encodePadded(getSignature()); resp.setHeader(HeaderSignature, sig); } finally { /* Forget last challenge */ m_challenge = null; m_localAddress = null; } } } super.writeRequested(ctx, evt); } private byte[] getSignature() { final ByteBuffer sigData = ByteBuffer.allocate(16 /* challenge */ + 16 /* ipv6 address */ + 6 /* hw address*/); sigData.put(m_challenge); sigData.put(m_localAddress.getAddress()); sigData.put(m_hwAddress); while (sigData.hasRemaining()) sigData.put((byte)0); try { m_rsaPkCS1PaddingCipher.init(Cipher.ENCRYPT_MODE, AirTunesCrytography.PrivateKey); return m_rsaPkCS1PaddingCipher.doFinal(sigData.array()); } catch (final Exception e) { throw new RuntimeException("Unable to sign response", e); } } }
3,653
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
AudioClock.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/AudioClock.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; /** * Audio device clock */ public interface AudioClock { /** * Returns the current playback time in seconds. * * @return time of currently played sample */ double getNowSecondsTime(); /** * Returns the current playback time in frames * * @return time of currently played sample */ long getNowFrameTime(); /** * Returns the earliest time in samples for which data * is still accepted * * @return earliest playback time for new data */ double getNextSecondsTime(); /** * Returns the earliest time in frames for which data * is still accepted * * @return earliest playback time for new data */ long getNextFrameTime(); /** * Converts from frame time to seconds time * * @param frameTime frame time to convert * @return corresponding seconds time */ double convertFrameToSecondsTime(long frameTime); /** * Adjusts the frame time so that the given frame time * coindices with the given seconds time * * @param frameTime frame time corresponding to seconds time * @param secondsTime seconds time corresponding to frame time */ void setFrameTime(long frameTime, double secondsTime); }
1,882
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtpPacket.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtpPacket.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.buffer.ChannelBuffer; /** * Base class for the various RTP packet types of RAOP/AirTunes */ public abstract class RaopRtpPacket extends RtpPacket { /** * Reads an 32-bit unsigned integer from a channel buffer * @param buffer the channel buffer * @param index the start index * @return the integer, as long to preserve the original sign */ public static long getBeUInt(final ChannelBuffer buffer, final int index) { return ( ((buffer.getByte(index+0) & 0xffL) << 24) | ((buffer.getByte(index+1) & 0xffL) << 16) | ((buffer.getByte(index+2) & 0xffL) << 8) | ((buffer.getByte(index+3) & 0xffL) << 0) ); } /** * Writes an 32-bit unsigned integer to a channel buffer * @param buffer the channel buffer * @param index the start index * @param value the integer, as long to preserve the original sign */ public static void setBeUInt(final ChannelBuffer buffer, final int index, final long value) { assert (value & ~0xffffffffL) == 0; buffer.setByte(index+0, (int)((value & 0xff000000L) >> 24)); buffer.setByte(index+1, (int)((value & 0x00ff0000L) >> 16)); buffer.setByte(index+2, (int)((value & 0x0000ff00L) >> 8)); buffer.setByte(index+3, (int)((value & 0x000000ffL) >> 0)); } /** * Reads an 16-bit unsigned integer from a channel buffer * @param buffer the channel buffer * @param index the start index * @return the short, as int to preserve the original sign */ public static int getBeUInt16(final ChannelBuffer buffer, final int index) { return (int)( ((buffer.getByte(index+0) & 0xffL) << 8) | ((buffer.getByte(index+1) & 0xffL) << 0) ); } /** * Writes an 16-bit unsigned integer to a channel buffer * @param buffer the channel buffer * @param index the start index * @param value the short, as int to preserve the original sign */ public static void setBeUInt16(final ChannelBuffer buffer, final int index, final int value) { assert (value & ~0xffffL) == 0; buffer.setByte(index+0, (int)((value & 0xff00L) >> 8)); buffer.setByte(index+1, (int)((value & 0x00ffL) >> 0)); } /** * Represents an NTP time stamp, i.e. an amount of seconds * since 1900-01-01 00:00:00.000. * * The value is internally represented as a 64-bit fixed * point number with 32 fractional bits. */ public static final class NtpTime { public static final int Length = 8; private final ChannelBuffer m_buffer; protected NtpTime(final ChannelBuffer buffer) { assert buffer.capacity() == Length; m_buffer = buffer; } public long getSeconds() { return getBeUInt(m_buffer, 0); } public void setSeconds(final long seconds) { setBeUInt(m_buffer, 0, seconds); } public long getFraction() { return getBeUInt(m_buffer, 4); } public void setFraction(final long fraction) { setBeUInt(m_buffer, 4, fraction); } public double getDouble() { return getSeconds() + (double)getFraction() / 0x100000000L; } public void setDouble(final double v) { setSeconds((long)v); setFraction((long)(0x100000000L * (v - Math.floor(v)))); } } /** * Base class for {@link TimingRequest} and {@link TimingResponse} */ public static class Timing extends RaopRtpPacket { public static final int Length = RaopRtpPacket.Length + 4 + 8 + 8 + 8; protected Timing() { super(Length); setMarker(true); setSequence(7); } protected Timing(final ChannelBuffer buffer, final int minimumSize) throws ProtocolException { super(buffer, minimumSize); } /** * The time at which the {@link TimingRequest} was send. Copied into * {@link TimingResponse} when iTunes/iOS responds to a {@link TimingRequest} * @return */ public NtpTime getReferenceTime() { return new NtpTime(getBuffer().slice(RaopRtpPacket.Length + 4, 8)); } /** * The time at which a {@link TimingRequest} was received. Filled out * by iTunes/iOS. * @return */ public NtpTime getReceivedTime() { return new NtpTime(getBuffer().slice(RaopRtpPacket.Length + 12, 8)); } /** * The time at which a {@link TimingResponse} was sent as an response * to a {@link TimingRequest} * @return */ public NtpTime getSendTime() { return new NtpTime(getBuffer().slice(RaopRtpPacket.Length + 20, 8)); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(super.toString()); s.append(" "); s.append("ref="); s.append(getReferenceTime().getDouble()); s.append(" "); s.append("recv="); s.append(getReceivedTime().getDouble()); s.append(" "); s.append("send="); s.append(getSendTime().getDouble()); return s.toString(); } } /** * Time synchronization request. * <p> * Sent by the target (AirPort Express/AirReceiver) on the timing channel. * Used to synchronize to the source's clock. *<p> * The sequence number must always be 7, otherwise * at least iOS ignores the packet. */ public static final class TimingRequest extends Timing { public static final byte PayloadType = 0x52; public TimingRequest() { setPayloadType(PayloadType); } protected TimingRequest(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } } /** * Time synchronization response. * <p> * Sent by the source (iTunes/iOS) on the timing channel. * Used to synchronize to the source's clock. * <p> * The sequence should match the request's * sequence, which is always 7. */ public static final class TimingResponse extends Timing { public static final byte PayloadType = 0x53; public TimingResponse() { setPayloadType(PayloadType); } protected TimingResponse(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } } /** * Synchronization Requests. * <p> * Sent by the source (iTunes/iOs) on the control channel. * Used to translate RTP time stamps (frame time) into the source's time (seconds time) * and from there into the target's time (provided that the two are synchronized using * {@link TimingRequest} and * {@link TimingResponse}. * */ public static final class Sync extends RaopRtpPacket { public static final byte PayloadType = 0x54; public static final int Length = RaopRtpPacket.Length + 4 + 8 + 4; public Sync() { super(Length); setPayloadType(PayloadType); } protected Sync(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } /** * Gets the source's RTP time at which the sync packet was send * with the latency taken into account. (i.e. the RTP time stamp * of the packet supposed to be played back at {@link #getTime()}). * @return the source's RTP time corresponding to {@link #getTime()} minus the latency */ public long getTimeStampMinusLatency() { return getBeUInt(getBuffer(), RaopRtpPacket.Length); } /** * Sets the source's RTP time at which the sync packet was send * with the latency taken into account. (i.e. the RTP time stamp * of the packet supposed to be played back at {@link #getTime()}). * @return the source's RTP time corresponding to {@link #getTime()} minus the latency */ public void setTimeStampMinusLatency(final long value) { setBeUInt(getBuffer(), RaopRtpPacket.Length, value); } /** * The source's NTP time at which the sync packet was send * @return the source's NTP time corresponding to the RTP time returned by {@link #getTimeStamp()} */ public NtpTime getTime() { return new NtpTime(getBuffer().slice(RaopRtpPacket.Length + 4, 8)); } /** * Gets the current RTP time (frame time) at which the sync packet was sent, * <b>disregarding</b> the latency. (i.e. approximately the RTP time stamp * of the packet sent at {@link #getTime()}) * @return the source's RTP time corresponding to {@link #getTime()} */ public long getTimeStamp() { return getBeUInt(getBuffer(), RaopRtpPacket.Length + 4 + 8); } /** * Sets the current RTP time (frame time) at which the sync packet was sent, * <b>disregarding</b> the latency. (i.e. approximately the RTP time stamp * of the packet sent at {@link #getTime()}) * @param value the source's RTP time corresponding to {@link #getTime()} */ public void setTimeStamp(final long value) { setBeUInt(getBuffer(), RaopRtpPacket.Length + 4 + 8, value); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(super.toString()); s.append(" "); s.append("ts-lat="); s.append(getTimeStampMinusLatency()); s.append(" "); s.append("ts="); s.append(getTimeStamp()); s.append(" "); s.append("time="); s.append(getTime().getDouble()); return s.toString(); } } /** * Retransmit request. * <p> * Sent by the target (Airport Express/AirReceiver) on the control channel. Used to let the * source know about missing packets. * <p> * The source is supposed to respond by re-sending the packets with sequence numbers * {@link #getSequenceFirst()} to {@link #getSequenceFirst()} + {@link #getSequenceCount()}. * <p> * The retransmit responses are sent on the <b>control</b> channel, and use packet format * {@link AudioRetransmit} instead of {@link AudioTransmit}. * */ public static final class RetransmitRequest extends RaopRtpPacket { public static final byte PayloadType = 0x55; public static final int Length = RaopRtpPacket.Length + 4; public RetransmitRequest() { super(Length); setPayloadType(PayloadType); setMarker(true); setSequence(1); } protected RetransmitRequest(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } /** * Gets the sequence number of the first missing packet * @return sequence number */ public int getSequenceFirst() { return getBeUInt16(getBuffer(), RaopRtpPacket.Length); } /** * Sets the sequence number of the first missing packet * @param value sequence number */ public void setSequenceFirst(final int value) { setBeUInt16(getBuffer(), RaopRtpPacket.Length, value); } /** * Gets the number of missing packets * @return number of missing packets */ public int getSequenceCount() { return getBeUInt16(getBuffer(), RaopRtpPacket.Length + 2); } /** * Sets the number of missing packets * @param value number of missing packets */ public void setSequenceCount(final int value) { setBeUInt16(getBuffer(), RaopRtpPacket.Length + 2, value); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(super.toString()); s.append(" "); s.append("first="); s.append(getSequenceFirst()); s.append(" "); s.append("count="); s.append(getSequenceCount()); return s.toString(); } } /** * Base class for {@link AudioTransmit} and {@link AudioRetransmit}. */ public static abstract class Audio extends RaopRtpPacket { public Audio(final int length) { super(length); } protected Audio(final ChannelBuffer buffer, final int minimumSize) throws ProtocolException { super(buffer, minimumSize); } /** * Gets the packet's RTP time stamp (frame time) * @return RTP timestamp in frames */ abstract public long getTimeStamp(); /** * Gets the packet's RTP time stamp (frame time) * @param timeStamp RTP timestamp in frames */ abstract public void setTimeStamp(long timeStamp); /** * Unknown, seems to be always zero */ abstract public long getSSrc(); /** * Unknown, seems to be always zero */ abstract public void setSSrc(long sSrc); /** * ChannelBuffer containing the audio data * @return channel buffer containing audio data */ abstract public ChannelBuffer getPayload(); } /** * Audio data transmission. * <p> * Sent by the source (iTunes/iOS) on the audio channel. */ public static final class AudioTransmit extends Audio { public static final byte PayloadType = 0x60; public static final int Length = RaopRtpPacket.Length + 4 + 4; public AudioTransmit(final int payloadLength) { super(Length + payloadLength); assert payloadLength >= 0; setPayloadType(PayloadType); } protected AudioTransmit(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } @Override public long getTimeStamp() { return getBeUInt(getBuffer(), RaopRtpPacket.Length); } @Override public void setTimeStamp(final long timeStamp) { setBeUInt(getBuffer(), RaopRtpPacket.Length, timeStamp); } @Override public long getSSrc() { return getBeUInt(getBuffer(), RaopRtpPacket.Length + 4); } @Override public void setSSrc(final long sSrc) { setBeUInt(getBuffer(), RaopRtpPacket.Length + 4, sSrc); } @Override public ChannelBuffer getPayload() { return getBuffer().slice(Length, getLength() - Length); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(super.toString()); s.append(" "); s.append("ts="); s.append(getTimeStamp()); s.append(" "); s.append("ssrc="); s.append(getSSrc()); s.append(" "); s.append("<"); s.append(getPayload().capacity()); s.append(" bytes payload>"); return s.toString(); } } /** * Audio data re-transmission. * <p> * Sent by the source (iTunes/iOS) on the control channel in response * to {@link RetransmitRequest}. */ public static final class AudioRetransmit extends Audio { public static final byte PayloadType = 0x56; public static final int Length = RaopRtpPacket.Length + 4 + 4 + 4; public AudioRetransmit(final int payloadLength) { super(Length + payloadLength); assert payloadLength >= 0; setPayloadType(PayloadType); } protected AudioRetransmit(final ChannelBuffer buffer) throws ProtocolException { super(buffer, Length); } /** * First two bytes after RTP header */ public int getUnknown2Bytes() { return getBeUInt16(getBuffer(), RaopRtpPacket.Length); } /** * First two bytes after RTP header */ public void setUnknown2Bytes(final int b) { setBeUInt16(getBuffer(), RaopRtpPacket.Length, b); } /** * This is to be the sequence of the original * packet (i.e., the sequence we requested to be * retransmitted). */ public int getOriginalSequence() { return getBeUInt16(getBuffer(), RaopRtpPacket.Length + 2); } /** * This seems is the sequence of the original * packet (i.e., the sequence we requested to be * retransmitted). */ public void setOriginalSequence(final int seq) { setBeUInt16(getBuffer(), RaopRtpPacket.Length + 2, seq); } @Override public long getTimeStamp() { return getBeUInt(getBuffer(), RaopRtpPacket.Length + 4); } @Override public void setTimeStamp(final long timeStamp) { setBeUInt(getBuffer(), RaopRtpPacket.Length + 4, timeStamp); } @Override public long getSSrc() { return getBeUInt(getBuffer(), RaopRtpPacket.Length + 4 + 4); } @Override public void setSSrc(final long sSrc) { setBeUInt(getBuffer(), RaopRtpPacket.Length + 4 + 4, sSrc); } @Override public ChannelBuffer getPayload() { return getBuffer().slice(Length, getLength() - Length); } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(super.toString()); s.append(" "); s.append("?="); s.append(getUnknown2Bytes()); s.append(" "); s.append("oseq="); s.append(getOriginalSequence()); s.append(" "); s.append("ts="); s.append(getTimeStamp()); s.append(" "); s.append("ssrc="); s.append(getSSrc()); s.append(" "); s.append("<"); s.append(getPayload().capacity()); s.append(" bytes payload>"); return s.toString(); } } /** * Creates an RTP packet from a {@link ChannelBuffer}, using the * sub-class of {@link RaopRtpPacket} indicated by the packet's * {@link #getPayloadType()} * * @param buffer ChannelBuffer containing the packet * @return Instance of one of the sub-classes of {@link RaopRtpPacket} * @throws ProtocolException if the packet is invalid. */ public static RaopRtpPacket decode(final ChannelBuffer buffer) throws ProtocolException { final RtpPacket rtpPacket = new RtpPacket(buffer, Length); switch (rtpPacket.getPayloadType()) { case TimingRequest.PayloadType: return new TimingRequest(buffer); case TimingResponse.PayloadType: return new TimingResponse(buffer); case Sync.PayloadType: return new Sync(buffer); case RetransmitRequest.PayloadType: return new RetransmitRequest(buffer); case AudioRetransmit.PayloadType: return new AudioRetransmit(buffer); case AudioTransmit.PayloadType: return new AudioTransmit(buffer); default: throw new ProtocolException("Invalid PayloadType " + rtpPacket.getPayloadType()); } } protected RaopRtpPacket(final int length) { super(length); setVersion((byte)2); } protected RaopRtpPacket(final ChannelBuffer buffer, final int minimumSize) throws ProtocolException { super(buffer, minimumSize); } protected RaopRtpPacket(final ChannelBuffer buffer) throws ProtocolException { super(buffer); } }
17,791
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtspOptionsHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtspOptionsHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.*; /** * Handles RTSP OPTIONS requests. * <p> * iTunes sends those to verify that we're a legitimate device, * by including a Apple-Request header and expecting an appropriate * Apple-Response */ public class RaopRtspOptionsHandler extends SimpleChannelUpstreamHandler { private static final String Options = RaopRtspMethods.ANNOUNCE.getName() + ", " + RaopRtspMethods.SETUP.getName() + ", " + RaopRtspMethods.RECORD.getName() + ", " + RaopRtspMethods.PAUSE.getName() + ", " + RaopRtspMethods.FLUSH.getName() + ", " + RtspMethods.TEARDOWN.getName() + ", " + RaopRtspMethods.OPTIONS.getName() + ", " + RaopRtspMethods.GET_PARAMETER.getName() + ", " + RaopRtspMethods.SET_PARAMETER.getName(); @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); if (RtspMethods.OPTIONS.equals(req.getMethod())) { final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.setHeader(RtspHeaders.Names.PUBLIC, Options); ctx.getChannel().write(response); } else { super.messageReceived(ctx, evt); } } }
2,055
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
AudioStreamInformationProvider.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/AudioStreamInformationProvider.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import javax.sound.sampled.AudioFormat; /** * Provides information about an audio stream */ public interface AudioStreamInformationProvider { /** * The JavaSoune audio format of the streamed audio * @return the AudioFormat */ public AudioFormat getAudioFormat(); /** * Average frames per second * @return frames per second */ public int getFramesPerPacket(); /** * Average packets per second * @return packets per second */ public double getPacketsPerSecond(); }
1,212
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RaopRtspHeaderHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RaopRtspHeaderHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; /** * Adds a few default headers to every RTSP response */ public class RaopRtspHeaderHandler extends SimpleChannelHandler { private static final String HeaderCSeq = "CSeq"; private static final String HeaderAudioJackStatus = "Audio-Jack-Status"; private static final String HeaderAudioJackStatusDefault = "connected; type=analog"; /* private static final String HeaderAudioLatency = "Audio-Latency"; private static final long HeaderAudioLatencyFrames = 88400; */ private String m_cseq; @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); synchronized(this) { if (req.containsHeader(HeaderCSeq)) { m_cseq = req.getHeader(HeaderCSeq); } else { throw new ProtocolException("No CSeq header"); } } super.messageReceived(ctx, evt); } @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpResponse resp = (HttpResponse)evt.getMessage(); synchronized(this) { if (m_cseq != null) resp.setHeader(HeaderCSeq, m_cseq); resp.setHeader(HeaderAudioJackStatus, HeaderAudioJackStatusDefault); //resp.setHeader(HeaderAudioLatency, Long.toString(HeaderAudioLatencyFrames)); } super.writeRequested(ctx, evt); } }
2,161
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
RtspUnsupportedResponseHandler.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/AirReceiver/RtspUnsupportedResponseHandler.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.AirReceiver; import java.util.logging.Logger; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.RtspResponseStatuses; import org.jboss.netty.handler.codec.rtsp.RtspVersions; /** * Sends a METHOD NOT VALID response if no other channel handler * takes responsibility for a RTSP message. */ public class RtspUnsupportedResponseHandler extends SimpleChannelUpstreamHandler { private static Logger s_logger = Logger.getLogger(RtspUnsupportedResponseHandler.class.getName()); @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception { final HttpRequest req = (HttpRequest)evt.getMessage(); s_logger.warning("Method " + req.getMethod() + " is not supported"); final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.METHOD_NOT_VALID); ctx.getChannel().write(response); } }
1,660
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
SampleIndexedAccessor.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleIndexedAccessor.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; public interface SampleIndexedAccessor { SampleDimensions getDimensions(); SampleIndexedAccessor slice(SampleOffset offset, SampleDimensions dimensions); SampleIndexedAccessor slice(SampleRange range); float getSample(int channel, int sample); void setSample(int channel, int index, float sample); }
1,021
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
Latch.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/Latch.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; public final class Latch<T> { private final Object m_monitor; private boolean m_ready = false; private T m_value = null; public Latch() { m_monitor = this; } public Latch(Object monitor) { m_monitor = monitor; } public void offer(T value) throws InterruptedException { synchronized(m_monitor) { /* Wait until the currently offered value is consumed */ while (m_ready) { m_monitor.wait(); /* If there is a concurrent consume() and a concurrent offer() * the concurrent offer()'s notify() might have hit us instead * of the consumer. In this case we re-notify() hoping to * eventually hit the consume(): */ if (m_ready) m_monitor.notify(); } assert m_value == null; m_value = value; m_ready = true; m_monitor.notify(); } } public T consume() throws InterruptedException { synchronized(m_monitor) { /* Wait until a value is offered */ while (!m_ready) { m_monitor.wait(); /* If there is a concurrent consume() and a concurrent offer() * the concurrent consume()'s notify() might have hit us instead * of the offer(). In this case we re-notify() hoping to * eventually hit the offer(): */ if (!m_ready) m_monitor.notify(); } final T value = m_value; m_value = null; m_ready = false; m_monitor.notify(); return value; } } }
2,103
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
SampleBuffer.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleBuffer.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; import java.nio.ByteBuffer; import java.nio.IntBuffer; public final class SampleBuffer implements SampleIndexedAccessor { private final SampleDimensions m_bufferDimensions; private final float[] m_buffer; private final SampleIndexer m_samplesIndexer; private double m_timeStamp = 0.0; public SampleBuffer(final float[] buffer, final SampleDimensions bufferDimensions, SampleIndexer samplesIndexer) { m_buffer = buffer; m_bufferDimensions = bufferDimensions; m_samplesIndexer = samplesIndexer; } public SampleBuffer(final float[] buffer, final SampleDimensions bufferDimensions, final SampleRange range, final SampleBufferLayout layout) { m_buffer = buffer; m_bufferDimensions = bufferDimensions; m_samplesIndexer = layout.getIndexer(bufferDimensions, range); } public SampleBuffer(final SampleDimensions dimensions) { this( new float[dimensions.getTotalSamples()], dimensions, new SampleRange(SampleOffset.Zero, dimensions), SampleBufferLayout.Banded ); } public double getTimeStamp() { return m_timeStamp; } public void setTimeStamp(double timeStamp) { m_timeStamp = timeStamp; } public SampleBuffer slice(SampleRange range) { return new SampleBuffer(m_buffer, m_bufferDimensions, m_samplesIndexer.slice(range)); } public SampleBuffer slice(SampleOffset offset, SampleDimensions dimensions) { return new SampleBuffer(m_buffer, m_bufferDimensions, m_samplesIndexer.slice(offset, dimensions)); } public void copyFrom(final ByteBuffer src, final SampleDimensions srcDims, final SampleRange srcRange, final SampleByteBufferFormat srcByteFormat) { srcDims.assertContains(srcRange); m_samplesIndexer.getDimensions().assertContains(srcRange.size); final SampleIndexedAccessor srcAccessor = srcByteFormat.getAccessor(src, srcDims, srcRange); for(int c=0; c < srcRange.size.channels; ++c) { for(int s=0; s < srcRange.size.samples; ++s) { m_buffer[m_samplesIndexer.getSampleIndex(c, s)] = srcAccessor.getSample(c, s); } } } public void copyFrom(final ByteBuffer src, final SampleDimensions srcDims, final SampleByteBufferFormat srcFormat) { copyFrom(src, srcDims, new SampleRange(srcDims), srcFormat); } public void copyFrom(final IntBuffer src, final SampleDimensions srcDims, final SampleRange srcRange, final SampleBufferLayout srcLayout, final Signedness srcSignedness) { m_samplesIndexer.getDimensions().assertContains(srcRange.size); srcDims.assertContains(srcRange); final SampleIndexer srcIndexer = srcLayout.getIndexer(srcDims, srcRange); for(int c=0; c < srcRange.size.channels; ++c) { for(int s=0; s < srcRange.size.samples; ++s) { m_buffer[m_samplesIndexer.getSampleIndex(c, s)] = srcSignedness.shortToNormalizedFloat((short)src.get(srcIndexer.getSampleIndex(c, s))); } } } public void copyFrom(final IntBuffer src, final SampleDimensions srcDims, final SampleBufferLayout srcLayout, final Signedness srcSignedness) { copyFrom(src, srcDims, new SampleRange(srcDims), srcLayout, srcSignedness); } public void copyTo(final ByteBuffer dst, final SampleDimensions dstDims, final SampleOffset dstOffset, final SampleByteBufferFormat dstByteFormat) { dstDims.assertContains(new SampleRange(dstOffset, m_samplesIndexer.getDimensions())); final SampleIndexedAccessor dstAccessor = dstByteFormat.getAccessor(dst, dstDims, dstOffset); for(int c=0; c < m_samplesIndexer.getDimensions().channels; ++c) { for(int s=0; s < m_samplesIndexer.getDimensions().samples; ++s) { dstAccessor.setSample(c, s, m_buffer[m_samplesIndexer.getSampleIndex(c, s)]); } } } public void copyTo(final ByteBuffer dst, final SampleDimensions dstDims, final SampleByteBufferFormat dstFormat) { copyTo(dst, dstDims, SampleOffset.Zero, dstFormat); } @Override public SampleDimensions getDimensions() { return m_samplesIndexer.getDimensions(); } @Override public float getSample(int channel, int sample) { return m_buffer[m_samplesIndexer.getSampleIndex(channel, sample)]; } @Override public void setSample(int channel, int sample, float value) { m_buffer[m_samplesIndexer.getSampleIndex(channel, sample)] = value; } }
4,880
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
SampleOffset.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleOffset.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; public class SampleOffset { public final int channel; public final int sample; public final static SampleOffset Zero = new SampleOffset(0, 0); public SampleOffset(final int _channel, final int _sample) { if (_channel < 0) throw new IllegalArgumentException("channel must be greater or equal to zero"); if (_sample < 0) throw new IllegalArgumentException("sample must be greater or equal to zero"); channel = _channel; sample = _sample; } public SampleOffset add(SampleOffset other) { return new SampleOffset(channel + other.channel, sample + other.sample); } @Override public String toString() { return "[" + channel + ";" + sample + "]"; } }
1,390
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z
SampleSource.java
/FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleSource.java
/* * This file is part of AirReceiver. * * AirReceiver is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AirReceiver is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with AirReceiver. If not, see <http://www.gnu.org/licenses/>. */ package org.phlo.audio; public interface SampleSource { public SampleBuffer getSampleBuffer(double timeStamp); }
802
Java
.java
fgp/AirReceiver
170
102
9
2011-04-28T07:17:04Z
2020-10-13T10:13:16Z