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
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/package-info.java
/** * Classes for creating dial plots. */ package org.jfree.chart.plot.dial;
79
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardDialScale.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/StandardDialScale.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * StandardDialScale.java * ---------------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 17-Nov-2006 : Added flags for tick label visibility (DG); * 24-Oct-2007 : Added tick label formatter (DG); * 19-Nov-2007 : Added some missing accessor methods (DG); * 27-Feb-2009 : Fixed bug 2617557: tickLabelPaint ignored (DG); * 09-Feb-2010 : Fixed bug 2946521 (DG); * 08-Jan-2012 : Added missing angleToValue() implementation (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.DecimalFormat; import java.text.NumberFormat; import org.jfree.chart.ui.TextAnchor; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.SerialUtilities; /** * A scale for a {@link DialPlot}. * * @since 1.0.7 */ public class StandardDialScale extends AbstractDialLayer implements DialScale, Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = 3715644629665918516L; /** The minimum data value for the scale. */ private double lowerBound; /** The maximum data value for the scale. */ private double upperBound; /** * The start angle for the scale display, in degrees (using the same * encoding as Arc2D). */ private double startAngle; /** The extent of the scale display. */ private double extent; /** * The factor (in the range 0.0 to 1.0) that determines the outside limit * of the tick marks. */ private double tickRadius; /** * The increment (in data units) between major tick marks. */ private double majorTickIncrement; /** * The factor that is subtracted from the tickRadius to determine the * inner point of the major ticks. */ private double majorTickLength; /** * The paint to use for major tick marks. This field is transient because * it requires special handling for serialization. */ private transient Paint majorTickPaint; /** * The stroke to use for major tick marks. This field is transient because * it requires special handling for serialization. */ private transient Stroke majorTickStroke; /** * The number of minor ticks between each major tick. */ private int minorTickCount; /** * The factor that is subtracted from the tickRadius to determine the * inner point of the minor ticks. */ private double minorTickLength; /** * The paint to use for minor tick marks. This field is transient because * it requires special handling for serialization. */ private transient Paint minorTickPaint; /** * The stroke to use for minor tick marks. This field is transient because * it requires special handling for serialization. */ private transient Stroke minorTickStroke; /** * The tick label offset. */ private double tickLabelOffset; /** * The tick label font. */ private Font tickLabelFont; /** * A flag that controls whether or not the tick labels are * displayed. */ private boolean tickLabelsVisible; /** * The number formatter for the tick labels. */ private NumberFormat tickLabelFormatter; /** * A flag that controls whether or not the first tick label is * displayed. */ private boolean firstTickLabelVisible; /** * The tick label paint. This field is transient because it requires * special handling for serialization. */ private transient Paint tickLabelPaint; /** * Creates a new instance of DialScale. */ public StandardDialScale() { this(0.0, 100.0, 175, -170, 10.0, 4); } /** * Creates a new instance. * * @param lowerBound the lower bound of the scale. * @param upperBound the upper bound of the scale. * @param startAngle the start angle (in degrees, using the same * orientation as Java's <code>Arc2D</code> class). * @param extent the extent (in degrees, counter-clockwise). * @param majorTickIncrement the interval between major tick marks (must * be > 0). * @param minorTickCount the number of minor ticks between major tick * marks. */ public StandardDialScale(double lowerBound, double upperBound, double startAngle, double extent, double majorTickIncrement, int minorTickCount) { if (majorTickIncrement <= 0.0) { throw new IllegalArgumentException( "Requires 'majorTickIncrement' > 0."); } this.startAngle = startAngle; this.extent = extent; this.lowerBound = lowerBound; this.upperBound = upperBound; this.tickRadius = 0.70; this.tickLabelsVisible = true; this.tickLabelFormatter = new DecimalFormat("0.0"); this.firstTickLabelVisible = true; this.tickLabelFont = new Font("Dialog", Font.BOLD, 16); this.tickLabelPaint = Color.BLUE; this.tickLabelOffset = 0.10; this.majorTickIncrement = majorTickIncrement; this.majorTickLength = 0.04; this.majorTickPaint = Color.BLACK; this.majorTickStroke = new BasicStroke(3.0f); this.minorTickCount = minorTickCount; this.minorTickLength = 0.02; this.minorTickPaint = Color.BLACK; this.minorTickStroke = new BasicStroke(1.0f); } /** * Returns the lower bound for the scale. * * @return The lower bound for the scale. * * @see #setLowerBound(double) * * @since 1.0.8 */ public double getLowerBound() { return this.lowerBound; } /** * Sets the lower bound for the scale and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param lower the lower bound. * * @see #getLowerBound() * * @since 1.0.8 */ public void setLowerBound(double lower) { this.lowerBound = lower; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the upper bound for the scale. * * @return The upper bound for the scale. * * @see #setUpperBound(double) * * @since 1.0.8 */ public double getUpperBound() { return this.upperBound; } /** * Sets the upper bound for the scale and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param upper the upper bound. * * @see #getUpperBound() * * @since 1.0.8 */ public void setUpperBound(double upper) { this.upperBound = upper; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the start angle for the scale (in degrees using the same * orientation as Java's <code>Arc2D</code> class). * * @return The start angle. * * @see #setStartAngle(double) */ public double getStartAngle() { return this.startAngle; } /** * Sets the start angle for the scale and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param angle the angle (in degrees). * * @see #getStartAngle() */ public void setStartAngle(double angle) { this.startAngle = angle; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the extent. * * @return The extent. * * @see #setExtent(double) */ public double getExtent() { return this.extent; } /** * Sets the extent and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param extent the extent. * * @see #getExtent() */ public void setExtent(double extent) { this.extent = extent; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the radius (as a percentage of the maximum space available) of * the outer limit of the tick marks. * * @return The tick radius. * * @see #setTickRadius(double) */ public double getTickRadius() { return this.tickRadius; } /** * Sets the tick radius and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param radius the radius. * * @see #getTickRadius() */ public void setTickRadius(double radius) { if (radius <= 0.0) { throw new IllegalArgumentException( "The 'radius' must be positive."); } this.tickRadius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the increment (in data units) between major tick labels. * * @return The increment between major tick labels. * * @see #setMajorTickIncrement(double) */ public double getMajorTickIncrement() { return this.majorTickIncrement; } /** * Sets the increment (in data units) between major tick labels and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param increment the increment (must be > 0). * * @see #getMajorTickIncrement() */ public void setMajorTickIncrement(double increment) { if (increment <= 0.0) { throw new IllegalArgumentException( "The 'increment' must be positive."); } this.majorTickIncrement = increment; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the length factor for the major tick marks. The value is * subtracted from the tick radius to determine the inner starting point * for the tick marks. * * @return The length factor. * * @see #setMajorTickLength(double) */ public double getMajorTickLength() { return this.majorTickLength; } /** * Sets the length factor for the major tick marks and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param length the length. * * @see #getMajorTickLength() */ public void setMajorTickLength(double length) { if (length < 0.0) { throw new IllegalArgumentException("Negative 'length' argument."); } this.majorTickLength = length; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the major tick paint. * * @return The major tick paint (never <code>null</code>). * * @see #setMajorTickPaint(Paint) */ public Paint getMajorTickPaint() { return this.majorTickPaint; } /** * Sets the major tick paint and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getMajorTickPaint() */ public void setMajorTickPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.majorTickPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the stroke used to draw the major tick marks. * * @return The stroke (never <code>null</code>). * * @see #setMajorTickStroke(Stroke) */ public Stroke getMajorTickStroke() { return this.majorTickStroke; } /** * Sets the stroke used to draw the major tick marks and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getMajorTickStroke() */ public void setMajorTickStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.majorTickStroke = stroke; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the number of minor tick marks between major tick marks. * * @return The number of minor tick marks between major tick marks. * * @see #setMinorTickCount(int) */ public int getMinorTickCount() { return this.minorTickCount; } /** * Sets the number of minor tick marks between major tick marks and sends * a {@link DialLayerChangeEvent} to all registered listeners. * * @param count the count. * * @see #getMinorTickCount() */ public void setMinorTickCount(int count) { if (count < 0) { throw new IllegalArgumentException( "The 'count' cannot be negative."); } this.minorTickCount = count; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the length factor for the minor tick marks. The value is * subtracted from the tick radius to determine the inner starting point * for the tick marks. * * @return The length factor. * * @see #setMinorTickLength(double) */ public double getMinorTickLength() { return this.minorTickLength; } /** * Sets the length factor for the minor tick marks and sends * a {@link DialLayerChangeEvent} to all registered listeners. * * @param length the length. * * @see #getMinorTickLength() */ public void setMinorTickLength(double length) { if (length < 0.0) { throw new IllegalArgumentException("Negative 'length' argument."); } this.minorTickLength = length; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to draw the minor tick marks. * * @return The paint (never <code>null</code>). * * @see #setMinorTickPaint(Paint) */ public Paint getMinorTickPaint() { return this.minorTickPaint; } /** * Sets the paint used to draw the minor tick marks and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getMinorTickPaint() */ public void setMinorTickPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.minorTickPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the stroke used to draw the minor tick marks. * * @return The paint (never <code>null</code>). * * @see #setMinorTickStroke(Stroke) * * @since 1.0.8 */ public Stroke getMinorTickStroke() { return this.minorTickStroke; } /** * Sets the stroke used to draw the minor tick marks and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getMinorTickStroke() * * @since 1.0.8 */ public void setMinorTickStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.minorTickStroke = stroke; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the tick label offset. * * @return The tick label offset. * * @see #setTickLabelOffset(double) */ public double getTickLabelOffset() { return this.tickLabelOffset; } /** * Sets the tick label offset and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param offset the offset. * * @see #getTickLabelOffset() */ public void setTickLabelOffset(double offset) { this.tickLabelOffset = offset; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the font used to draw the tick labels. * * @return The font (never <code>null</code>). * * @see #setTickLabelFont(Font) */ public Font getTickLabelFont() { return this.tickLabelFont; } /** * Sets the font used to display the tick labels and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getTickLabelFont() */ public void setTickLabelFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.tickLabelFont = font; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to draw the tick labels. * * @return The paint (<code>null</code> not permitted). * * @see #setTickLabelPaint(Paint) */ public Paint getTickLabelPaint() { return this.tickLabelPaint; } /** * Sets the paint used to draw the tick labels and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setTickLabelPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.tickLabelPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> if the tick labels should be displayed, * and <code>false</code> otherwise. * * @return A boolean. * * @see #setTickLabelsVisible(boolean) */ public boolean getTickLabelsVisible() { return this.tickLabelsVisible; } /** * Sets the flag that controls whether or not the tick labels are * displayed, and sends a {@link DialLayerChangeEvent} to all registered * listeners. * * @param visible the new flag value. * * @see #getTickLabelsVisible() */ public void setTickLabelsVisible(boolean visible) { this.tickLabelsVisible = visible; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the number formatter used to convert the tick label values to * strings. * * @return The formatter (never <code>null</code>). * * @see #setTickLabelFormatter(NumberFormat) */ public NumberFormat getTickLabelFormatter() { return this.tickLabelFormatter; } /** * Sets the number formatter used to convert the tick label values to * strings, and sends a {@link DialLayerChangeEvent} to all registered * listeners. * * @param formatter the formatter (<code>null</code> not permitted). * * @see #getTickLabelFormatter() */ public void setTickLabelFormatter(NumberFormat formatter) { if (formatter == null) { throw new IllegalArgumentException("Null 'formatter' argument."); } this.tickLabelFormatter = formatter; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns a flag that controls whether or not the first tick label is * visible. * * @return A boolean. * * @see #setFirstTickLabelVisible(boolean) */ public boolean getFirstTickLabelVisible() { return this.firstTickLabelVisible; } /** * Sets a flag that controls whether or not the first tick label is * visible, and sends a {@link DialLayerChangeEvent} to all registered * listeners. * * @param visible the new flag value. * * @see #getFirstTickLabelVisible() */ public void setFirstTickLabelVisible(boolean visible) { this.firstTickLabelVisible = visible; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> to indicate that this layer should be * clipped within the dial window. * * @return <code>true</code>. */ @Override public boolean isClippedToWindow() { return true; } /** * Draws the scale on the dial plot. * * @param g2 the graphics target (<code>null</code> not permitted). * @param plot the dial plot (<code>null</code> not permitted). * @param frame the reference frame that is used to construct the * geometry of the plot (<code>null</code> not permitted). * @param view the visible part of the plot (<code>null</code> not * permitted). */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { Rectangle2D arcRect = DialPlot.rectangleByRadius(frame, this.tickRadius, this.tickRadius); Rectangle2D arcRectMajor = DialPlot.rectangleByRadius(frame, this.tickRadius - this.majorTickLength, this.tickRadius - this.majorTickLength); Rectangle2D arcRectMinor = arcRect; if (this.minorTickCount > 0 && this.minorTickLength > 0.0) { arcRectMinor = DialPlot.rectangleByRadius(frame, this.tickRadius - this.minorTickLength, this.tickRadius - this.minorTickLength); } Rectangle2D arcRectForLabels = DialPlot.rectangleByRadius(frame, this.tickRadius - this.tickLabelOffset, this.tickRadius - this.tickLabelOffset); boolean firstLabel = true; Arc2D arc = new Arc2D.Double(); Line2D workingLine = new Line2D.Double(); for (double v = this.lowerBound; v <= this.upperBound; v += this.majorTickIncrement) { arc.setArc(arcRect, this.startAngle, valueToAngle(v) - this.startAngle, Arc2D.OPEN); Point2D pt0 = arc.getEndPoint(); arc.setArc(arcRectMajor, this.startAngle, valueToAngle(v) - this.startAngle, Arc2D.OPEN); Point2D pt1 = arc.getEndPoint(); g2.setPaint(this.majorTickPaint); g2.setStroke(this.majorTickStroke); workingLine.setLine(pt0, pt1); g2.draw(workingLine); arc.setArc(arcRectForLabels, this.startAngle, valueToAngle(v) - this.startAngle, Arc2D.OPEN); Point2D pt2 = arc.getEndPoint(); if (this.tickLabelsVisible) { if (!firstLabel || this.firstTickLabelVisible) { g2.setFont(this.tickLabelFont); g2.setPaint(this.tickLabelPaint); TextUtilities.drawAlignedString( this.tickLabelFormatter.format(v), g2, (float) pt2.getX(), (float) pt2.getY(), TextAnchor.CENTER); } } firstLabel = false; // now do the minor tick marks if (this.minorTickCount > 0 && this.minorTickLength > 0.0) { double minorTickIncrement = this.majorTickIncrement / (this.minorTickCount + 1); for (int i = 0; i < this.minorTickCount; i++) { double vv = v + ((i + 1) * minorTickIncrement); if (vv >= this.upperBound) { break; } double angle = valueToAngle(vv); arc.setArc(arcRect, this.startAngle, angle - this.startAngle, Arc2D.OPEN); pt0 = arc.getEndPoint(); arc.setArc(arcRectMinor, this.startAngle, angle - this.startAngle, Arc2D.OPEN); Point2D pt3 = arc.getEndPoint(); g2.setStroke(this.minorTickStroke); g2.setPaint(this.minorTickPaint); workingLine.setLine(pt0, pt3); g2.draw(workingLine); } } } } /** * Converts a data value to an angle against this scale. * * @param value the data value. * * @return The angle (in degrees, using the same specification as Java's * Arc2D class). * * @see #angleToValue(double) */ @Override public double valueToAngle(double value) { double range = this.upperBound - this.lowerBound; double unit = this.extent / range; return this.startAngle + unit * (value - this.lowerBound); } /** * Converts the given angle to a data value, based on this scale. * * @param angle the angle (in degrees). * * @return The data value. * * @see #valueToAngle(double) */ @Override public double angleToValue(double angle) { double range = this.upperBound - this.lowerBound; double unit = range / this.extent; return (angle - this.startAngle) * unit; } /** * Tests this <code>StandardDialScale</code> for equality with an arbitrary * object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardDialScale)) { return false; } StandardDialScale that = (StandardDialScale) obj; if (this.lowerBound != that.lowerBound) { return false; } if (this.upperBound != that.upperBound) { return false; } if (this.startAngle != that.startAngle) { return false; } if (this.extent != that.extent) { return false; } if (this.tickRadius != that.tickRadius) { return false; } if (this.majorTickIncrement != that.majorTickIncrement) { return false; } if (this.majorTickLength != that.majorTickLength) { return false; } if (!PaintUtilities.equal(this.majorTickPaint, that.majorTickPaint)) { return false; } if (!this.majorTickStroke.equals(that.majorTickStroke)) { return false; } if (this.minorTickCount != that.minorTickCount) { return false; } if (this.minorTickLength != that.minorTickLength) { return false; } if (!PaintUtilities.equal(this.minorTickPaint, that.minorTickPaint)) { return false; } if (!this.minorTickStroke.equals(that.minorTickStroke)) { return false; } if (this.tickLabelsVisible != that.tickLabelsVisible) { return false; } if (this.tickLabelOffset != that.tickLabelOffset) { return false; } if (!this.tickLabelFont.equals(that.tickLabelFont)) { return false; } if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 193; // lowerBound long temp = Double.doubleToLongBits(this.lowerBound); result = 37 * result + (int) (temp ^ (temp >>> 32)); // upperBound temp = Double.doubleToLongBits(this.upperBound); result = 37 * result + (int) (temp ^ (temp >>> 32)); // startAngle temp = Double.doubleToLongBits(this.startAngle); result = 37 * result + (int) (temp ^ (temp >>> 32)); // extent temp = Double.doubleToLongBits(this.extent); result = 37 * result + (int) (temp ^ (temp >>> 32)); // tickRadius temp = Double.doubleToLongBits(this.tickRadius); result = 37 * result + (int) (temp ^ (temp >>> 32)); // majorTickIncrement // majorTickLength // majorTickPaint // majorTickStroke // minorTickCount // minorTickLength // minorTickPaint // minorTickStroke // tickLabelOffset // tickLabelFont // tickLabelsVisible // tickLabelFormatter // firstTickLabelsVisible return result; } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if this instance is not cloneable. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.majorTickPaint, stream); SerialUtilities.writeStroke(this.majorTickStroke, stream); SerialUtilities.writePaint(this.minorTickPaint, stream); SerialUtilities.writeStroke(this.minorTickStroke, stream); SerialUtilities.writePaint(this.tickLabelPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.majorTickPaint = SerialUtilities.readPaint(stream); this.majorTickStroke = SerialUtilities.readStroke(stream); this.minorTickPaint = SerialUtilities.readPaint(stream); this.minorTickStroke = SerialUtilities.readStroke(stream); this.tickLabelPaint = SerialUtilities.readPaint(stream); } }
31,894
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialPlot.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialPlot.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * DialPlot.java * ------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 08-Mar-2007 : Fix in hashCode() (DG); * 17-Oct-2007 : Fixed listener registration/deregistration bugs (DG); * 24-Oct-2007 : Maintain pointers in their own list, so they can be * drawn after other layers (DG); * 15-Feb-2008 : Fixed clipping bug (1873160) (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import org.jfree.chart.JFreeChart; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.PlotState; import org.jfree.data.general.Dataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.ValueDataset; /** * A dial plot composed of user-definable layers. * The example shown here is generated by the <code>DialDemo2.java</code> * program included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/DialPlotSample.png" * alt="DialPlotSample.png" /> * * @since 1.0.7 */ public class DialPlot extends Plot implements DialLayerChangeListener { /** * The background layer (optional). */ private DialLayer background; /** * The needle cap (optional). */ private DialLayer cap; /** * The dial frame. */ private DialFrame dialFrame; /** * The dataset(s) for the dial plot. */ private ObjectList<Dataset> datasets; /** * The scale(s) for the dial plot. */ private ObjectList<DialScale> scales; /** Storage for keys that map datasets to scales. */ private ObjectList<Integer> datasetToScaleMap; /** * The drawing layers for the dial plot. */ private List<DialLayer> layers; /** * The pointer(s) for the dial. */ private List<DialPointer> pointers; /** * The x-coordinate for the view window. */ private double viewX; /** * The y-coordinate for the view window. */ private double viewY; /** * The width of the view window, expressed as a percentage. */ private double viewW; /** * The height of the view window, expressed as a percentage. */ private double viewH; /** * Creates a new instance of <code>DialPlot</code>. */ public DialPlot() { this(null); } /** * Creates a new instance of <code>DialPlot</code>. * * @param dataset the dataset (<code>null</code> permitted). */ public DialPlot(ValueDataset dataset) { this.background = null; this.cap = null; this.dialFrame = new ArcDialFrame(); this.datasets = new ObjectList<Dataset>(); if (dataset != null) { setDataset(dataset); } this.scales = new ObjectList<DialScale>(); this.datasetToScaleMap = new ObjectList<Integer>(); this.layers = new java.util.ArrayList<DialLayer>(); this.pointers = new java.util.ArrayList<DialPointer>(); this.viewX = 0.0; this.viewY = 0.0; this.viewW = 1.0; this.viewH = 1.0; } /** * Returns the background. * * @return The background (possibly <code>null</code>). * * @see #setBackground(DialLayer) */ public DialLayer getBackground() { return this.background; } /** * Sets the background layer and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param background the background layer (<code>null</code> permitted). * * @see #getBackground() */ public void setBackground(DialLayer background) { if (this.background != null) { this.background.removeChangeListener(this); } this.background = background; if (background != null) { background.addChangeListener(this); } fireChangeEvent(); } /** * Returns the cap. * * @return The cap (possibly <code>null</code>). * * @see #setCap(DialLayer) */ public DialLayer getCap() { return this.cap; } /** * Sets the cap and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param cap the cap (<code>null</code> permitted). * * @see #getCap() */ public void setCap(DialLayer cap) { if (this.cap != null) { this.cap.removeChangeListener(this); } this.cap = cap; if (cap != null) { cap.addChangeListener(this); } fireChangeEvent(); } /** * Returns the dial's frame. * * @return The dial's frame (never <code>null</code>). * * @see #setDialFrame(DialFrame) */ public DialFrame getDialFrame() { return this.dialFrame; } /** * Sets the dial's frame and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param frame the frame (<code>null</code> not permitted). * * @see #getDialFrame() */ public void setDialFrame(DialFrame frame) { if (frame == null) { throw new IllegalArgumentException("Null 'frame' argument."); } this.dialFrame.removeChangeListener(this); this.dialFrame = frame; frame.addChangeListener(this); fireChangeEvent(); } /** * Returns the x-coordinate of the viewing rectangle. This is specified * in the range 0.0 to 1.0, relative to the dial's framing rectangle. * * @return The x-coordinate of the viewing rectangle. * * @see #setView(double, double, double, double) */ public double getViewX() { return this.viewX; } /** * Returns the y-coordinate of the viewing rectangle. This is specified * in the range 0.0 to 1.0, relative to the dial's framing rectangle. * * @return The y-coordinate of the viewing rectangle. * * @see #setView(double, double, double, double) */ public double getViewY() { return this.viewY; } /** * Returns the width of the viewing rectangle. This is specified * in the range 0.0 to 1.0, relative to the dial's framing rectangle. * * @return The width of the viewing rectangle. * * @see #setView(double, double, double, double) */ public double getViewWidth() { return this.viewW; } /** * Returns the height of the viewing rectangle. This is specified * in the range 0.0 to 1.0, relative to the dial's framing rectangle. * * @return The height of the viewing rectangle. * * @see #setView(double, double, double, double) */ public double getViewHeight() { return this.viewH; } /** * Sets the viewing rectangle, relative to the dial's framing rectangle, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param x the x-coordinate (in the range 0.0 to 1.0). * @param y the y-coordinate (in the range 0.0 to 1.0). * @param w the width (in the range 0.0 to 1.0). * @param h the height (in the range 0.0 to 1.0). * * @see #getViewX() * @see #getViewY() * @see #getViewWidth() * @see #getViewHeight() */ public void setView(double x, double y, double w, double h) { this.viewX = x; this.viewY = y; this.viewW = w; this.viewH = h; fireChangeEvent(); } /** * Adds a layer to the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param layer the layer (<code>null</code> not permitted). */ public void addLayer(DialLayer layer) { if (layer == null) { throw new IllegalArgumentException("Null 'layer' argument."); } this.layers.add(layer); layer.addChangeListener(this); fireChangeEvent(); } /** * Returns the index for the specified layer. * * @param layer the layer (<code>null</code> not permitted). * * @return The layer index. */ public int getLayerIndex(DialLayer layer) { if (layer == null) { throw new IllegalArgumentException("Null 'layer' argument."); } return this.layers.indexOf(layer); } /** * Removes the layer at the specified index and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. */ public void removeLayer(int index) { DialLayer layer = this.layers.get(index); if (layer != null) { layer.removeChangeListener(this); } this.layers.remove(index); fireChangeEvent(); } /** * Removes the specified layer and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param layer the layer (<code>null</code> not permitted). */ public void removeLayer(DialLayer layer) { // defer argument checking removeLayer(getLayerIndex(layer)); } /** * Adds a pointer to the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param pointer the pointer (<code>null</code> not permitted). */ public void addPointer(DialPointer pointer) { if (pointer == null) { throw new IllegalArgumentException("Null 'pointer' argument."); } this.pointers.add(pointer); pointer.addChangeListener(this); fireChangeEvent(); } /** * Returns the index for the specified pointer. * * @param pointer the pointer (<code>null</code> not permitted). * * @return The pointer index. */ public int getPointerIndex(DialPointer pointer) { if (pointer == null) { throw new IllegalArgumentException("Null 'pointer' argument."); } return this.pointers.indexOf(pointer); } /** * Removes the pointer at the specified index and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. */ public void removePointer(int index) { DialPointer pointer = this.pointers.get(index); if (pointer != null) { pointer.removeChangeListener(this); } this.pointers.remove(index); fireChangeEvent(); } /** * Removes the specified pointer and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param pointer the pointer (<code>null</code> not permitted). */ public void removePointer(DialPointer pointer) { // defer argument checking removeLayer(getPointerIndex(pointer)); } /** * Returns the dial pointer that is associated with the specified * dataset, or <code>null</code>. * * @param datasetIndex the dataset index. * * @return The pointer. */ public DialPointer getPointerForDataset(int datasetIndex) { for (DialPointer p : this.pointers) { if (p.getDatasetIndex() == datasetIndex) { return p; } } return null; } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly <code>null</code>). */ public ValueDataset getDataset() { return getDataset(0); } /** * Returns the dataset at the given index. * * @param index the dataset index. * * @return The dataset (possibly <code>null</code>). */ public ValueDataset getDataset(int index) { ValueDataset result = null; if (this.datasets.size() > index) { result = (ValueDataset) this.datasets.get(index); } return result; } /** * Sets the dataset for the plot, replacing the existing dataset, if there * is one, and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param dataset the dataset (<code>null</code> permitted). */ public void setDataset(ValueDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot. * * @param index the dataset index. * @param dataset the dataset (<code>null</code> permitted). */ public void setDataset(int index, ValueDataset dataset) { ValueDataset existing = (ValueDataset) this.datasets.get(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.set(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. */ public int getDatasetCount() { return this.datasets.size(); } /** * Draws the plot. This method is usually called by the {@link JFreeChart} * instance that manages the plot. * * @param g2 the graphics target. * @param area the area in which the plot should be drawn. * @param anchor the anchor point (typically the last point that the * mouse clicked on, <code>null</code> is permitted). * @param parentState the state for the parent plot (if any). * @param info used to collect plot rendering info (<code>null</code> * permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { Shape origClip = g2.getClip(); g2.setClip(area); // first, expand the viewing area into a drawing frame Rectangle2D frame = viewToFrame(area); // draw the background if there is one... if (this.background != null && this.background.isVisible()) { if (this.background.isClippedToWindow()) { Shape savedClip = g2.getClip(); g2.clip(this.dialFrame.getWindow(frame)); this.background.draw(g2, this, frame, area); g2.setClip(savedClip); } else { this.background.draw(g2, this, frame, area); } } for (DialLayer current : this.layers) { if (current.isVisible()) { if (current.isClippedToWindow()) { Shape savedClip = g2.getClip(); g2.clip(this.dialFrame.getWindow(frame)); current.draw(g2, this, frame, area); g2.setClip(savedClip); } else { current.draw(g2, this, frame, area); } } } // draw the pointers for (DialPointer current : this.pointers) { if (current.isVisible()) { if (current.isClippedToWindow()) { Shape savedClip = g2.getClip(); g2.clip(this.dialFrame.getWindow(frame)); current.draw(g2, this, frame, area); g2.setClip(savedClip); } else { current.draw(g2, this, frame, area); } } } // draw the cap if there is one... if (this.cap != null && this.cap.isVisible()) { if (this.cap.isClippedToWindow()) { Shape savedClip = g2.getClip(); g2.clip(this.dialFrame.getWindow(frame)); this.cap.draw(g2, this, frame, area); g2.setClip(savedClip); } else { this.cap.draw(g2, this, frame, area); } } if (this.dialFrame.isVisible()) { this.dialFrame.draw(g2, this, frame, area); } g2.setClip(origClip); } /** * Returns the frame surrounding the specified view rectangle. * * @param view the view rectangle (<code>null</code> not permitted). * * @return The frame rectangle. */ private Rectangle2D viewToFrame(Rectangle2D view) { double width = view.getWidth() / this.viewW; double height = view.getHeight() / this.viewH; double x = view.getX() - (width * this.viewX); double y = view.getY() - (height * this.viewY); return new Rectangle2D.Double(x, y, width, height); } /** * Returns the value from the specified dataset. * * @param datasetIndex the dataset index. * * @return The data value. */ public double getValue(int datasetIndex) { double result = Double.NaN; ValueDataset dataset = getDataset(datasetIndex); if (dataset != null) { Number n = dataset.getValue(); if (n != null) { result = n.doubleValue(); } } return result; } /** * Adds a dial scale to the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the scale index. * @param scale the scale (<code>null</code> not permitted). */ public void addScale(int index, DialScale scale) { if (scale == null) { throw new IllegalArgumentException("Null 'scale' argument."); } DialScale existing = this.scales.get(index); if (existing != null) { removeLayer(existing); } this.layers.add(scale); this.scales.set(index, scale); scale.addChangeListener(this); fireChangeEvent(); } /** * Returns the scale at the given index. * * @param index the scale index. * * @return The scale (possibly <code>null</code>). */ public DialScale getScale(int index) { DialScale result = null; if (this.scales.size() > index) { result = this.scales.get(index); } return result; } /** * Maps a dataset to a particular scale. * * @param index the dataset index (zero-based). * @param scaleIndex the scale index (zero-based). */ public void mapDatasetToScale(int index, int scaleIndex) { this.datasetToScaleMap.set(index, scaleIndex); fireChangeEvent(); } /** * Returns the dial scale for a specific dataset. * * @param datasetIndex the dataset index. * * @return The dial scale. */ public DialScale getScaleForDataset(int datasetIndex) { DialScale result = this.scales.get(0); Integer scaleIndex = this.datasetToScaleMap.get(datasetIndex); if (scaleIndex != null) { result = getScale(scaleIndex); } return result; } /** * A utility method that computes a rectangle using relative radius values. * * @param rect the reference rectangle (<code>null</code> not permitted). * @param radiusW the width radius (must be > 0.0) * @param radiusH the height radius. * * @return A new rectangle. */ public static Rectangle2D rectangleByRadius(Rectangle2D rect, double radiusW, double radiusH) { if (rect == null) { throw new IllegalArgumentException("Null 'rect' argument."); } double x = rect.getCenterX(); double y = rect.getCenterY(); double w = rect.getWidth() * radiusW; double h = rect.getHeight() * radiusH; return new Rectangle2D.Double(x - w / 2.0, y - h / 2.0, w, h); } /** * Receives notification when a layer has changed, and responds by * forwarding a {@link PlotChangeEvent} to all registered listeners. * * @param event the event. */ @Override public void dialLayerChanged(DialLayerChangeEvent event) { fireChangeEvent(); } /** * Tests this <code>DialPlot</code> instance for equality with an * arbitrary object. The plot's dataset(s) is (are) not included in * the test. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialPlot)) { return false; } DialPlot that = (DialPlot) obj; if (!ObjectUtilities.equal(this.background, that.background)) { return false; } if (!ObjectUtilities.equal(this.cap, that.cap)) { return false; } if (!this.dialFrame.equals(that.dialFrame)) { return false; } if (this.viewX != that.viewX) { return false; } if (this.viewY != that.viewY) { return false; } if (this.viewW != that.viewW) { return false; } if (this.viewH != that.viewH) { return false; } if (!this.layers.equals(that.layers)) { return false; } if (!this.pointers.equals(that.pointers)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return The hash code. */ @Override public int hashCode() { int result = 193; result = 37 * result + ObjectUtilities.hashCode(this.background); result = 37 * result + ObjectUtilities.hashCode(this.cap); result = 37 * result + this.dialFrame.hashCode(); long temp = Double.doubleToLongBits(this.viewX); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.viewY); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.viewW); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.viewH); result = 37 * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns the plot type. * * @return <code>"DialPlot"</code> */ @Override public String getPlotType() { return "DialPlot"; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } }
24,790
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialTextAnnotation.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialTextAnnotation.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * DialTextAnnotation.java * ----------------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 08-Mar-2007 : Fix in hashCode() (DG); * 17-Oct-2007 : Updated equals() (DG); * 24-Oct-2007 : Added getAnchor() and setAnchor() methods (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Arc2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.ui.TextAnchor; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.SerialUtilities; /** * A text annotation for a {@link DialPlot}. * * @since 1.0.7 */ public class DialTextAnnotation extends AbstractDialLayer implements DialLayer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = 3065267524054428071L; /** The label text. */ private String label; /** The font. */ private Font font; /** * The paint for the label. This field is transient because it requires * special handling for serialization. */ private transient Paint paint; /** The angle that defines the anchor point for the annotation. */ private double angle; /** The radius that defines the anchor point for the annotation. */ private double radius; /** The text anchor to be aligned to the annotation's anchor point. */ private TextAnchor anchor; /** * Creates a new instance of <code>DialTextAnnotation</code>. * * @param label the label (<code>null</code> not permitted). */ public DialTextAnnotation(String label) { if (label == null) { throw new IllegalArgumentException("Null 'label' argument."); } this.angle = -90.0; this.radius = 0.3; this.font = new Font("Dialog", Font.BOLD, 14); this.paint = Color.BLACK; this.label = label; this.anchor = TextAnchor.TOP_CENTER; } /** * Returns the label text. * * @return The label text (never <code>null</code). * * @see #setLabel(String) */ public String getLabel() { return this.label; } /** * Sets the label and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param label the label (<code>null</code> not permitted). * * @see #getLabel() */ public void setLabel(String label) { if (label == null) { throw new IllegalArgumentException("Null 'label' argument."); } this.label = label; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the font used to display the label. * * @return The font (never <code>null</code>). * * @see #setFont(Font) */ public Font getFont() { return this.font; } /** * Sets the font used to display the label and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getFont() */ public void setFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.font = font; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to display the label. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint used to display the label and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.paint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the angle used to calculate the anchor point. * * @return The angle (in degrees). * * @see #setAngle(double) * @see #getRadius() */ public double getAngle() { return this.angle; } /** * Sets the angle used to calculate the anchor point and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param angle the angle (in degrees). * * @see #getAngle() * @see #setRadius(double) */ public void setAngle(double angle) { this.angle = angle; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the radius used to calculate the anchor point. This is * specified as a percentage relative to the dial's framing rectangle. * * @return The radius. * * @see #setRadius(double) * @see #getAngle() */ public double getRadius() { return this.radius; } /** * Sets the radius used to calculate the anchor point and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param radius the radius (as a percentage of the dial's framing * rectangle). * * @see #getRadius() * @see #setAngle(double) */ public void setRadius(double radius) { if (radius < 0.0) { throw new IllegalArgumentException( "The 'radius' cannot be negative."); } this.radius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the text anchor point that will be aligned to the position * specified by {@link #getAngle()} and {@link #getRadius()}. * * @return The anchor point. * * @see #setAnchor(TextAnchor) */ public TextAnchor getAnchor() { return this.anchor; } /** * Sets the text anchor point and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param anchor the anchor point (<code>null</code> not permitted). * * @see #getAnchor() */ public void setAnchor(TextAnchor anchor) { if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' argument."); } this.anchor = anchor; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> to indicate that this layer should be * clipped within the dial window. * * @return <code>true</code>. */ @Override public boolean isClippedToWindow() { return true; } /** * Draws the background to the specified graphics device. If the dial * frame specifies a window, the clipping region will already have been * set to this window before this method is called. * * @param g2 the graphics device (<code>null</code> not permitted). * @param plot the plot (ignored here). * @param frame the dial frame (ignored here). * @param view the view rectangle (<code>null</code> not permitted). */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { // work out the anchor point Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius, this.radius); Arc2D arc = new Arc2D.Double(f, this.angle, 0.0, Arc2D.OPEN); Point2D pt = arc.getStartPoint(); g2.setPaint(this.paint); g2.setFont(this.font); TextUtilities.drawAlignedString(this.label, g2, (float) pt.getX(), (float) pt.getY(), this.anchor); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialTextAnnotation)) { return false; } DialTextAnnotation that = (DialTextAnnotation) obj; if (!this.label.equals(that.label)) { return false; } if (!this.font.equals(that.font)) { return false; } if (!PaintUtilities.equal(this.paint, that.paint)) { return false; } if (this.radius != that.radius) { return false; } if (this.angle != that.angle) { return false; } if (!this.anchor.equals(that.anchor)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return The hash code. */ @Override public int hashCode() { int result = 193; result = 37 * result + HashUtilities.hashCodeForPaint(this.paint); result = 37 * result + this.font.hashCode(); result = 37 * result + this.label.hashCode(); result = 37 * result + this.anchor.hashCode(); long temp = Double.doubleToLongBits(this.angle); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.radius); result = 37 * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns a clone of this instance. * * @return The clone. * * @throws CloneNotSupportedException if some attribute of this instance * cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); } }
12,252
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardDialFrame.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/StandardDialFrame.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * StandardDialFrame.java * ---------------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 08-Mar-2007 : Fix in hashCode() (DG); * 29-Oct-2007 : Renamed StandardDialFrame (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; /** * A simple circular frame for the {@link DialPlot} class. * * @since 1.0.7 */ public class StandardDialFrame extends AbstractDialLayer implements DialFrame, Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = 1016585407507121596L; /** The outer radius, relative to the framing rectangle. */ private double radius; /** * The color used for the front of the panel. This field is transient * because it requires special handling for serialization. */ private transient Paint backgroundPaint; /** * The color used for the border around the window. This field is transient * because it requires special handling for serialization. */ private transient Paint foregroundPaint; /** * The stroke for drawing the frame outline. This field is transient * because it requires special handling for serialization. */ private transient Stroke stroke; /** * Creates a new instance of <code>StandardDialFrame</code>. */ public StandardDialFrame() { this.backgroundPaint = Color.GRAY; this.foregroundPaint = Color.BLACK; this.stroke = new BasicStroke(2.0f); this.radius = 0.95; } /** * Returns the radius, relative to the framing rectangle. * * @return The radius. * * @see #setRadius(double) */ public double getRadius() { return this.radius; } /** * Sets the radius and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param radius the radius (must be positive). * * @see #getRadius() */ public void setRadius(double radius) { if (radius <= 0) { throw new IllegalArgumentException( "The 'radius' must be positive."); } this.radius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the background paint. * * @return The background paint (never <code>null</code>). * * @see #setBackgroundPaint(Paint) */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getBackgroundPaint() */ public void setBackgroundPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.backgroundPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the foreground paint. * * @return The foreground paint (never <code>null</code>). * * @see #setForegroundPaint(Paint) */ public Paint getForegroundPaint() { return this.foregroundPaint; } /** * Sets the foreground paint and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getForegroundPaint() */ public void setForegroundPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.foregroundPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the stroke for the frame. * * @return The stroke (never <code>null</code>). * * @see #setStroke(Stroke) */ public Stroke getStroke() { return this.stroke; } /** * Sets the stroke and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getStroke() */ public void setStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.stroke = stroke; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the shape for the window for this dial. Some dial layers will * request that their drawing be clipped within this window. * * @param frame the reference frame (<code>null</code> not permitted). * * @return The shape of the dial's window. */ @Override public Shape getWindow(Rectangle2D frame) { Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius, this.radius); return new Ellipse2D.Double(f.getX(), f.getY(), f.getWidth(), f.getHeight()); } /** * Returns <code>false</code> to indicate that this dial layer is not * clipped to the dial window. * * @return A boolean. */ @Override public boolean isClippedToWindow() { return false; } /** * Draws the frame. This method is called by the {@link DialPlot} class, * you shouldn't need to call it directly. * * @param g2 the graphics target (<code>null</code> not permitted). * @param plot the plot (<code>null</code> not permitted). * @param frame the frame (<code>null</code> not permitted). * @param view the view (<code>null</code> not permitted). */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { Shape window = getWindow(frame); Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius + 0.02, this.radius + 0.02); Ellipse2D e = new Ellipse2D.Double(f.getX(), f.getY(), f.getWidth(), f.getHeight()); Area area = new Area(e); Area area2 = new Area(window); area.subtract(area2); g2.setPaint(this.backgroundPaint); g2.fill(area); g2.setStroke(this.stroke); g2.setPaint(this.foregroundPaint); g2.draw(window); g2.draw(e); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardDialFrame)) { return false; } StandardDialFrame that = (StandardDialFrame) obj; if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } if (!PaintUtilities.equal(this.foregroundPaint, that.foregroundPaint)) { return false; } if (this.radius != that.radius) { return false; } if (!this.stroke.equals(that.stroke)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return The hash code. */ @Override public int hashCode() { int result = 193; long temp = Double.doubleToLongBits(this.radius); result = 37 * result + (int) (temp ^ (temp >>> 32)); result = 37 * result + HashUtilities.hashCodeForPaint( this.backgroundPaint); result = 37 * result + HashUtilities.hashCodeForPaint( this.foregroundPaint); result = 37 * result + this.stroke.hashCode(); return result; } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if any of the frame's attributes * cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.backgroundPaint, stream); SerialUtilities.writePaint(this.foregroundPaint, stream); SerialUtilities.writeStroke(this.stroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.backgroundPaint = SerialUtilities.readPaint(stream); this.foregroundPaint = SerialUtilities.readPaint(stream); this.stroke = SerialUtilities.readStroke(stream); } }
11,164
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialLayer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialLayer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * DialLayer.java * -------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * */ package org.jfree.chart.plot.dial; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.EventListener; /** * A dial layer draws itself within a reference frame. The view frame is a * subset of the reference frame, and defines the area that is actually * visible. * <br><br> * Classes that implement this interface should be {@link Serializable}, * otherwise chart serialization may fail. * * @since 1.0.7 */ public interface DialLayer { /** * Returns a flag that indicates whether or not the layer is visible. * * @return A boolean. */ public boolean isVisible(); /** * Registers a listener with this layer, so that it receives notification * of changes to this layer. * * @param listener the listener. */ public void addChangeListener(DialLayerChangeListener listener); /** * Deregisters a listener, so that it no longer receives notification of * changes to this layer. * * @param listener the listener. */ public void removeChangeListener(DialLayerChangeListener listener); /** * Returns <code>true</code> if the specified listener is currently * registered with the this layer. * * @param listener the listener. * * @return A boolean. */ public boolean hasListener(EventListener listener); /** * Returns <code>true</code> if the drawing should be clipped to the * dial window (which is defined by the {@link DialFrame}), and * <code>false</code> otherwise. * * @return A boolean. */ public boolean isClippedToWindow(); /** * Draws the content of this layer. * * @param g2 the graphics target (<code>null</code> not permitted). * @param plot the plot (typically this should not be <code>null</code>, * but for a layer that doesn't need to reference the plot, it may * be permitted). * @param frame the reference frame for the dial's geometry * (<code>null</code> not permitted). This is typically larger than * the visible area of the dial (see the next parameter). * @param view the visible area for the dial (<code>null</code> not * permitted). */ public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); }
3,890
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialPointer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialPointer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * DialPointer.java * ---------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 17-Oct-2007 : Added equals() overrides (DG); * 24-Oct-2007 : Implemented PublicCloneable, changed default radius, * and added argument checks (DG); * 23-Nov-2007 : Added fillPaint and outlinePaint attributes to * DialPointer.Pointer (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; /** * A base class for the pointer in a {@link DialPlot}. * * @since 1.0.7 */ public abstract class DialPointer extends AbstractDialLayer implements DialLayer, Cloneable, PublicCloneable, Serializable { /** The needle radius. */ double radius; /** * The dataset index for the needle. */ int datasetIndex; /** * Creates a new <code>DialPointer</code> instance. */ protected DialPointer() { this(0); } /** * Creates a new pointer for the specified dataset. * * @param datasetIndex the dataset index. */ protected DialPointer(int datasetIndex) { this.radius = 0.9; this.datasetIndex = datasetIndex; } /** * Returns the dataset index that the pointer maps to. * * @return The dataset index. * * @see #getDatasetIndex() */ public int getDatasetIndex() { return this.datasetIndex; } /** * Sets the dataset index for the pointer and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param index the index. * * @see #getDatasetIndex() */ public void setDatasetIndex(int index) { this.datasetIndex = index; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the radius of the pointer, as a percentage of the dial's * framing rectangle. * * @return The radius. * * @see #setRadius(double) */ public double getRadius() { return this.radius; } /** * Sets the radius of the pointer and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param radius the radius. * * @see #getRadius() */ public void setRadius(double radius) { this.radius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> to indicate that this layer should be * clipped within the dial window. * * @return <code>true</code>. */ @Override public boolean isClippedToWindow() { return true; } /** * Checks this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> not permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialPointer)) { return false; } DialPointer that = (DialPointer) obj; if (this.datasetIndex != that.datasetIndex) { return false; } if (this.radius != that.radius) { return false; } return super.equals(obj); } /** * Returns a hash code. * * @return A hash code. */ @Override public int hashCode() { int result = 23; result = HashUtilities.hashCode(result, this.radius); return result; } /** * Returns a clone of the pointer. * * @return a clone. * * @throws CloneNotSupportedException if one of the attributes cannot * be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * A dial pointer that draws a thin line (like a pin). */ public static class Pin extends DialPointer { /** For serialization. */ static final long serialVersionUID = -8445860485367689750L; /** The paint. */ private transient Paint paint; /** The stroke. */ private transient Stroke stroke; /** * Creates a new instance. */ public Pin() { this(0); } /** * Creates a new instance. * * @param datasetIndex the dataset index. */ public Pin(int datasetIndex) { super(datasetIndex); this.paint = Color.RED; this.stroke = new BasicStroke(3.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL); } /** * Returns the paint. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.paint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the stroke. * * @return The stroke (never <code>null</code>). * * @see #setStroke(Stroke) */ public Stroke getStroke() { return this.stroke; } /** * Sets the stroke and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getStroke() */ public void setStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.stroke = stroke; notifyListeners(new DialLayerChangeEvent(this)); } /** * Draws the pointer. * * @param g2 the graphics target. * @param plot the plot. * @param frame the dial's reference frame. * @param view the dial's view. */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { g2.setPaint(this.paint); g2.setStroke(this.stroke); Rectangle2D arcRect = DialPlot.rectangleByRadius(frame, this.radius, this.radius); double value = plot.getValue(this.datasetIndex); DialScale scale = plot.getScaleForDataset(this.datasetIndex); double angle = scale.valueToAngle(value); Arc2D arc = new Arc2D.Double(arcRect, angle, 0, Arc2D.OPEN); Point2D pt = arc.getEndPoint(); Line2D line = new Line2D.Double(frame.getCenterX(), frame.getCenterY(), pt.getX(), pt.getY()); g2.draw(line); } /** * Tests this pointer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialPointer.Pin)) { return false; } DialPointer.Pin that = (DialPointer.Pin) obj; if (!PaintUtilities.equal(this.paint, that.paint)) { return false; } if (!this.stroke.equals(that.stroke)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = super.hashCode(); result = HashUtilities.hashCode(result, this.paint); result = HashUtilities.hashCode(result, this.stroke); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); SerialUtilities.writeStroke(this.stroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); this.stroke = SerialUtilities.readStroke(stream); } } /** * A dial pointer. */ public static class Pointer extends DialPointer { /** For serialization. */ static final long serialVersionUID = -4180500011963176960L; /** * The radius that defines the width of the pointer at the base. */ private double widthRadius; /** * The fill paint. * * @since 1.0.8 */ private transient Paint fillPaint; /** * The outline paint. * * @since 1.0.8 */ private transient Paint outlinePaint; /** * Creates a new instance. */ public Pointer() { this(0); } /** * Creates a new instance. * * @param datasetIndex the dataset index. */ public Pointer(int datasetIndex) { super(datasetIndex); this.widthRadius = 0.05; this.fillPaint = Color.GRAY; this.outlinePaint = Color.BLACK; } /** * Returns the width radius. * * @return The width radius. * * @see #setWidthRadius(double) */ public double getWidthRadius() { return this.widthRadius; } /** * Sets the width radius and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param radius the radius * * @see #getWidthRadius() */ public void setWidthRadius(double radius) { this.widthRadius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the fill paint. * * @return The paint (never <code>null</code>). * * @see #setFillPaint(Paint) * * @since 1.0.8 */ public Paint getFillPaint() { return this.fillPaint; } /** * Sets the fill paint and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getFillPaint() * * @since 1.0.8 */ public void setFillPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.fillPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the outline paint. * * @return The paint (never <code>null</code>). * * @see #setOutlinePaint(Paint) * * @since 1.0.8 */ public Paint getOutlinePaint() { return this.outlinePaint; } /** * Sets the outline paint and sends a {@link DialLayerChangeEvent} to * all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getOutlinePaint() * * @since 1.0.8 */ public void setOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.outlinePaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Draws the pointer. * * @param g2 the graphics target. * @param plot the plot. * @param frame the dial's reference frame. * @param view the dial's view. */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { g2.setPaint(Color.BLUE); g2.setStroke(new BasicStroke(1.0f)); Rectangle2D lengthRect = DialPlot.rectangleByRadius(frame, this.radius, this.radius); Rectangle2D widthRect = DialPlot.rectangleByRadius(frame, this.widthRadius, this.widthRadius); double value = plot.getValue(this.datasetIndex); DialScale scale = plot.getScaleForDataset(this.datasetIndex); double angle = scale.valueToAngle(value); Arc2D arc1 = new Arc2D.Double(lengthRect, angle, 0, Arc2D.OPEN); Point2D pt1 = arc1.getEndPoint(); Arc2D arc2 = new Arc2D.Double(widthRect, angle - 90.0, 180.0, Arc2D.OPEN); Point2D pt2 = arc2.getStartPoint(); Point2D pt3 = arc2.getEndPoint(); Arc2D arc3 = new Arc2D.Double(widthRect, angle - 180.0, 0.0, Arc2D.OPEN); Point2D pt4 = arc3.getStartPoint(); GeneralPath gp = new GeneralPath(); gp.moveTo((float) pt1.getX(), (float) pt1.getY()); gp.lineTo((float) pt2.getX(), (float) pt2.getY()); gp.lineTo((float) pt4.getX(), (float) pt4.getY()); gp.lineTo((float) pt3.getX(), (float) pt3.getY()); gp.closePath(); g2.setPaint(this.fillPaint); g2.fill(gp); g2.setPaint(this.outlinePaint); Line2D line = new Line2D.Double(frame.getCenterX(), frame.getCenterY(), pt1.getX(), pt1.getY()); g2.draw(line); line.setLine(pt2, pt3); g2.draw(line); line.setLine(pt3, pt1); g2.draw(line); line.setLine(pt2, pt1); g2.draw(line); line.setLine(pt2, pt4); g2.draw(line); line.setLine(pt3, pt4); g2.draw(line); } /** * Tests this pointer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialPointer.Pointer)) { return false; } DialPointer.Pointer that = (DialPointer.Pointer) obj; if (this.widthRadius != that.widthRadius) { return false; } if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) { return false; } if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = super.hashCode(); result = HashUtilities.hashCode(result, this.widthRadius); result = HashUtilities.hashCode(result, this.fillPaint); result = HashUtilities.hashCode(result, this.outlinePaint); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.fillPaint, stream); SerialUtilities.writePaint(this.outlinePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.fillPaint = SerialUtilities.readPaint(stream); this.outlinePaint = SerialUtilities.readPaint(stream); } } }
19,469
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialFrame.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialFrame.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * DialFrame.java * -------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * */ package org.jfree.chart.plot.dial; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A dial frame is the face plate for a dial plot - it is always drawn last. * JFreeChart includes a couple of implementations of this interface * ({@link StandardDialFrame} and {@link ArcDialFrame}). * <br><br> * Classes that implement this interface should be {@link Serializable}, * otherwise chart serialization may fail. * * @since 1.0.7 */ public interface DialFrame extends DialLayer { /** * Returns the shape of the viewing window for the dial, or * <code>null</code> if the dial is completely open. Other layers in the * plot will rely on their drawing to be clipped within this window. * * @param frame the reference frame for the dial. * * @return The window. */ public Shape getWindow(Rectangle2D frame); }
2,399
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialLayerChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialLayerChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * DialLayerChangeListener.java * ---------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 06-Nov-2006 : Version 1 (DG); * */ package org.jfree.chart.plot.dial; import java.util.EventListener; /** * The interface via which an object is notified of changes to a * {@link DialLayer}. The {@link DialPlot} class listens for changes to its * layers in this way. * * @since 1.0.7 */ public interface DialLayerChangeListener extends EventListener { /** * A call-back method for receiving notification of a change to a * {@link DialLayer}. * * @param event the event. */ public void dialLayerChanged(DialLayerChangeEvent event); }
2,078
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialCap.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialCap.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------ * DialCap.java * ------------ * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 17-Oct-2007 : Updated equals() method (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; /** * A regular dial layer that can be used to draw a cap over the center of * the dial (the base of the dial pointer(s)). * * @since 1.0.7 */ public class DialCap extends AbstractDialLayer implements DialLayer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = -2929484264982524463L; /** * The radius of the cap, as a percentage of the framing rectangle. */ private double radius; /** * The fill paint. This field is transient because it requires special * handling for serialization. */ private transient Paint fillPaint; /** * The paint used to draw the cap outline (this should never be * <code>null</code>). This field is transient because it requires * special handling for serialization. */ private transient Paint outlinePaint; /** * The stroke used to draw the cap outline (this should never be * <code>null</code>). This field is transient because it requires * special handling for serialization. */ private transient Stroke outlineStroke; /** * Creates a new instance of <code>StandardDialBackground</code>. The * default background paint is <code>Color.WHITE</code>. */ public DialCap() { this.radius = 0.05; this.fillPaint = Color.WHITE; this.outlinePaint = Color.BLACK; this.outlineStroke = new BasicStroke(2.0f); } /** * Returns the radius of the cap, as a percentage of the dial's framing * rectangle. * * @return The radius. * * @see #setRadius(double) */ public double getRadius() { return this.radius; } /** * Sets the radius of the cap, as a percentage of the dial's framing * rectangle, and sends a {@link DialLayerChangeEvent} to all registered * listeners. * * @param radius the radius (must be greater than zero). * * @see #getRadius() */ public void setRadius(double radius) { if (radius <= 0.0) { throw new IllegalArgumentException("Requires radius > 0.0."); } this.radius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to fill the cap. * * @return The paint (never <code>null</code>). * * @see #setFillPaint(Paint) */ public Paint getFillPaint() { return this.fillPaint; } /** * Sets the paint for the cap background and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getFillPaint() */ public void setFillPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.fillPaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to draw the outline of the cap. * * @return The paint (never <code>null</code>). * * @see #setOutlinePaint(Paint) */ public Paint getOutlinePaint() { return this.outlinePaint; } /** * Sets the paint used to draw the outline of the cap and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getOutlinePaint() */ public void setOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.outlinePaint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the stroke used to draw the outline of the cap. * * @return The stroke (never <code>null</code>). * * @see #setOutlineStroke(Stroke) */ public Stroke getOutlineStroke() { return this.outlineStroke; } /** * Sets the stroke used to draw the outline of the cap and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getOutlineStroke() */ public void setOutlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.outlineStroke = stroke; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> to indicate that this layer should be * clipped within the dial window. * * @return <code>true</code>. */ @Override public boolean isClippedToWindow() { return true; } /** * Draws the background to the specified graphics device. If the dial * frame specifies a window, the clipping region will already have been * set to this window before this method is called. * * @param g2 the graphics device (<code>null</code> not permitted). * @param plot the plot (ignored here). * @param frame the dial frame (ignored here). * @param view the view rectangle (<code>null</code> not permitted). */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { g2.setPaint(this.fillPaint); Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius, this.radius); Ellipse2D e = new Ellipse2D.Double(f.getX(), f.getY(), f.getWidth(), f.getHeight()); g2.fill(e); g2.setPaint(this.outlinePaint); g2.setStroke(this.outlineStroke); g2.draw(e); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof DialCap)) { return false; } DialCap that = (DialCap) obj; if (this.radius != that.radius) { return false; } if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) { return false; } if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) { return false; } if (!this.outlineStroke.equals(that.outlineStroke)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return The hash code. */ @Override public int hashCode() { int result = 193; result = 37 * result + HashUtilities.hashCodeForPaint(this.fillPaint); result = 37 * result + HashUtilities.hashCodeForPaint( this.outlinePaint); result = 37 * result + this.outlineStroke.hashCode(); return result; } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if some attribute of the cap cannot * be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.fillPaint, stream); SerialUtilities.writePaint(this.outlinePaint, stream); SerialUtilities.writeStroke(this.outlineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.fillPaint = SerialUtilities.readPaint(stream); this.outlinePaint = SerialUtilities.readPaint(stream); this.outlineStroke = SerialUtilities.readStroke(stream); } }
10,547
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardDialRange.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/StandardDialRange.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * StandardDialRange.java * ---------------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * 08-Mar-2007 : Fix in hashCode() (DG); * 17-Oct-2007 : Removed increment attribute (DG); * 24-Oct-2007 : Added scaleIndex (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.dial; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Arc2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; /** * A layer that draws a range highlight on a dial plot. * * @since 1.0.7 */ public class StandardDialRange extends AbstractDialLayer implements DialLayer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = 345515648249364904L; /** The scale index. */ private int scaleIndex; /** The minimum data value for the scale. */ private double lowerBound; /** The maximum data value for the scale. */ private double upperBound; /** * The paint used to draw the range highlight. This field is transient * because it requires special handling for serialization. */ private transient Paint paint; /** * The factor (in the range 0.0 to 1.0) that determines the inside limit * of the range highlight. */ private double innerRadius; /** * The factor (in the range 0.0 to 1.0) that determines the outside limit * of the range highlight. */ private double outerRadius; /** * Creates a new instance of <code>StandardDialRange</code>. */ public StandardDialRange() { this(0.0, 100.0, Color.WHITE); } /** * Creates a new instance of <code>StandardDialRange</code>. * * @param lower the lower bound. * @param upper the upper bound. * @param paint the paint (<code>null</code> not permitted). */ public StandardDialRange(double lower, double upper, Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.scaleIndex = 0; this.lowerBound = lower; this.upperBound = upper; this.innerRadius = 0.48; this.outerRadius = 0.52; this.paint = paint; } /** * Returns the scale index. * * @return The scale index. * * @see #setScaleIndex(int) */ public int getScaleIndex() { return this.scaleIndex; } /** * Sets the scale index and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param index the scale index. * * @see #getScaleIndex() */ public void setScaleIndex(int index) { this.scaleIndex = index; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the lower bound (a data value) of the dial range. * * @return The lower bound of the dial range. * * @see #setLowerBound(double) */ public double getLowerBound() { return this.lowerBound; } /** * Sets the lower bound of the dial range and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param bound the lower bound. * * @see #getLowerBound() */ public void setLowerBound(double bound) { if (bound >= this.upperBound) { throw new IllegalArgumentException( "Lower bound must be less than upper bound."); } this.lowerBound = bound; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the upper bound of the dial range. * * @return The upper bound. * * @see #setUpperBound(double) */ public double getUpperBound() { return this.upperBound; } /** * Sets the upper bound of the dial range and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param bound the upper bound. * * @see #getUpperBound() */ public void setUpperBound(double bound) { if (bound <= this.lowerBound) { throw new IllegalArgumentException( "Lower bound must be less than upper bound."); } this.upperBound = bound; notifyListeners(new DialLayerChangeEvent(this)); } /** * Sets the bounds for the range and sends a {@link DialLayerChangeEvent} * to all registered listeners. * * @param lower the lower bound. * @param upper the upper bound. */ public void setBounds(double lower, double upper) { if (lower >= upper) { throw new IllegalArgumentException( "Lower must be less than upper."); } this.lowerBound = lower; this.upperBound = upper; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the paint used to highlight the range. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint used to highlight the range and sends a * {@link DialLayerChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.paint = paint; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the inner radius. * * @return The inner radius. * * @see #setInnerRadius(double) */ public double getInnerRadius() { return this.innerRadius; } /** * Sets the inner radius and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param radius the radius. * * @see #getInnerRadius() */ public void setInnerRadius(double radius) { this.innerRadius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns the outer radius. * * @return The outer radius. * * @see #setOuterRadius(double) */ public double getOuterRadius() { return this.outerRadius; } /** * Sets the outer radius and sends a {@link DialLayerChangeEvent} to all * registered listeners. * * @param radius the radius. * * @see #getOuterRadius() */ public void setOuterRadius(double radius) { this.outerRadius = radius; notifyListeners(new DialLayerChangeEvent(this)); } /** * Returns <code>true</code> to indicate that this layer should be * clipped within the dial window. * * @return <code>true</code>. */ @Override public boolean isClippedToWindow() { return true; } /** * Draws the range. * * @param g2 the graphics target. * @param plot the plot. * @param frame the dial's reference frame (in Java2D space). * @param view the dial's view rectangle (in Java2D space). */ @Override public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) { Rectangle2D arcRectInner = DialPlot.rectangleByRadius(frame, this.innerRadius, this.innerRadius); Rectangle2D arcRectOuter = DialPlot.rectangleByRadius(frame, this.outerRadius, this.outerRadius); DialScale scale = plot.getScale(this.scaleIndex); if (scale == null) { throw new RuntimeException("No scale for scaleIndex = " + this.scaleIndex); } double angleMin = scale.valueToAngle(this.lowerBound); double angleMax = scale.valueToAngle(this.upperBound); Arc2D arcInner = new Arc2D.Double(arcRectInner, angleMin, angleMax - angleMin, Arc2D.OPEN); Arc2D arcOuter = new Arc2D.Double(arcRectOuter, angleMax, angleMin - angleMax, Arc2D.OPEN); g2.setPaint(this.paint); g2.setStroke(new BasicStroke(2.0f)); g2.draw(arcInner); g2.draw(arcOuter); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardDialRange)) { return false; } StandardDialRange that = (StandardDialRange) obj; if (this.scaleIndex != that.scaleIndex) { return false; } if (this.lowerBound != that.lowerBound) { return false; } if (this.upperBound != that.upperBound) { return false; } if (!PaintUtilities.equal(this.paint, that.paint)) { return false; } if (this.innerRadius != that.innerRadius) { return false; } if (this.outerRadius != that.outerRadius) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return The hash code. */ @Override public int hashCode() { int result = 193; long temp = Double.doubleToLongBits(this.lowerBound); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.upperBound); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.innerRadius); result = 37 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.outerRadius); result = 37 * result + (int) (temp ^ (temp >>> 32)); result = 37 * result + HashUtilities.hashCodeForPaint(this.paint); return result; } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if any of the attributes of this * instance cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); } }
12,892
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DialLayerChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/plot/dial/DialLayerChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * DialLayerChangeEvent.java * ------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 06-Nov-2006 : Version 1 (DG); * */ package org.jfree.chart.plot.dial; import org.jfree.chart.event.ChartChangeEvent; /** * An event that can be forwarded to any {@link DialLayerChangeListener} to * signal a change to a {@link DialLayer}. * * @since 1.0.7 */ public class DialLayerChangeEvent extends ChartChangeEvent { /** The dial layer that generated the event. */ private DialLayer layer; /** * Creates a new instance. * * @param layer the dial layer that generated the event. */ public DialLayerChangeEvent(DialLayer layer) { super(layer); this.layer = layer; } /** * Returns the layer that generated the event. * * @return The layer that generated the event. */ public DialLayer getDialLayer() { return this.layer; } }
2,323
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ChartProgressEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/ChartProgressEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * ChartProgressEvent.java * ----------------------- * (C) Copyright 2003-2010, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 14-Jan-2003 : Version 1 (DG); * 20-Jan-2010 : Fixed bug in constructor (DG); * */ package org.jfree.chart.event; import org.jfree.chart.JFreeChart; /** * An event that contains information about the drawing progress of a chart. */ public class ChartProgressEvent extends java.util.EventObject { /** Indicates drawing has started. */ public static final int DRAWING_STARTED = 1; /** Indicates drawing has finished. */ public static final int DRAWING_FINISHED = 2; /** The type of event. */ private int type; /** The percentage of completion. */ private int percent; /** The chart that generated the event. */ private JFreeChart chart; /** * Creates a new chart change event. * * @param source the source of the event (could be the chart, a title, an * axis etc.) * @param chart the chart that generated the event. * @param type the type of event. * @param percent the percentage of completion. */ public ChartProgressEvent(Object source, JFreeChart chart, int type, int percent) { super(source); this.chart = chart; this.type = type; this.percent = percent; } /** * Returns the chart that generated the change event. * * @return The chart that generated the change event. */ public JFreeChart getChart() { return this.chart; } /** * Sets the chart that generated the change event. * * @param chart the chart that generated the event. */ public void setChart(JFreeChart chart) { this.chart = chart; } /** * Returns the event type. * * @return The event type. */ public int getType() { return this.type; } /** * Sets the event type. * * @param type the event type. */ public void setType(int type) { this.type = type; } /** * Returns the percentage complete. * * @return The percentage complete. */ public int getPercent() { return this.percent; } /** * Sets the percentage complete. * * @param percent the percentage. */ public void setPercent(int percent) { this.percent = percent; } }
3,804
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/package-info.java
/** * Event classes and listener interfaces, used to provide a change * notification mechanism so that charts are automatically redrawn * whenever changes are made to any chart component. */ package org.jfree.chart.event;
226
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
TitleChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/TitleChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * TitleChangeListener.java * ------------------------ * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Oct-2002 : Now extends EventListener (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of changes to a chart title. * */ public interface TitleChangeListener extends EventListener { /** * Receives notification of a chart title change event. * * @param event the event. */ public void titleChanged(TitleChangeEvent event); }
2,181
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PlotChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/PlotChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * PlotChangeListener.java * ----------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Oct-2002 : Now extends EventListener (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of changes to a plot. * */ public interface PlotChangeListener extends EventListener { /** * Receives notification of a plot change event. * * @param event the event. */ public void plotChanged(PlotChangeEvent event); }
2,161
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OverlayChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/OverlayChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * OverlayChangeEvent.java * ----------------------- * (C) Copyright 2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 09-Apr-2009 : Version 1 (DG); * */ package org.jfree.chart.event; import java.util.EventObject; import org.jfree.chart.panel.Overlay; /** * A change event for an {@link Overlay}. * * @since 1.0.13 */ public class OverlayChangeEvent extends EventObject { /** * Creates a new change event. * * @param source the event source. */ public OverlayChangeEvent(Object source) { super(source); } }
1,924
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PlotChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/PlotChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * PlotChangeEvent.java * -------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * */ package org.jfree.chart.event; import org.jfree.chart.plot.Plot; /** * An event that can be forwarded to any * {@link org.jfree.chart.event.PlotChangeListener} to signal a change to a * plot. */ public class PlotChangeEvent extends ChartChangeEvent { /** The plot that generated the event. */ private Plot plot; /** * Creates a new PlotChangeEvent. * * @param plot the plot that generated the event. */ public PlotChangeEvent(Plot plot) { super(plot); this.plot = plot; } /** * Returns the plot that generated the event. * * @return The plot that generated the event. */ public Plot getPlot() { return this.plot; } }
2,481
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
RendererChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/RendererChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * RendererChangeEvent.java * ------------------------ * (C) Copyright 2003-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Oct-2003 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 04-Apr-2007 : Fixed typo in API docs (DG); * 26-Mar-2009 : Added flag to signal visible series change (DG); * */ package org.jfree.chart.event; /** * An event that can be forwarded to any {@link RendererChangeListener} to * signal a change to a renderer. */ public class RendererChangeEvent extends ChartChangeEvent { /** The renderer that generated the event. */ private Object renderer; /** * A flag that indicates whether this event relates to a change in the * series visibility. If so, the receiver (if it is a plot) may want to * update the axis bounds. * * @since 1.0.13 */ private boolean seriesVisibilityChanged; /** * Creates a new event. * * @param renderer the renderer that generated the event. */ public RendererChangeEvent(Object renderer) { this(renderer, false); } /** * Creates a new event. * * @param renderer the renderer that generated the event. * @param seriesVisibilityChanged a flag that indicates whether or not * the event relates to a change in the series visibility flags. */ public RendererChangeEvent(Object renderer, boolean seriesVisibilityChanged) { super(renderer); this.renderer = renderer; this.seriesVisibilityChanged = seriesVisibilityChanged; } /** * Returns the renderer that generated the event. * * @return The renderer that generated the event. */ public Object getRenderer() { return this.renderer; } /** * Returns the flag that indicates whether or not the event relates to * a change in series visibility. * * @return A boolean. * * @since 1.0.13 */ public boolean getSeriesVisibilityChanged() { return this.seriesVisibilityChanged; } }
3,468
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ChartProgressListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/ChartProgressListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * ChartProgressListener.java * -------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 14-Jan-2003 : Version 1 (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of chart progress events. */ public interface ChartProgressListener extends EventListener { /** * Receives notification of a chart progress event. * * @param event the event. */ public void chartProgress(ChartProgressEvent event); }
1,989
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
TitleChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/TitleChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * TitleChangeEvent.java * --------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 22-Jun-2001) * -------------------------- * 22-Jun-2001 : Changed Title to AbstractTitle while incorporating * David Berry's changes (DG); * 24-Aug-2001 : Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 08-Jan-2004 : Renamed AbstractTitle --> Title and moved to new package (DG); * */ package org.jfree.chart.event; import org.jfree.chart.title.Title; /** * A change event that encapsulates information about a change to a chart title. */ public class TitleChangeEvent extends ChartChangeEvent { /** The chart title that generated the event. */ private Title title; /** * Default constructor. * * @param title the chart title that generated the event. */ public TitleChangeEvent(Title title) { super(title); this.title = title; } /** * Returns the title that generated the event. * * @return The title that generated the event. */ public Title getTitle() { return this.title; } }
2,559
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ChartChangeEventType.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/ChartChangeEventType.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * ChartChangeEventType.java * ------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 18-Feb-2005 : Version 1 (DG); * */ package org.jfree.chart.event; /** * Defines tokens used to indicate an event type. */ public enum ChartChangeEventType { /** GENERAL. */ GENERAL("ChartChangeEventType.GENERAL"), /** NEW_DATASET. */ NEW_DATASET("ChartChangeEventType.NEW_DATASET"), /** DATASET_UPDATED. */ DATASET_UPDATED("ChartChangeEventType.DATASET_UPDATED"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private ChartChangeEventType(String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ @Override public String toString() { return this.name; } }
2,273
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AnnotationChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/AnnotationChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * AnnotationChangeEvent.java * -------------------------- * (C) Copyright 2009, by Object Refinery Limited and Contributors. * * Original Author: Peter Kolb (patch 2809117); * Contributor(s): ; * * Changes: * -------- * 20-Jun-2009 : Version 1 (PK); * */ package org.jfree.chart.event; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.util.ParamChecks; /** * An event that can be forwarded to any {@link AnnotationChangeListener} to * signal a change to an {@link Annotation}. * * @since 1.0.14 */ public class AnnotationChangeEvent extends ChartChangeEvent { /** The annotation that generated the event. */ private Annotation annotation; /** * Creates a new <code>AnnotationChangeEvent</code> instance. * * @param source the event source. * @param annotation the annotation that triggered the event * (<code>null</code> not permitted). * * @since 1.0.14 */ public AnnotationChangeEvent(Object source, Annotation annotation) { super(source); ParamChecks.nullNotPermitted(annotation, "annotation"); this.annotation = annotation; } /** * Returns the annotation that triggered the event. * * @return The annotation that triggered the event (never <code>null</code>). * * @since 1.0.14 */ public Annotation getAnnotation() { return this.annotation; } }
2,690
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AxisChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/AxisChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * AxisChangeEvent.java * -------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 14-Oct-2002 : Now extends EventListener (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of changes to an axis. * <P> * The Plot class implements this interface, and automatically registers with * its axes (if any). Any axis changes are passed on by the plot as a plot * change event. This is part of the notification mechanism that ensures that * charts are redrawn whenever changes are made to any chart component. * */ public interface AxisChangeListener extends EventListener { /** * Receives notification of an axis change event. * * @param event the event. */ public void axisChanged(AxisChangeEvent event); }
2,406
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
RendererChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/RendererChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * RendererChangeListener.java * --------------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Oct-2003 : Added standard source header. Fixed DOS encoding problem (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of changes to a renderer. * */ public interface RendererChangeListener extends EventListener { /** * Receives notification of a renderer change event. * * @param event the event. */ public void rendererChanged(RendererChangeEvent event); }
2,009
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ChartChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/ChartChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * ChartChangeListener.java * ------------------------ * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Oct-2002 : Now extends java.util.EventListener (DG); * */ package org.jfree.chart.event; import java.util.EventListener; /** * The interface that must be supported by classes that wish to receive * notification of chart events. * <P> * The {@link org.jfree.chart.ChartPanel} class registers itself with the * chart it displays, and whenever the chart changes, the panel redraws itself. * */ public interface ChartChangeListener extends EventListener { /** * Receives notification of a chart change event. * * @param event the event. */ public void chartChanged(ChartChangeEvent event); }
2,334
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AnnotationChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/AnnotationChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * AnnotationChangeListener.java * ------------------------- * (C) Copyright 2009, by Object Refinery Limited and Contributors. * * Original Author: Peter Kolb (patch 2809117); * Contributor(s): ; * * Changes: * -------- * 20-Jun-2009 : Version 1 (PK); * */ package org.jfree.chart.event; import java.util.EventListener; import org.jfree.chart.annotations.Annotation; /** * The interface that must be supported by classes that wish to receive * notification of changes to an {@link Annotation}. * * @since 1.0.14 */ public interface AnnotationChangeListener extends EventListener { /** * Receives notification of an annotation change event. * * @param event the event. * * @since 1.0.14 */ public void annotationChanged(AnnotationChangeEvent event); }
2,069
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MarkerChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/MarkerChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------- * MarkerChangeEvent.java * ---------------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Sep-2006 : Version 1 (DG); * */ package org.jfree.chart.event; import org.jfree.chart.plot.Marker; /** * An event that can be forwarded to any {@link MarkerChangeListener} to * signal a change to a {@link Marker}. * * @since 1.0.3 */ public class MarkerChangeEvent extends ChartChangeEvent { /** The plot that generated the event. */ private Marker marker; /** * Creates a new <code>MarkerChangeEvent</code> instance. * * @param marker the marker that triggered the event (<code>null</code> * not permitted). * * @since 1.0.3 */ public MarkerChangeEvent(Marker marker) { super(marker); this.marker = marker; } /** * Returns the marker that triggered the event. * * @return The marker that triggered the event (never <code>null</code>). * * @since 1.0.3 */ public Marker getMarker() { return this.marker; } }
2,430
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MarkerChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/MarkerChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * MarkerChangeListener.java * ------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Sep-2006 : Version 1 (DG); * */ package org.jfree.chart.event; import java.util.EventListener; import org.jfree.chart.plot.Marker; /** * The interface that must be supported by classes that wish to receive * notification of changes to a {@link Marker}. * * @since 1.0.3 */ public interface MarkerChangeListener extends EventListener { /** * Receives notification of a marker change event. * * @param event the event. * * @since 1.0.3 */ public void markerChanged(MarkerChangeEvent event); }
2,034
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AxisChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/AxisChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * AxisChangeEvent.java * -------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.chart.event; import org.jfree.chart.axis.Axis; /** * A change event that encapsulates information about a change to an axis. */ public class AxisChangeEvent extends ChartChangeEvent { /** The axis that generated the change event. */ private Axis axis; /** * Creates a new AxisChangeEvent. * * @param axis the axis that generated the event. */ public AxisChangeEvent(Axis axis) { super(axis); this.axis = axis; } /** * Returns the axis that generated the event. * * @return The axis that generated the event. */ public Axis getAxis() { return this.axis; } }
2,335
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
OverlayChangeListener.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/OverlayChangeListener.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * OverlayChangeListener.java * -------------------------- * (C) Copyright 2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 09-Apr-2009 : Version 1 (DG); * */ package org.jfree.chart.event; import java.util.EventListener; import org.jfree.chart.panel.Overlay; /** * A listener for changes to an {@link Overlay}. * * @since 1.0.13 */ public interface OverlayChangeListener extends EventListener { /** * This method is called to notify a listener of a change event. * * @param event the event. */ public void overlayChanged(OverlayChangeEvent event); }
1,955
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ChartChangeEvent.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/event/ChartChangeEvent.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * ChartChangeEvent.java * --------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes (from 24-Aug-2001) * -------------------------- * 24-Aug-2001 : Added standard source header. Fixed DOS encoding problem (DG); * 07-Nov-2001 : Updated header (DG); * Change event type names (DG); * 09-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Feb-2005 : Changed the type from int to ChartChangeEventType (DG); * */ package org.jfree.chart.event; import java.util.EventObject; import org.jfree.chart.JFreeChart; /** * A change event that encapsulates information about a change to a chart. */ public class ChartChangeEvent extends EventObject { /** The type of event. */ private ChartChangeEventType type; /** The chart that generated the event. */ private JFreeChart chart; /** * Creates a new chart change event. * * @param source the source of the event (could be the chart, a title, * an axis etc.) */ public ChartChangeEvent(Object source) { this(source, null, ChartChangeEventType.GENERAL); } /** * Creates a new chart change event. * * @param source the source of the event (could be the chart, a title, an * axis etc.) * @param chart the chart that generated the event. */ public ChartChangeEvent(Object source, JFreeChart chart) { this(source, chart, ChartChangeEventType.GENERAL); } /** * Creates a new chart change event. * * @param source the source of the event (could be the chart, a title, an axis etc.) * @param chart the chart that generated the event. * @param type the type of event. */ public ChartChangeEvent(Object source, JFreeChart chart, ChartChangeEventType type) { super(source); this.chart = chart; this.type = type; } /** * Returns the chart that generated the change event. * * @return The chart that generated the change event. */ public JFreeChart getChart() { return this.chart; } /** * Sets the chart that generated the change event. * * @param chart the chart that generated the event. */ public void setChart(JFreeChart chart) { this.chart = chart; } /** * Returns the event type. * * @return The event type. */ public ChartChangeEventType getType() { return this.type; } /** * Sets the event type. * * @param type the event type. */ public void setType(ChartChangeEventType type) { this.type = type; } }
4,081
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/package-info.java
/** * A range of objects that can be used to represent the needle on a * {@link org.jfree.chart.plot.CompassPlot}. */ package org.jfree.chart.needle;
153
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MeterNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/MeterNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * MeterNeedle.java * ---------------- * (C) Copyright 2002-2012, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * Nicolas Brodu (for Astrium and EADS Corporate Research * Center); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 07-Nov-2002 : Fixed errors reported by Checkstyle (DG); * 01-Sep-2003 : Implemented Serialization (NB); * 16-Mar-2004 : Changed transform from private to protected (BRS); * 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.needle; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.SerialUtilities; /** * The base class used to represent the needle on a * {@link org.jfree.chart.plot.CompassPlot}. */ public abstract class MeterNeedle implements Serializable { /** For serialization. */ private static final long serialVersionUID = 5203064851510951052L; /** The outline paint. */ private transient Paint outlinePaint = Color.BLACK; /** The outline stroke. */ private transient Stroke outlineStroke = new BasicStroke(2); /** The fill paint. */ private transient Paint fillPaint = null; /** The highlight paint. */ private transient Paint highlightPaint = null; /** The size. */ private int size = 5; /** Scalar to aply to locate the rotation x point. */ private double rotateX = 0.5; /** Scalar to aply to locate the rotation y point. */ private double rotateY = 0.5; /** A transform. */ protected static AffineTransform transform = new AffineTransform(); /** * Creates a new needle. */ public MeterNeedle() { this(null, null, null); } /** * Creates a new needle. * * @param outline the outline paint (<code>null</code> permitted). * @param fill the fill paint (<code>null</code> permitted). * @param highlight the highlight paint (<code>null</code> permitted). */ public MeterNeedle(Paint outline, Paint fill, Paint highlight) { this.fillPaint = fill; this.highlightPaint = highlight; this.outlinePaint = outline; } /** * Returns the outline paint. * * @return The outline paint. */ public Paint getOutlinePaint() { return this.outlinePaint; } /** * Sets the outline paint. * * @param p the new paint. */ public void setOutlinePaint(Paint p) { if (p != null) { this.outlinePaint = p; } } /** * Returns the outline stroke. * * @return The outline stroke. */ public Stroke getOutlineStroke() { return this.outlineStroke; } /** * Sets the outline stroke. * * @param s the new stroke. */ public void setOutlineStroke(Stroke s) { if (s != null) { this.outlineStroke = s; } } /** * Returns the fill paint. * * @return The fill paint. */ public Paint getFillPaint() { return this.fillPaint; } /** * Sets the fill paint. * * @param p the fill paint. */ public void setFillPaint(Paint p) { if (p != null) { this.fillPaint = p; } } /** * Returns the highlight paint. * * @return The highlight paint. */ public Paint getHighlightPaint() { return this.highlightPaint; } /** * Sets the highlight paint. * * @param p the highlight paint. */ public void setHighlightPaint(Paint p) { if (p != null) { this.highlightPaint = p; } } /** * Returns the scalar used for determining the rotation x value. * * @return The x rotate scalar. */ public double getRotateX() { return this.rotateX; } /** * Sets the rotateX value. * * @param x the new value. */ public void setRotateX(double x) { this.rotateX = x; } /** * Sets the rotateY value. * * @param y the new value. */ public void setRotateY(double y) { this.rotateY = y; } /** * Returns the scalar used for determining the rotation y value. * * @return The y rotate scalar. */ public double getRotateY() { return this.rotateY; } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. */ public void draw(Graphics2D g2, Rectangle2D plotArea) { draw(g2, plotArea, 0); } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param angle the angle. */ public void draw(Graphics2D g2, Rectangle2D plotArea, double angle) { Point2D.Double pt = new Point2D.Double(); pt.setLocation( plotArea.getMinX() + this.rotateX * plotArea.getWidth(), plotArea.getMinY() + this.rotateY * plotArea.getHeight() ); draw(g2, plotArea, pt, angle); } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Paint savePaint = g2.getColor(); Stroke saveStroke = g2.getStroke(); drawNeedle(g2, plotArea, rotate, Math.toRadians(angle)); g2.setStroke(saveStroke); g2.setPaint(savePaint); } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ protected abstract void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle); /** * Displays a shape. * * @param g2 the graphics device. * @param shape the shape. */ protected void defaultDisplay(Graphics2D g2, Shape shape) { if (this.fillPaint != null) { g2.setPaint(this.fillPaint); g2.fill(shape); } if (this.outlinePaint != null) { g2.setStroke(this.outlineStroke); g2.setPaint(this.outlinePaint); g2.draw(shape); } } /** * Returns the size. * * @return The size. */ public int getSize() { return this.size; } /** * Sets the size. * * @param pixels the new size. */ public void setSize(int pixels) { this.size = pixels; } /** * Returns the transform. * * @return The transform. */ public AffineTransform getTransform() { return MeterNeedle.transform; } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MeterNeedle)) { return false; } MeterNeedle that = (MeterNeedle) obj; if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) { return false; } if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) { return false; } if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) { return false; } if (!PaintUtilities.equal(this.highlightPaint, that.highlightPaint)) { return false; } if (this.size != that.size) { return false; } if (this.rotateX != that.rotateX) { return false; } if (this.rotateY != that.rotateY) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = HashUtilities.hashCode(193, this.fillPaint); result = HashUtilities.hashCode(result, this.highlightPaint); result = HashUtilities.hashCode(result, this.outlinePaint); result = HashUtilities.hashCode(result, this.outlineStroke); result = HashUtilities.hashCode(result, this.rotateX); result = HashUtilities.hashCode(result, this.rotateY); result = HashUtilities.hashCode(result, this.size); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.outlineStroke, stream); SerialUtilities.writePaint(this.outlinePaint, stream); SerialUtilities.writePaint(this.fillPaint, stream); SerialUtilities.writePaint(this.highlightPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.outlineStroke = SerialUtilities.readStroke(stream); this.outlinePaint = SerialUtilities.readPaint(stream); this.fillPaint = SerialUtilities.readPaint(stream); this.highlightPaint = SerialUtilities.readPaint(stream); } }
11,918
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
WindNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/WindNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * WindNeedle.java * --------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 09-Sep-2003 : Added equals() method (DG); * 22-Nov-2007 : Implemented hashCode() (DG) * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle that indicates wind direction, for use with the * {@link org.jfree.chart.plot.CompassPlot} class. */ public class WindNeedle extends ArrowNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2861061368907167834L; /** * Default constructor. */ public WindNeedle() { super(false); // isArrowAtTop } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { super.drawNeedle(g2, plotArea, rotate, angle); if ((rotate != null) && (plotArea != null)) { int spacing = getSize() * 3; Rectangle2D newArea = new Rectangle2D.Double(); Point2D newRotate = rotate; newArea.setRect(plotArea.getMinX() - spacing, plotArea.getMinY(), plotArea.getWidth(), plotArea.getHeight()); super.drawNeedle(g2, newArea, newRotate, angle); newArea.setRect(plotArea.getMinX() + spacing, plotArea.getMinY(), plotArea.getWidth(), plotArea.getHeight()); super.drawNeedle(g2, newArea, newRotate, angle); } } /** * Tests another object for equality with this object. * * @param object the object to test. * * @return A boolean. */ @Override public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } if (super.equals(object) && object instanceof WindNeedle) { return true; } return false; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } }
4,027
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MiddlePinNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/MiddlePinNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * MiddlePinNeedle.java * -------------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle that is drawn as a pin shape. */ public class MiddlePinNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 6237073996403125310L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Area shape; GeneralPath pointer = new GeneralPath(); int minY = (int) (plotArea.getMinY()); //int maxX = (int) (plotArea.getMaxX()); int maxY = (int) (plotArea.getMaxY()); int midY = ((maxY - minY) / 2) + minY; int midX = (int) (plotArea.getMinX() + (plotArea.getWidth() / 2)); //int midY = (int) (plotArea.getMinY() + (plotArea.getHeight() / 2)); int lenX = (int) (plotArea.getWidth() / 10); if (lenX < 2) { lenX = 2; } pointer.moveTo(midX - lenX, midY - lenX); pointer.lineTo(midX + lenX, midY - lenX); pointer.lineTo(midX, minY); pointer.closePath(); lenX = 4 * lenX; Ellipse2D circle = new Ellipse2D.Double(midX - lenX / 2, midY - lenX, lenX, lenX); shape = new Area(circle); shape.add(new Area(pointer)); if ((rotate != null) && (angle != 0)) { /// we have rotation getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); shape.transform(getTransform()); } defaultDisplay(g2, shape); } /** * Tests another object for equality with this object. * * @param object the object to test. * * @return A boolean. */ @Override public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } if (super.equals(object) && object instanceof MiddlePinNeedle) { return true; } return false; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>MiddlePinNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
4,887
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ShipNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/ShipNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * ShipNeedle.java * --------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle in the shape of a ship, for use with the * {@link org.jfree.chart.plot.CompassPlot} class. */ public class ShipNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 149554868169435612L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { GeneralPath shape = new GeneralPath(); shape.append(new Arc2D.Double(-9.0, -7.0, 10, 14, 0.0, 25.5, Arc2D.OPEN), true); shape.append(new Arc2D.Double(0.0, -7.0, 10, 14, 154.5, 25.5, Arc2D.OPEN), true); shape.closePath(); getTransform().setToTranslation(plotArea.getMinX(), plotArea.getMaxY()); getTransform().scale(plotArea.getWidth(), plotArea.getHeight() / 3); shape.transform(getTransform()); if ((rotate != null) && (angle != 0)) { /// we have rotation getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); shape.transform(getTransform()); } defaultDisplay(g2, shape); } /** * Tests another object for equality with this object. * * @param object the object to test. * * @return A boolean. */ @Override public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } if (super.equals(object) && object instanceof ShipNeedle) { return true; } return false; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>ShipNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
4,440
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PlumNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/PlumNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * PlumNeedle.java * --------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle for use with the {@link org.jfree.chart.plot.CompassPlot} class. */ public class PlumNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3082660488660600718L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Arc2D shape = new Arc2D.Double(Arc2D.PIE); double radius = plotArea.getHeight(); double halfX = plotArea.getWidth() / 2; double diameter = 2 * radius; shape.setFrame(plotArea.getMinX() + halfX - radius , plotArea.getMinY() - radius, diameter, diameter); radius = Math.toDegrees(Math.asin(halfX / radius)); shape.setAngleStart(270 - radius); shape.setAngleExtent(2 * radius); Area s = new Area(shape); if ((rotate != null) && (angle != 0)) { /// we have rotation houston, please spin me getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); s.transform(getTransform()); } defaultDisplay(g2, s); } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PlumNeedle)) { return false; } if (!super.equals(obj)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>PlumNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
4,461
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ArrowNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/ArrowNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * ArrowNeedle.java * ---------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Added hashCode() implementation (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.HashUtilities; /** * A needle in the shape of an arrow. */ public class ArrowNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -5334056511213782357L; /** * A flag controlling whether or not there is an arrow at the top of the * needle. */ private boolean isArrowAtTop = true; /** * Constructs a new arrow needle. * * @param isArrowAtTop a flag that controls whether or not there is an * arrow at the top of the needle. */ public ArrowNeedle(boolean isArrowAtTop) { this.isArrowAtTop = isArrowAtTop; } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Line2D shape = new Line2D.Float(); Shape d = null; float x = (float) (plotArea.getMinX() + (plotArea.getWidth() / 2)); float minY = (float) plotArea.getMinY(); float maxY = (float) plotArea.getMaxY(); shape.setLine(x, minY, x, maxY); GeneralPath shape1 = new GeneralPath(); if (this.isArrowAtTop) { shape1.moveTo(x, minY); minY += 4 * getSize(); } else { shape1.moveTo(x, maxY); minY = maxY - 4 * getSize(); } shape1.lineTo(x + getSize(), minY); shape1.lineTo(x - getSize(), minY); shape1.closePath(); if ((rotate != null) && (angle != 0)) { getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); d = getTransform().createTransformedShape(shape); } else { d = shape; } defaultDisplay(g2, d); if ((rotate != null) && (angle != 0)) { d = getTransform().createTransformedShape(shape1); } else { d = shape1; } defaultDisplay(g2, d); } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ArrowNeedle)) { return false; } if (!super.equals(obj)) { return false; } ArrowNeedle that = (ArrowNeedle) obj; if (this.isArrowAtTop != that.isArrowAtTop) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = super.hashCode(); result = HashUtilities.hashCode(result, this.isArrowAtTop); return result; } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>ArrowNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
5,542
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PointerNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/PointerNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * PointerNeedle.java * ------------------ * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle in the shape of a pointer, for use with the * {@link org.jfree.chart.plot.CompassPlot} class. */ public class PointerNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4744677345334729606L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { GeneralPath shape1 = new GeneralPath(); GeneralPath shape2 = new GeneralPath(); float minX = (float) plotArea.getMinX(); float minY = (float) plotArea.getMinY(); float maxX = (float) plotArea.getMaxX(); float maxY = (float) plotArea.getMaxY(); float midX = (float) (minX + (plotArea.getWidth() / 2)); float midY = (float) (minY + (plotArea.getHeight() / 2)); shape1.moveTo(minX, midY); shape1.lineTo(midX, minY); shape1.lineTo(maxX, midY); shape1.closePath(); shape2.moveTo(minX, midY); shape2.lineTo(midX, maxY); shape2.lineTo(maxX, midY); shape2.closePath(); if ((rotate != null) && (angle != 0)) { /// we have rotation huston, please spin me getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); shape1.transform(getTransform()); shape2.transform(getTransform()); } if (getFillPaint() != null) { g2.setPaint(getFillPaint()); g2.fill(shape1); } if (getHighlightPaint() != null) { g2.setPaint(getHighlightPaint()); g2.fill(shape2); } if (getOutlinePaint() != null) { g2.setStroke(getOutlineStroke()); g2.setPaint(getOutlinePaint()); g2.draw(shape1); g2.draw(shape2); } } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PointerNeedle)) { return false; } if (!super.equals(obj)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>PointerNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
5,127
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PinNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/PinNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * PinNeedle.java * -------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle that is drawn as a pin shape. */ public class PinNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3787089953079863373L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Area shape; GeneralPath pointer = new GeneralPath(); int minY = (int) (plotArea.getMinY()); //int maxX = (int) (plotArea.getMaxX()); int maxY = (int) (plotArea.getMaxY()); int midX = (int) (plotArea.getMinX() + (plotArea.getWidth() / 2)); //int midY = (int) (plotArea.getMinY() + (plotArea.getHeight() / 2)); int lenX = (int) (plotArea.getWidth() / 10); if (lenX < 2) { lenX = 2; } pointer.moveTo(midX - lenX, maxY - lenX); pointer.lineTo(midX + lenX, maxY - lenX); pointer.lineTo(midX, minY + lenX); pointer.closePath(); lenX = 4 * lenX; Ellipse2D circle = new Ellipse2D.Double(midX - lenX / 2, plotArea.getMaxY() - lenX, lenX, lenX); shape = new Area(circle); shape.add(new Area(pointer)); if ((rotate != null) && (angle != 0)) { /// we have rotation getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); shape.transform(getTransform()); } defaultDisplay(g2, shape); } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PinNeedle)) { return false; } if (!super.equals(obj)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>PinNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
4,788
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LineNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/LineNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * LineNeedle.java * --------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 08-Jun-2005 : Implemented Cloneable (DG); * 22-Nov-2007 : Added hashCode() implementation (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle that is represented by a line. */ public class LineNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 6215321387896748945L; /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { Line2D shape = new Line2D.Double(); double x = plotArea.getMinX() + (plotArea.getWidth() / 2); shape.setLine(x, plotArea.getMinY(), x, plotArea.getMaxY()); Shape s = shape; if ((rotate != null) && (angle != 0)) { /// we have rotation getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); s = getTransform().createTransformedShape(s); } defaultDisplay(g2, s); } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LineNeedle)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>LineNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
4,057
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LongNeedle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/needle/LongNeedle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * LongNeedle.java * --------------- * (C) Copyright 2002-2008, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 09-Sep-2003 : Added equals() method (DG); * 16-Mar-2004 : Implemented Rotation; * 22-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.needle; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A needle that is represented by a long line. */ public class LongNeedle extends MeterNeedle implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4319985779783688159L; /** * Default constructor. */ public LongNeedle() { super(); setRotateY(0.8); } /** * Draws the needle. * * @param g2 the graphics device. * @param plotArea the plot area. * @param rotate the rotation point. * @param angle the angle. */ @Override protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea, Point2D rotate, double angle) { GeneralPath shape1 = new GeneralPath(); GeneralPath shape2 = new GeneralPath(); GeneralPath shape3 = new GeneralPath(); float minX = (float) plotArea.getMinX(); float minY = (float) plotArea.getMinY(); float maxX = (float) plotArea.getMaxX(); float maxY = (float) plotArea.getMaxY(); //float midX = (float) (minX + (plotArea.getWidth() * getRotateX())); //float midY = (float) (minY + (plotArea.getHeight() * getRotateY())); float midX = (float) (minX + (plotArea.getWidth() * 0.5)); float midY = (float) (minY + (plotArea.getHeight() * 0.8)); float y = maxY - (2 * (maxY - midY)); if (y < minY) { y = minY; } shape1.moveTo(minX, midY); shape1.lineTo(midX, minY); shape1.lineTo(midX, y); shape1.closePath(); shape2.moveTo(maxX, midY); shape2.lineTo(midX, minY); shape2.lineTo(midX, y); shape2.closePath(); shape3.moveTo(minX, midY); shape3.lineTo(midX, maxY); shape3.lineTo(maxX, midY); shape3.lineTo(midX, y); shape3.closePath(); Shape s1 = shape1; Shape s2 = shape2; Shape s3 = shape3; if ((rotate != null) && (angle != 0)) { /// we have rotation huston, please spin me getTransform().setToRotation(angle, rotate.getX(), rotate.getY()); s1 = shape1.createTransformedShape(transform); s2 = shape2.createTransformedShape(transform); s3 = shape3.createTransformedShape(transform); } if (getHighlightPaint() != null) { g2.setPaint(getHighlightPaint()); g2.fill(s3); } if (getFillPaint() != null) { g2.setPaint(getFillPaint()); g2.fill(s1); g2.fill(s2); } if (getOutlinePaint() != null) { g2.setStroke(getOutlineStroke()); g2.setPaint(getOutlinePaint()); g2.draw(s1); g2.draw(s2); g2.draw(s3); } } /** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LongNeedle)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Returns a clone of this needle. * * @return A clone. * * @throws CloneNotSupportedException if the <code>LongNeedle</code> * cannot be cloned (in theory, this should not happen). */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
5,800
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ESP32FS.java
/FileExtraction/Java_unseen/me-no-dev_arduino-esp32fs-plugin/src/ESP32FS.java
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Tool to put the contents of the sketch's "data" subfolder into an SPIFFS partition image and upload it to an ESP32 MCU Copyright (c) 2015 Hristo Gochkov (hristo at espressif dot com) This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.esp32.mkspiffs; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; import processing.app.PreferencesData; import processing.app.Editor; import processing.app.Base; import processing.app.BaseNoGui; import processing.app.Platform; import processing.app.Sketch; import processing.app.tools.Tool; import processing.app.helpers.ProcessUtils; import processing.app.debug.TargetPlatform; import org.apache.commons.codec.digest.DigestUtils; import processing.app.helpers.FileUtils; import cc.arduino.files.DeleteFilesOnShutdown; /** * Example Tools menu entry. */ public class ESP32FS implements Tool { Editor editor; public void init(Editor editor) { this.editor = editor; } public String getMenuTitle() { return "ESP32 Sketch Data Upload"; } private int listenOnProcess(String[] arguments){ try { final Process p = ProcessUtils.exec(arguments); Thread thread = new Thread() { public void run() { try { InputStreamReader reader = new InputStreamReader(p.getInputStream()); int c; while ((c = reader.read()) != -1) System.out.print((char) c); reader.close(); reader = new InputStreamReader(p.getErrorStream()); while ((c = reader.read()) != -1) System.err.print((char) c); reader.close(); } catch (Exception e){} } }; thread.start(); int res = p.waitFor(); thread.join(); return res; } catch (Exception e){ return -1; } } private void sysExec(final String[] arguments){ Thread thread = new Thread() { public void run() { try { if(listenOnProcess(arguments) != 0){ editor.statusError("SPIFFS Upload failed!"); } else { editor.statusNotice("SPIFFS Image Uploaded"); } } catch (Exception e){ editor.statusError("SPIFFS Upload failed!"); } } }; thread.start(); } private String getBuildFolderPath(Sketch s) { // first of all try the getBuildPath() function introduced with IDE 1.6.12 // see commit arduino/Arduino#fd1541eb47d589f9b9ea7e558018a8cf49bb6d03 try { String buildpath = s.getBuildPath().getAbsolutePath(); return buildpath; } catch (IOException er) { editor.statusError(er); } catch (Exception er) { try { File buildFolder = FileUtils.createTempFolder("build", DigestUtils.md5Hex(s.getMainFilePath()) + ".tmp"); return buildFolder.getAbsolutePath(); } catch (IOException e) { editor.statusError(e); } catch (Exception e) { // Arduino 1.6.5 doesn't have FileUtils.createTempFolder // String buildPath = BaseNoGui.getBuildFolder().getAbsolutePath(); java.lang.reflect.Method method; try { method = BaseNoGui.class.getMethod("getBuildFolder"); File f = (File) method.invoke(null); return f.getAbsolutePath(); } catch (SecurityException ex) { editor.statusError(ex); } catch (IllegalAccessException ex) { editor.statusError(ex); } catch (InvocationTargetException ex) { editor.statusError(ex); } catch (NoSuchMethodException ex) { editor.statusError(ex); } } } return ""; } private long parseInt(String value){ if(value.startsWith("0x")) return Long.parseLong(value.substring(2), 16); else return Integer.parseInt(value); } private long getIntPref(String name){ String data = BaseNoGui.getBoardPreferences().get(name); if(data == null || data.contentEquals("")) return 0; return parseInt(data); } private void createAndUpload(){ long spiStart = 0, spiSize = 0, spiPage = 256, spiBlock = 4096; String partitions = ""; if(!PreferencesData.get("target_platform").contentEquals("esp32")){ System.err.println(); editor.statusError("SPIFFS Not Supported on "+PreferencesData.get("target_platform")); return; } TargetPlatform platform = BaseNoGui.getTargetPlatform(); String toolExtension = ".py"; if(PreferencesData.get("runtime.os").contentEquals("windows")) { toolExtension = ".exe"; } else if(PreferencesData.get("runtime.os").contentEquals("macosx")) { toolExtension = ""; } String pythonCmd; if(PreferencesData.get("runtime.os").contentEquals("windows")) pythonCmd = "python.exe"; else pythonCmd = "python"; String mkspiffsCmd; if(PreferencesData.get("runtime.os").contentEquals("windows")) mkspiffsCmd = "mkspiffs.exe"; else mkspiffsCmd = "mkspiffs"; String espotaCmd = "espota.py"; if(PreferencesData.get("runtime.os").contentEquals("windows")) espotaCmd = "espota.exe"; Boolean isNetwork = false; File espota = new File(platform.getFolder()+"/tools"); File esptool = new File(platform.getFolder()+"/tools"); String serialPort = PreferencesData.get("serial.port"); if(!BaseNoGui.getBoardPreferences().containsKey("build.partitions")){ System.err.println(); editor.statusError("Partitions Not Defined for "+BaseNoGui.getBoardPreferences().get("name")); return; } try { partitions = BaseNoGui.getBoardPreferences().get("build.partitions"); if(partitions == null || partitions.contentEquals("")){ editor.statusError("Partitions Not Found for "+BaseNoGui.getBoardPreferences().get("name")); return; } } catch(Exception e){ editor.statusError(e); return; } File partitionsFile = new File(platform.getFolder() + "/tools/partitions", partitions + ".csv"); if (!partitionsFile.exists() || !partitionsFile.isFile()) { System.err.println(); editor.statusError("SPIFFS Error: partitions file " + partitions + ".csv not found!"); return; } try { BufferedReader partitionsReader = new BufferedReader(new FileReader(partitionsFile)); String partitionsLine = ""; while ((partitionsLine = partitionsReader.readLine()) != null) { if(partitionsLine.contains("spiffs")) { partitionsLine = partitionsLine.substring(partitionsLine.indexOf(",")+1); partitionsLine = partitionsLine.substring(partitionsLine.indexOf(",")+1); partitionsLine = partitionsLine.substring(partitionsLine.indexOf(",")+1); while(partitionsLine.startsWith(" ")) partitionsLine = partitionsLine.substring(1); String pStart = partitionsLine.substring(0, partitionsLine.indexOf(",")); partitionsLine = partitionsLine.substring(partitionsLine.indexOf(",")+1); while(partitionsLine.startsWith(" ")) partitionsLine = partitionsLine.substring(1); String pSize = partitionsLine.substring(0, partitionsLine.indexOf(",")); spiStart = parseInt(pStart); spiSize = parseInt(pSize); } } if(spiSize == 0){ System.err.println(); editor.statusError("SPIFFS Error: partition size could not be found!"); return; } } catch(Exception e){ editor.statusError(e); return; } File tool = new File(platform.getFolder() + "/tools", mkspiffsCmd); if (!tool.exists() || !tool.isFile()) { tool = new File(platform.getFolder() + "/tools/mkspiffs", mkspiffsCmd); if (!tool.exists()) { tool = new File(PreferencesData.get("runtime.tools.mkspiffs.path"), mkspiffsCmd); if (!tool.exists()) { System.err.println(); editor.statusError("SPIFFS Error: mkspiffs not found!"); return; } } } //make sure the serial port or IP is defined if (serialPort == null || serialPort.isEmpty()) { System.err.println(); editor.statusError("SPIFFS Error: serial port not defined!"); return; } //find espota if IP else find esptool if(serialPort.split("\\.").length == 4){ isNetwork = true; espota = new File(platform.getFolder()+"/tools", espotaCmd); if(!espota.exists() || !espota.isFile()){ System.err.println(); editor.statusError("SPIFFS Error: espota not found!"); return; } } else { String esptoolCmd = "esptool"+toolExtension; esptool = new File(platform.getFolder()+"/tools", esptoolCmd); if(!esptool.exists() || !esptool.isFile()){ esptool = new File(platform.getFolder()+"/tools/esptool_py", esptoolCmd); if(!esptool.exists()){ esptool = new File(PreferencesData.get("runtime.tools.esptool_py.path"), esptoolCmd); if (!esptool.exists()) { System.err.println(); editor.statusError("SPIFFS Error: esptool not found!"); return; } } } } //load a list of all files int fileCount = 0; File dataFolder = new File(editor.getSketch().getFolder(), "data"); if (!dataFolder.exists()) { dataFolder.mkdirs(); } if(dataFolder.exists() && dataFolder.isDirectory()){ File[] files = dataFolder.listFiles(); if(files.length > 0){ for(File file : files){ if((file.isDirectory() || file.isFile()) && !file.getName().startsWith(".")) fileCount++; } } } String dataPath = dataFolder.getAbsolutePath(); String toolPath = tool.getAbsolutePath(); String sketchName = editor.getSketch().getName(); String imagePath = getBuildFolderPath(editor.getSketch()) + "/" + sketchName + ".spiffs.bin"; String uploadSpeed = BaseNoGui.getBoardPreferences().get("upload.speed"); Object[] options = { "Yes", "No" }; String title = "SPIFFS Create"; String message = "No files have been found in your data folder!\nAre you sure you want to create an empty SPIFFS image?"; if(fileCount == 0 && JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]) != JOptionPane.YES_OPTION){ System.err.println(); editor.statusError("SPIFFS Warning: mkspiffs canceled!"); return; } editor.statusNotice("SPIFFS Creating Image..."); System.out.println("[SPIFFS] data : "+dataPath); System.out.println("[SPIFFS] start : "+spiStart); System.out.println("[SPIFFS] size : "+(spiSize/1024)); System.out.println("[SPIFFS] page : "+spiPage); System.out.println("[SPIFFS] block : "+spiBlock); try { if(listenOnProcess(new String[]{toolPath, "-c", dataPath, "-p", spiPage+"", "-b", spiBlock+"", "-s", spiSize+"", imagePath}) != 0){ System.err.println(); editor.statusError("SPIFFS Create Failed!"); return; } } catch (Exception e){ editor.statusError(e); editor.statusError("SPIFFS Create Failed!"); return; } editor.statusNotice("SPIFFS Uploading Image..."); System.out.println("[SPIFFS] upload : "+imagePath); if(isNetwork){ System.out.println("[SPIFFS] IP : "+serialPort); System.out.println(); if(espota.getAbsolutePath().endsWith(".py")) sysExec(new String[]{pythonCmd, espota.getAbsolutePath(), "-i", serialPort, "-p", "3232", "-s", "-f", imagePath}); else sysExec(new String[]{espota.getAbsolutePath(), "-i", serialPort, "-p", "3232", "-s", "-f", imagePath}); } else { String mcu = BaseNoGui.getBoardPreferences().get("build.mcu"); String flashMode = BaseNoGui.getBoardPreferences().get("build.flash_mode"); String flashFreq = BaseNoGui.getBoardPreferences().get("build.flash_freq"); System.out.println("[SPIFFS] address: "+spiStart); System.out.println("[SPIFFS] port : "+serialPort); System.out.println("[SPIFFS] speed : "+uploadSpeed); System.out.println("[SPIFFS] mode : "+flashMode); System.out.println("[SPIFFS] freq : "+flashFreq); System.out.println(); if(esptool.getAbsolutePath().endsWith(".py")) sysExec(new String[]{pythonCmd, esptool.getAbsolutePath(), "--chip", mcu, "--baud", uploadSpeed, "--port", serialPort, "--before", "default_reset", "--after", "hard_reset", "write_flash", "-z", "--flash_mode", flashMode, "--flash_freq", flashFreq, "--flash_size", "detect", ""+spiStart, imagePath}); else sysExec(new String[]{esptool.getAbsolutePath(), "--chip", mcu, "--baud", uploadSpeed, "--port", serialPort, "--before", "default_reset", "--after", "hard_reset", "write_flash", "-z", "--flash_mode", flashMode, "--flash_freq", flashFreq, "--flash_size", "detect", ""+spiStart, imagePath}); } } public void run() { createAndUpload(); } }
14,428
Java
.java
me-no-dev/arduino-esp32fs-plugin
527
142
35
2017-09-30T10:59:34Z
2023-09-20T17:54:26Z
AnnotationTab.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/AnnotationTab.java
/* * AnnotationTab.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.main; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.widget.SwitchCompat; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import hcm.ssj.core.Annotation; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.core.event.Event; import hcm.ssj.core.event.StringEvent; import hcm.ssj.creator.R; import hcm.ssj.creator.core.BandComm; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.util.Util; /** * Annotation tab for main activity.<br> * Created by Frank Gaibler on 23.09.2016. */ public class AnnotationTab implements ITab { private Activity activity = null; //tab private View view; private String title; private int icon; //annotation private double curAnnoStartTime = 0; private FloatingActionButton floatingActionButton = null; private EditText editTextPathAnno = null; private EditText editTextNameAnno = null; private LinearLayout annoClassList = null; private boolean running = false; private BandComm bandComm; private int annoWithBand = -1; private CheckBox externalAnno = null; private Annotation anno = null; /** * @param activity Activity */ AnnotationTab(Activity activity) { this.activity = activity; anno = PipelineBuilder.getInstance().getAnnotation(); view = createContent(activity); title = activity.getResources().getString(R.string.str_annotation); icon = android.R.drawable.ic_menu_agenda; bandComm = new BandComm(activity); } /** * @param context Context */ private View createContent(final Context context) { //layouts LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, ScrollView.LayoutParams.MATCH_PARENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); // ScrollView scrollViewAnno = new ScrollView(context); scrollViewAnno.setLayoutParams(new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT)); scrollViewAnno.addView(linearLayout); // CoordinatorLayout coordinatorLayout = new CoordinatorLayout(context); coordinatorLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); coordinatorLayout.addView(scrollViewAnno); //add annotation button floatingActionButton = new FloatingActionButton(context); floatingActionButton.setImageResource(R.drawable.ic_add_white_24dp); CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams( CoordinatorLayout.LayoutParams.WRAP_CONTENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.BOTTOM | Gravity.END; int dpValue = 12; // margin in dips float d = context.getResources().getDisplayMetrics().density; int margin = (int) (dpValue * d); // margin in pixels params.setMargins(0, 0, margin, margin); floatingActionButton.setLayoutParams(params); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (annoClassList != null) { int id = annoClassList.getChildCount(); String name = context.getString(R.string.str_defaultAnno, id); annoClassList.addView(createClassSwitch(context, name)); anno.addClass(id, name); } } }); coordinatorLayout.addView(floatingActionButton); //file name TextView textViewDescriptionName = new TextView(context); textViewDescriptionName.setText(R.string.str_fileName); textViewDescriptionName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); linearLayout.addView(textViewDescriptionName); editTextNameAnno = new EditText(context); editTextNameAnno.setInputType(InputType.TYPE_CLASS_TEXT); editTextNameAnno.setText(anno.getFileName(), TextView.BufferType.NORMAL); editTextNameAnno.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { anno.setFileName(s.toString().trim()); } }); linearLayout.addView(editTextNameAnno); //file path TextView textViewDescriptionPath = new TextView(context); textViewDescriptionPath.setText(R.string.str_filePath); textViewDescriptionPath.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); linearLayout.addView(textViewDescriptionPath); editTextPathAnno = new EditText(context); editTextPathAnno.setInputType(InputType.TYPE_CLASS_TEXT); editTextPathAnno.setText(anno.getFilePath(), TextView.BufferType.NORMAL); editTextPathAnno.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { anno.setFilePath(s.toString().trim()); } }); linearLayout.addView(editTextPathAnno); //other options externalAnno = new CheckBox(context); externalAnno.setText(R.string.anno_msband); externalAnno.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { bandComm.create(); annoWithBand = 0; //associate with first element in anno list } else { bandComm.destroy(); annoWithBand = -1; } } }); linearLayout.addView(externalAnno); //annotations dpValue = 12; // margin in dips d = context.getResources().getDisplayMetrics().density; margin = (int) (dpValue * d); // margin in pixels annoClassList = new LinearLayout(context); setAnnoClasses(anno.getClassArray()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(margin, margin, margin, 0); annoClassList.setLayoutParams(lp); annoClassList.setOrientation(LinearLayout.VERTICAL); annoClassList.setGravity(Gravity.CENTER_HORIZONTAL); linearLayout.addView(annoClassList); return coordinatorLayout; } /** * @param context Context * @return CompoundButton */ private LinearLayout createClassSwitch(final Context context, String name) { LinearLayout layout = new LinearLayout(context); layout.setBackgroundColor(Color.parseColor("#EEEEEE")); int dpValue = 8; // margin in dips float d = context.getResources().getDisplayMetrics().density; int margin = (int) (dpValue * d); // margin in pixels LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(margin, margin, margin, 0); layout.setLayoutParams(params); TextView textView = new TextView(context); textView.setText(name); textView.setTextSize(textView.getTextSize() * 0.5f); layout.addView(textView); LinearLayout buttonLayout = new LinearLayout(context); buttonLayout.setGravity(Gravity.CENTER_VERTICAL | Gravity.END); LinearLayout.LayoutParams paramsBtn = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); paramsBtn.gravity = Gravity.END; // paramsBtn.height = LinearLayout.LayoutParams.WRAP_CONTENT; // paramsBtn.width = LinearLayout.LayoutParams.WRAP_CONTENT; buttonLayout.setLayoutParams(paramsBtn); SwitchCompat switchButton = new SwitchCompat(context); switchButton.setEnabled(false); buttonLayout.addView(switchButton); layout.addView(buttonLayout); switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { double time = Util.getAnnotationTime(); if (isChecked) { for (int i = 0; i < annoClassList.getChildCount(); i++) { SwitchCompat button = (SwitchCompat) ((LinearLayout)((LinearLayout)(annoClassList.getChildAt(i))).getChildAt(1)).getChildAt(0); if (button != buttonView) { button.setChecked(false); } } } //only modify anno when pipeline is running if (Pipeline.getInstance().isRunning()) { String name = ((TextView) (((ViewGroup) (buttonView.getParent().getParent())).getChildAt(0))).getText().toString(); if (isChecked) { curAnnoStartTime = time; //create start event StringEvent ev = new StringEvent(name); ev.time = (long)(time * 1000); ev.dur = 0; ev.state = Event.State.CONTINUED; anno.getChannel().pushEvent(ev); } else { anno.addEntry(name, curAnnoStartTime, time); //create end event StringEvent ev = new StringEvent(name); ev.time = (long)(curAnnoStartTime * 1000); ev.dur = (int)((time - curAnnoStartTime) * 1000); ev.state = Event.State.COMPLETED; anno.getChannel().pushEvent(ev); curAnnoStartTime = 0; } } } }); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { //only allow edits while pipe is not active if (!running) { //content LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); final EditText editText = new EditText(context); editText.setInputType(InputType.TYPE_CLASS_TEXT); editText.setText(((TextView) v).getText(), TextView.BufferType.NORMAL); linearLayout.addView(editText); //dialog AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.str_annotation); builder.setView(linearLayout); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String name = editText.getText().toString().trim(); ((TextView) v).setText(name); anno.setClasses(getAnnoClassesFromView()); } }); builder.setNegativeButton(R.string.str_cancel, null); builder.setNeutralButton(R.string.str_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ViewGroup viewGroup = (ViewGroup) v.getParent(); if (viewGroup != null) { ((SwitchCompat)((LinearLayout) viewGroup.getChildAt(1)).getChildAt(0)).setChecked(false); anno.removeClass(((TextView) viewGroup.getChildAt(0)).getText().toString()); ((ViewGroup) viewGroup.getParent()).removeView(viewGroup); } v.invalidate(); } }); AlertDialog alert = builder.create(); alert.show(); } } }); return layout; } /** * */ void startAnnotation() { syncWithModel(); enableComponents(false); running = true; activity.runOnUiThread(new Runnable() { @Override public void run() { //activate buttons for (int i = 0; i < annoClassList.getChildCount(); i++) { SwitchCompat button = (SwitchCompat) ((LinearLayout)((LinearLayout)(annoClassList.getChildAt(i))).getChildAt(1)).getChildAt(0); button.setEnabled(true); } } }); } /** * */ void finishAnnotation() { try { if(anno != null) anno.save(); } catch (IOException | XmlPullParserException e) { Log.e("unnable to save annotation file", e); } activity.runOnUiThread(new Runnable() { @Override public void run() { for (int i = 0; i < annoClassList.getChildCount(); i++) { SwitchCompat button = (SwitchCompat) ((LinearLayout)((LinearLayout)(annoClassList.getChildAt(i))).getChildAt(1)).getChildAt(0); button.setChecked(false); button.setEnabled(false); } } }); //wait for buttons to "uncheck" try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } running = false; enableComponents(true); } /** * @param enable boolean */ private void enableComponents(final boolean enable) { if (floatingActionButton != null) { floatingActionButton.post(new Runnable() { public void run() { floatingActionButton.setVisibility(enable ? View.VISIBLE : View.INVISIBLE); floatingActionButton.setEnabled(enable); } }); } if (editTextPathAnno != null) { editTextPathAnno.post(new Runnable() { public void run() { editTextPathAnno.setEnabled(enable); } }); } if (editTextNameAnno != null) { editTextNameAnno.post(new Runnable() { public void run() { editTextNameAnno.setEnabled(enable); } }); } } /** * @return View */ @Override public View getView() { return view; } /** * @return String */ @Override public String getTitle() { return title; } /** * @return int */ @Override public int getIcon() { return icon; } /** * @return int */ public int getBandAnnoButton() { return annoWithBand; } /** * @param id int * @param value boolean * @return boolean */ public boolean toggleAnnoButton(int id, final boolean value) { if (annoClassList == null || activity == null || !running) { return false; } final LinearLayout anno = (LinearLayout) annoClassList.getChildAt(id); if (anno == null) { return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { SwitchCompat button = (SwitchCompat) ((LinearLayout)anno.getChildAt(1)).getChildAt(0); if (button.isEnabled()) button.setChecked(value); } }); return true; } public String[] getAnnoClassesFromView() { if (annoClassList == null) return null; String[] classes = new String[annoClassList.getChildCount()]; for(int i = 0; i < annoClassList.getChildCount(); i++) { LinearLayout anno = (LinearLayout) annoClassList.getChildAt(i); classes[i] = ((TextView) anno.getChildAt(0)).getText().toString(); } return classes; } public void setAnnoClasses(String[] classes) { if (annoClassList == null) return; //clear existing annotations annoClassList.removeAllViews(); for (String aClass : classes) { annoClassList.addView(createClassSwitch(activity, aClass)); } } public void syncWithModel() { activity.runOnUiThread(new Runnable() { @Override public void run() { setAnnoClasses(anno.getClassArray()); if (editTextPathAnno != null) { editTextPathAnno.setText(anno.getFilePath()); } if (editTextNameAnno != null) { editTextNameAnno.setText(anno.getFileName()); } } }); } }
20,903
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Console.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/Console.java
/* * Console.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.main; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.creator.R; import hcm.ssj.file.FileCons; /** * Console tab for main activity.<br> * Created by Frank Gaibler on 23.09.2016. */ class Console implements ITab { //tab private View view; private String title; private int icon; //console private TextView textViewConsole = null; private String strLogMsg = ""; private boolean handleLogMessages = false; private Thread threadLog = new Thread() { private final int sleepTime = 100; private Handler handlerLog = new Handler(Looper.getMainLooper()); private Runnable runnableLog = new Runnable() { public void run() { if (textViewConsole != null) { textViewConsole.setText(strLogMsg); } } }; @Override public void run() { while (handleLogMessages) { try { handlerLog.post(runnableLog); Thread.sleep(sleepTime); // Scroll to the bottom if it was on bottom before posting the new message if(view instanceof ConsoleScrollView && ((ConsoleScrollView)view).lockScroll) { ((ScrollView) view).fullScroll(ScrollView.FOCUS_DOWN); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } }; private Log.LogListener logListener = new Log.LogListener() { private String[] tags = {"0", "1", "V", "D", "I", "W", "E", "A"}; private final int max = 10000; private final int interim = max / 2; /** * @param msg String */ public void msg(int type, String msg) { strLogMsg += (type > 0 && type < tags.length ? tags[type] : type) + "/" + Cons.LOGTAG + ": " + msg + FileCons.DELIMITER_LINE; int length = strLogMsg.length(); if (length > max) { strLogMsg = strLogMsg.substring(length - interim); strLogMsg = strLogMsg.substring(strLogMsg.indexOf(FileCons.DELIMITER_LINE) + FileCons.DELIMITER_LINE.length()); } } }; private class ConsoleScrollView extends ScrollView { public boolean isBottom = false; public boolean lockScroll = false; public ConsoleScrollView(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent ev) { boolean ret = super.onTouchEvent(ev); if(ev.getActionMasked() == MotionEvent.ACTION_MOVE && isBottom) { lockScroll = true; } else if(ev.getActionMasked() == MotionEvent.ACTION_MOVE && !isBottom) { lockScroll = false; } return ret; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { // Grab the last child placed in the ScrollView, we need it to determinate the bottom position. View view = getChildAt(0); // Calculate the scrolldiff int diff = (view.getBottom()-(getHeight()+getScrollY())); // if diff is zero, then the bottom has been reached if( diff <= 0 ) { // notify that we have reached the bottom isBottom = true; } else { isBottom = false; } super.onScrollChanged(l, t, oldl, oldt); } } /** * @param context Context */ Console(Context context) { //view textViewConsole = new TextView(context); ConsoleScrollView scrollView = new ConsoleScrollView(context); scrollView.setFillViewport(true); scrollView.addView(textViewConsole); view = scrollView; //title title = context.getResources().getString(R.string.str_console); //icon icon = android.R.drawable.ic_menu_recent_history; } /** * */ void clear() { strLogMsg = ""; } /** * */ void cleanUp() { handleLogMessages = false; Log.removeLogListener(logListener); } /** * */ void init() { Log.addLogListener(logListener); handleLogMessages = true; threadLog.start(); } /** * @return View */ @Override public View getView() { return view; } /** * @return String */ @Override public String getTitle() { return title; } /** * @return int */ @Override public int getIcon() { return icon; } }
6,595
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
TabHandler.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/TabHandler.java
/* * TabHandler.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.main; import android.app.Activity; import androidx.core.content.ContextCompat; import android.view.SurfaceView; import android.view.View; import android.widget.TabHost; import android.widget.TableLayout; import com.jjoe64.graphview.GraphView; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import hcm.ssj.camera.CameraPainter; import hcm.ssj.core.Component; import hcm.ssj.creator.R; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.util.Util; import hcm.ssj.creator.view.PipeListener; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.feedback.VisualFeedback; import hcm.ssj.file.IFileWriter; import hcm.ssj.landmark.LandmarkPainter; import hcm.ssj.graphic.GridPainter; import hcm.ssj.graphic.SignalPainter; import hcm.ssj.ml.Trainer; public class TabHandler { private Activity activity; //tabs private TabHost tabHost = null; private LinkedHashMap<ITab, TabHost.TabSpec> firstTabs = new LinkedHashMap<>(); private LinkedHashMap<Component, TabHost.TabSpec> additionalTabs = new LinkedHashMap<>(); private Canvas canvas; private Console console; public TabHandler(Activity activity) { this.activity = activity; tabHost = (TabHost) activity.findViewById(R.id.id_tabHost); if (tabHost != null) { tabHost.setup(); //canvas canvas = new Canvas(this.activity); firstTabs.put(canvas, getTabSpecForITab(canvas)); //console console = new Console(this.activity); firstTabs.put(console, getTabSpecForITab(console)); //init tabs canvas.init(new PipeListener() { @Override public void viewChanged() { checkAdditionalTabs(); } }); console.init(); } } private void checkAdditionalTabs() { checkAnnotationTabs(); checkSignalPainterTabs(); checkCameraPainterTabs(); checkLandmarkPainterTabs(); checkGridPainterTabs(); checkFeedbackCollectionTabs(); checkVisualFeedbackTabs(); buildTabs(); } private void checkVisualFeedbackTabs() { List<Component> visualFeedbacks = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.EventHandler, VisualFeedback.class); removeComponentsOfClass(additionalTabs, VisualFeedback.class); if (!visualFeedbacks.isEmpty()) { boolean anyUnmanaged = false; TableLayout visualFeedbackLayout = getTableLayoutForVisualFeedback(visualFeedbacks); TabHost.TabSpec newTabSpec = getNewTabSpec(visualFeedbackLayout, visualFeedbacks.get(0).getComponentName(), android.R.drawable.ic_menu_compass); // TODO: Change icon. for (Component visualFeedback : visualFeedbacks) { boolean isManaged = PipelineBuilder.getInstance().isManagedFeedback(visualFeedback); if(! isManaged) { anyUnmanaged = true; ((VisualFeedback) visualFeedback).options.layout.set(visualFeedbackLayout); } } if(anyUnmanaged) additionalTabs.put(visualFeedbacks.get(0), newTabSpec); } } private void checkFeedbackCollectionTabs() { List<Component> feedbackCollections = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.EventHandler, FeedbackCollection.class); removeObsoleteComponentsOfClass(additionalTabs, feedbackCollections, FeedbackCollection.class); for (Component feedbackCollection : feedbackCollections) { if (additionalTabs.containsKey(feedbackCollection)) { continue; } TableLayout tableLayout = ((FeedbackCollection) feedbackCollection).options.layout.get(); if (tableLayout == null) { tableLayout = new TableLayout(activity); ((FeedbackCollection) feedbackCollection).options.layout.set(tableLayout); } TabHost.TabSpec tabSpec = getNewTabSpec(tableLayout, feedbackCollection.getComponentName(), android.R.drawable.ic_menu_compass); // TODO: Change icon. additionalTabs.put(feedbackCollection, tabSpec); } } private void checkCameraPainterTabs() { List<Component> cameraPainters = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, CameraPainter.class); removeObsoleteComponentsOfClass(additionalTabs, cameraPainters, CameraPainter.class); for (Component cameraPainter : cameraPainters) { if (additionalTabs.containsKey(cameraPainter)) { continue; } SurfaceView surfaceView = ((CameraPainter) cameraPainter).options.surfaceView.get(); if (surfaceView == null) { surfaceView = new SurfaceView(activity); ((CameraPainter) cameraPainter).options.surfaceView.set(surfaceView); } TabHost.TabSpec tabSpec = getNewTabSpec(surfaceView, cameraPainter.getComponentName(), android.R.drawable.ic_menu_camera); additionalTabs.put(cameraPainter, tabSpec); } } private void checkLandmarkPainterTabs() { List<Component> landmarkPainters = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, LandmarkPainter.class); removeObsoleteComponentsOfClass(additionalTabs, landmarkPainters, LandmarkPainter.class); for (Component landmarkPainter : landmarkPainters) { if (additionalTabs.containsKey(landmarkPainter)) { continue; } SurfaceView surfaceView = ((LandmarkPainter) landmarkPainter).options.surfaceView.get(); if (surfaceView == null) { surfaceView = new SurfaceView(activity); ((LandmarkPainter) landmarkPainter).options.surfaceView.set(surfaceView); } TabHost.TabSpec tabSpec = getNewTabSpec(surfaceView, landmarkPainter.getComponentName(), android.R.drawable.ic_menu_camera); additionalTabs.put(landmarkPainter, tabSpec); } } private void checkGridPainterTabs() { List<Component> gridPainters = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, GridPainter.class); removeObsoleteComponentsOfClass(additionalTabs, gridPainters, GridPainter.class); for (Component gridPainter : gridPainters) { if (additionalTabs.containsKey(gridPainter)) { continue; } SurfaceView surfaceView = ((GridPainter) gridPainter).options.surfaceView.get(); if (surfaceView == null) { surfaceView = new SurfaceView(activity); ((GridPainter) gridPainter).options.surfaceView.set(surfaceView); } TabHost.TabSpec tabSpec = getNewTabSpec(surfaceView, gridPainter.getComponentName(), android.R.drawable.ic_menu_view); additionalTabs.put(gridPainter, tabSpec); } } private void checkSignalPainterTabs() { List<Component> signalPainters = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, SignalPainter.class); removeObsoleteComponentsOfClass(additionalTabs, signalPainters, SignalPainter.class); for (Component signalPainter : signalPainters) { if (additionalTabs.containsKey(signalPainter)) { continue; } GraphView graphView = ((SignalPainter) signalPainter).options.graphView.get(); if (graphView == null) { graphView = new GraphView(activity); ((SignalPainter) signalPainter).options.graphView.set(graphView); } TabHost.TabSpec tabSpec = getNewTabSpec(graphView, signalPainter.getComponentName(), android.R.drawable.ic_menu_view); additionalTabs.put(signalPainter, tabSpec); } } private void checkAnnotationTabs() { List<Component> iFileWriters = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, IFileWriter.class); List<Component> trainers = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, Trainer.class); if (iFileWriters.isEmpty() && trainers.isEmpty()) { removeComponentsOfClass(firstTabs, AnnotationTab.class); } else if (!containsOfClass(firstTabs, AnnotationTab.class)) { AnnotationTab annotationTab = new AnnotationTab(activity); TabHost.TabSpec annotationTabSpec = getTabSpecForITab(annotationTab); firstTabs.put(annotationTab, annotationTabSpec); } else //Annotation tab is already here, refresh it { getAnnotation().syncWithModel(); } } private TableLayout getTableLayoutForVisualFeedback(List<Component> visualFeedbackComponents) { List<TableLayout> layouts = new ArrayList<>(); for (Object visualFeedback : visualFeedbackComponents) { TableLayout currentLayout = ((VisualFeedback) visualFeedback).options.layout.get(); if (currentLayout != null && !layouts.contains(currentLayout)) { layouts.add(currentLayout); } } return (layouts.size() == 1) ? layouts.get(0) : new TableLayout(activity); } private void removeComponentsOfClass(Map map, Class objectClass) { removeObsoleteComponentsOfClass(map, new ArrayList<Component>(), objectClass); } private void removeObsoleteComponentsOfClass(Map map, List<Component> retainableObjects, Class objectClass) { Iterator<Object> iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object additionalTabObject = iterator.next(); if (!retainableObjects.contains(additionalTabObject) && objectClass.isInstance(additionalTabObject)) { iterator.remove(); } } } private <T, S> boolean containsOfClass(Map<T, S> map, Class objectClass) { for (Map.Entry entry : map.entrySet()) { if (objectClass.isInstance(entry.getKey())) { return true; } } return false; } private void buildTabs() { tabHost.setCurrentTab(0); tabHost.clearAllTabs(); for (TabHost.TabSpec spec : firstTabs.values()) { tabHost.addTab(spec); } for (TabHost.TabSpec spec : additionalTabs.values()) { tabHost.addTab(spec); } } private TabHost.TabSpec getTabSpecForITab(ITab iTab) { return getNewTabSpec(iTab.getView(), iTab.getTitle(), iTab.getIcon()); } private TabHost.TabSpec getNewTabSpec(final View view, String title, int icon) { final TabHost.TabSpec tabSpec = tabHost.newTabSpec(title); tabSpec.setContent(new TabHost.TabContentFactory() { public View createTabContent(String tag) { return view; } }); tabSpec.setIndicator("", ContextCompat.getDrawable(activity, icon)); return tabSpec; } public void preStart() { AnnotationTab annotationTab = getAnnotation(); if (annotationTab != null) { annotationTab.startAnnotation(); } } public void preStop() { AnnotationTab annotationTab = getAnnotation(); if (annotationTab != null) { annotationTab.finishAnnotation(); } } public void actualizeContent(Util.AppAction appAction, Object o) { canvas.actualizeContent(appAction, o); } public void cleanUp() { console.cleanUp(); canvas.cleanUp(); } public AnnotationTab getAnnotation() { for (ITab iTab : firstTabs.keySet()) { if (iTab instanceof AnnotationTab) { return (AnnotationTab) iTab; } } return null; } }
11,989
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Canvas.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/Canvas.java
/* * Canvas.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.main; import android.content.Context; import android.view.View; import hcm.ssj.creator.R; import hcm.ssj.creator.util.Util; import hcm.ssj.creator.view.PipeListener; import hcm.ssj.creator.view.PipeView; /** * Canvas tab for main activity.<br> * Created by Frank Gaibler on 23.09.2016. */ class Canvas implements ITab { //tab private View view; private String title; private int icon; //canvas private PipeView pipeView = null; private PipeListener listener = null; /** * @param context Context */ Canvas(Context context) { //view pipeView = new PipeView(context); pipeView.setWillNotDraw(false); TwoDScrollView twoDScrollView = new TwoDScrollView(context); twoDScrollView.setHorizontalScrollBarEnabled(true); twoDScrollView.setVerticalScrollBarEnabled(true); twoDScrollView.setFillViewport(true); //necessary for pipe to have immediate size data twoDScrollView.addView(pipeView); view = twoDScrollView; //title title = context.getResources().getString(R.string.str_pipe); //icon icon = android.R.drawable.ic_menu_edit; } /** * @param appAction Util.AppAction * @param o Object */ void actualizeContent(Util.AppAction appAction, Object o) { if (pipeView != null) { pipeView.recalculate(appAction, o); } } /** * */ void cleanUp() { if (pipeView != null && listener != null) { pipeView.removeViewListener(listener); listener = null; } } /** * @param listener PipeListener */ void init(PipeListener listener) { this.listener = listener; pipeView.addViewListener(this.listener); } /** * @return View */ @Override public View getView() { return view; } /** * @return String */ @Override public String getTitle() { return title; } /** * @return int */ @Override public int getIcon() { return icon; } }
3,543
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
TwoDScrollView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/TwoDScrollView.java
/* * TwoDScrollView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ /* * Revised 5/19/2010 by GORGES * Now supports two-dimensional view scrolling * http://GORGES.us */ package hcm.ssj.creator.main; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.util.AttributeSet; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.Scroller; import android.widget.TextView; import java.util.List; /** * Layout container for a view hierarchy that can be scrolled by the user, * allowing it to be larger than the physical display. A TwoDScrollView * is a {@link FrameLayout}, meaning you should place one child in it * containing the entire contents to scroll; this child may itself be a layout * manager with a complex hierarchy of objects. A child that is often used * is a {@link LinearLayout} in a vertical orientation, presenting a vertical * array of top-level items that the user can scroll through. * <p> * <p>The {@link TextView} class also * takes care of its own scrolling, so does not require a TwoDScrollView, but * using the two together is possible to achieve the effect of a text view * within a larger container. */ public class TwoDScrollView extends FrameLayout { static final int ANIMATED_SCROLL_GAP = 250; static final float MAX_SCROLL_FACTOR = 0.5f; private long mLastScroll; private final Rect mTempRect = new Rect(); private Scroller mScroller; /** * Flag to indicate that we are moving focus ourselves. This is so the * code that watches for focus changes initiated outside this TwoDScrollView * knows that it does not have to do anything. */ private boolean mTwoDScrollViewMovedFocus; /** * Position of the last motion event. */ private float mLastMotionY; private float mLastMotionX; /** * True when the layout has changed but the traversal has not come through yet. * Ideally the view hierarchy would keep track of this for us. */ private boolean mIsLayoutDirty = true; /** * The child to give focus to in the event that a child has requested focus while the * layout is dirty. This prevents the scroll from being wrong if the child has not been * laid out before requesting focus. */ private View mChildToScrollTo = null; /** * True if the user is currently dragging this TwoDScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private boolean mIsBeingDragged = false; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; /** * Whether arrow scrolling is animated. */ private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; /** * When set to true, the scroll view measure its child to make it fill the currently * visible area. */ @ViewDebug.ExportedProperty(category = "layout") private boolean mFillViewport; public TwoDScrollView(Context context) { this(context, null); } public TwoDScrollView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.scrollViewStyle); } public TwoDScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initTwoDScrollView(); } /** * Indicates whether this ScrollView's content is stretched to fill the viewport. * * @return True if the content fills the viewport, false otherwise. * @attr ref android.R.styleable#ScrollView_fillViewport */ public boolean isFillViewport() { return mFillViewport; } /** * Indicates this ScrollView whether it should stretch its content height to fill * the viewport or not. * * @param fillViewport True to stretch the content's height to the viewport's * boundaries, false otherwise. * @attr ref android.R.styleable#ScrollView_fillViewport */ public void setFillViewport(boolean fillViewport) { if (fillViewport != mFillViewport) { mFillViewport = fillViewport; requestLayout(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!mFillViewport) { return; } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { return; } if (getChildCount() > 0) { final View child = getChildAt(0); final int height = getMeasuredHeight(); if (child.getMeasuredHeight() < height) { final int widthPadding; final int heightPadding; final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; if (targetSdkVersion >= Build.VERSION_CODES.M) { widthPadding = getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin; heightPadding = getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin; } else { widthPadding = getPaddingLeft() + getPaddingRight(); heightPadding = getPaddingTop() + getPaddingBottom(); } final int childWidthMeasureSpec = getChildMeasureSpec( widthMeasureSpec, widthPadding, lp.width); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( height - heightPadding, MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } @Override protected float getTopFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getVerticalFadingEdgeLength(); if (getScrollY() < length) { return getScrollY() / (float) length; } return 1.0f; } @Override protected float getBottomFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getVerticalFadingEdgeLength(); final int bottomEdge = getHeight() - getPaddingBottom(); final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge; if (span < length) { return span / (float) length; } return 1.0f; } @Override protected float getLeftFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getHorizontalFadingEdgeLength(); if (getScrollX() < length) { return getScrollX() / (float) length; } return 1.0f; } @Override protected float getRightFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getHorizontalFadingEdgeLength(); final int rightEdge = getWidth() - getPaddingRight(); final int span = getChildAt(0).getRight() - getScrollX() - rightEdge; if (span < length) { return span / (float) length; } return 1.0f; } /** * @return The maximum amount this scroll view will scroll in response to * an arrow event. */ public int getMaxScrollAmountVertical() { return (int) (MAX_SCROLL_FACTOR * getHeight()); } public int getMaxScrollAmountHorizontal() { return (int) (MAX_SCROLL_FACTOR * getWidth()); } private void initTwoDScrollView() { mScroller = new Scroller(getContext()); setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); } @Override public void addView(View child) { if (getChildCount() > 0) { throw new IllegalStateException("TwoDScrollView can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 0) { throw new IllegalStateException("TwoDScrollView can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("TwoDScrollView can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("TwoDScrollView can host only one direct child"); } super.addView(child, index, params); } /** * @return Returns true this TwoDScrollView can be scrolled */ private boolean canScroll() { View child = getChildAt(0); if (child != null) { int childHeight = child.getHeight(); int childWidth = child.getWidth(); return (getHeight() < childHeight + getPaddingTop() + getPaddingBottom()) || (getWidth() < childWidth + getPaddingLeft() + getPaddingRight()); } return false; } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first boolean handled = super.dispatchKeyEvent(event); return handled || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { mTempRect.setEmpty(); if (!canScroll()) { if (isFocused()) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN); return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN); } return false; } boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_UP, false); } else { handled = fullScroll(View.FOCUS_UP, false); } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_DOWN, false); } else { handled = fullScroll(View.FOCUS_DOWN, false); } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_LEFT, true); } else { handled = fullScroll(View.FOCUS_LEFT, true); } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_RIGHT, true); } else { handled = fullScroll(View.FOCUS_RIGHT, true); } break; } } return handled; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. * * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { return true; } if (!canScroll()) { mIsBeingDragged = false; return false; } final float y = ev.getY(); final float x = ev.getX(); switch (action) { case MotionEvent.ACTION_MOVE: /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int yDiff = (int) Math.abs(y - mLastMotionY); final int xDiff = (int) Math.abs(x - mLastMotionX); if (yDiff > mTouchSlop || xDiff > mTouchSlop) { mIsBeingDragged = true; } break; case MotionEvent.ACTION_DOWN: /* Remember location of down touch */ mLastMotionY = y; mLastMotionX = x; /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ mIsBeingDragged = !mScroller.isFinished(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ mIsBeingDragged = false; break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. return false; } if (!canScroll()) { return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); final float y = ev.getY(); final float x = ev.getX(); switch (action) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mLastMotionY = y; mLastMotionX = x; break; case MotionEvent.ACTION_MOVE: // Scroll to follow the motion event int deltaX = (int) (mLastMotionX - x); int deltaY = (int) (mLastMotionY - y); mLastMotionX = x; mLastMotionY = y; if (deltaX < 0) { if (getScrollX() < 0) { deltaX = 0; } } else if (deltaX > 0) { final int rightEdge = getWidth() - getPaddingRight(); final int availableToScroll = getChildAt(0).getRight() - getScrollX() - rightEdge; if (availableToScroll > 0) { deltaX = Math.min(availableToScroll, deltaX); } else { deltaX = 0; } } if (deltaY < 0) { if (getScrollY() < 0) { deltaY = 0; } } else if (deltaY > 0) { final int bottomEdge = getHeight() - getPaddingBottom(); final int availableToScroll = getChildAt(0).getBottom() - getScrollY() - bottomEdge; if (availableToScroll > 0) { deltaY = Math.min(availableToScroll, deltaY); } else { deltaY = 0; } } if (deltaY != 0 || deltaX != 0) scrollBy(deltaX, deltaY); break; case MotionEvent.ACTION_UP: final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialXVelocity = (int) velocityTracker.getXVelocity(); int initialYVelocity = (int) velocityTracker.getYVelocity(); if ((Math.abs(initialXVelocity) + Math.abs(initialYVelocity) > mMinimumVelocity) && getChildCount() > 0) { fling(-initialXVelocity, -initialYVelocity); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } return true; } /** * Finds the next focusable component that fits in this View's bounds * (excluding fading edges) pretending that this View's top is located at * the parameter top. * * @param topFocus look for a candidate is the one at the top of the bounds * if topFocus is true, or at the bottom of the bounds if topFocus is * false * @param top the top offset of the bounds in which a focusable must be * found (the fading edge is assumed to start at this position) * @param preferredFocusable the View that has highest priority and will be * returned if it is within my bounds (null is valid) * @return the next focusable component in the bounds or null if none can be * found */ private View findFocusableViewInMyBounds(final boolean topFocus, final int top, final boolean leftFocus, final int left, View preferredFocusable) { /* * The fading edge's transparent side should be considered for focus * since it's mostly visible, so we divide the actual fading edge length * by 2. */ final int verticalFadingEdgeLength = getVerticalFadingEdgeLength() / 2; final int topWithoutFadingEdge = top + verticalFadingEdgeLength; final int bottomWithoutFadingEdge = top + getHeight() - verticalFadingEdgeLength; final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength() / 2; final int leftWithoutFadingEdge = left + horizontalFadingEdgeLength; final int rightWithoutFadingEdge = left + getWidth() - horizontalFadingEdgeLength; if ((preferredFocusable != null) && (preferredFocusable.getTop() < bottomWithoutFadingEdge) && (preferredFocusable.getBottom() > topWithoutFadingEdge) && (preferredFocusable.getLeft() < rightWithoutFadingEdge) && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { return preferredFocusable; } return findFocusableViewInBounds(topFocus, topWithoutFadingEdge, bottomWithoutFadingEdge, leftFocus, leftWithoutFadingEdge, rightWithoutFadingEdge); } /** * Finds the next focusable component that fits in the specified bounds. * </p> * * @param topFocus look for a candidate is the one at the top of the bounds * if topFocus is true, or at the bottom of the bounds if topFocus is * false * @param top the top offset of the bounds in which a focusable must be * found * @param bottom the bottom offset of the bounds in which a focusable must * be found * @return the next focusable component in the bounds or null if none can * be found */ private View findFocusableViewInBounds(boolean topFocus, int top, int bottom, boolean leftFocus, int left, int right) { List<View> focusables = getFocusables(View.FOCUS_FORWARD); View focusCandidate = null; /* * A fully contained focusable is one where its top is below the bound's * top, and its bottom is above the bound's bottom. A partially * contained focusable is one where some part of it is within the * bounds, but it also has some part that is not within bounds. A fully contained * focusable is preferred to a partially contained focusable. */ boolean foundFullyContainedFocusable = false; int count = focusables.size(); for (int i = 0; i < count; i++) { View view = focusables.get(i); int viewTop = view.getTop(); int viewBottom = view.getBottom(); int viewLeft = view.getLeft(); int viewRight = view.getRight(); if (top < viewBottom && viewTop < bottom && left < viewRight && viewLeft < right) { /* * the focusable is in the target area, it is a candidate for * focusing */ final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom) && (left < viewLeft) && (viewRight < right); if (focusCandidate == null) { /* No candidate, take this one */ focusCandidate = view; foundFullyContainedFocusable = viewIsFullyContained; } else { final boolean viewIsCloserToVerticalBoundary = (topFocus && viewTop < focusCandidate.getTop()) || (!topFocus && viewBottom > focusCandidate.getBottom()); final boolean viewIsCloserToHorizontalBoundary = (leftFocus && viewLeft < focusCandidate.getLeft()) || (!leftFocus && viewRight > focusCandidate.getRight()); if (foundFullyContainedFocusable) { if (viewIsFullyContained && viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) { /* * We're dealing with only fully contained views, so * it has to be closer to the boundary to beat our * candidate */ focusCandidate = view; } } else { if (viewIsFullyContained) { /* Any fully contained view beats a partially contained view */ focusCandidate = view; foundFullyContainedFocusable = true; } else if (viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) { /* * Partially contained view beats another partially * contained view if it's closer */ focusCandidate = view; } } } } } return focusCandidate; } /** * <p>Handles scrolling in response to a "home/end" shortcut press. This * method will scroll the view to the top or bottom and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go the top of the view or * {@link android.view.View#FOCUS_DOWN} to go the bottom * @return true if the key event is consumed by this method, false otherwise */ public boolean fullScroll(int direction, boolean horizontal) { if (!horizontal) { boolean down = direction == View.FOCUS_DOWN; int height = getHeight(); mTempRect.top = 0; mTempRect.bottom = height; if (down) { int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); mTempRect.bottom = view.getBottom(); mTempRect.top = mTempRect.bottom - height; } } return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom, 0, 0, 0); } else { boolean right = direction == View.FOCUS_DOWN; int width = getWidth(); mTempRect.left = 0; mTempRect.right = width; if (right) { int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); mTempRect.right = view.getBottom(); mTempRect.left = mTempRect.right - width; } } return scrollAndFocus(0, 0, 0, direction, mTempRect.top, mTempRect.bottom); } } /** * <p>Scrolls the view to make the area defined by <code>top</code> and * <code>bottom</code> visible. This method attempts to give the focus * to a component visible in this area. If no component can be focused in * the new visible area, the focus is reclaimed by this scrollview.</p> * * @param directionY the scroll direction: {@link android.view.View#FOCUS_UP} * to go upward * {@link android.view.View#FOCUS_DOWN} to downward * @param top the top offset of the new area to be made visible * @param bottom the bottom offset of the new area to be made visible * @return true if the key event is consumed by this method, false otherwise */ private boolean scrollAndFocus(int directionY, int top, int bottom, int directionX, int left, int right) { boolean handled = true; int height = getHeight(); int containerTop = getScrollY(); int containerBottom = containerTop + height; boolean up = directionY == View.FOCUS_UP; int width = getWidth(); int containerLeft = getScrollX(); int containerRight = containerLeft + width; boolean leftwards = directionX == View.FOCUS_UP; View newFocused = findFocusableViewInBounds(up, top, bottom, leftwards, left, right); if (newFocused == null) { newFocused = this; } if ((top >= containerTop && bottom <= containerBottom) || (left >= containerLeft && right <= containerRight)) { handled = false; } else { int deltaY = up ? (top - containerTop) : (bottom - containerBottom); int deltaX = leftwards ? (left - containerLeft) : (right - containerRight); doScroll(deltaX, deltaY); } if (newFocused != findFocus() && newFocused.requestFocus(directionY)) { mTwoDScrollViewMovedFocus = true; mTwoDScrollViewMovedFocus = false; } return handled; } /** * Handle scrolling in response to an up or down arrow click. * * @param direction The direction corresponding to the arrow key that was * pressed * @return True if we consumed the event, false otherwise */ public boolean arrowScroll(int direction, boolean horizontal) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); final int maxJump = horizontal ? getMaxScrollAmountHorizontal() : getMaxScrollAmountVertical(); if (!horizontal) { if (nextFocused != null) { nextFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(nextFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScroll(0, scrollDelta); nextFocused.requestFocus(direction); } else { // no new focus int scrollDelta = maxJump; if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { scrollDelta = getScrollY(); } else if (direction == View.FOCUS_DOWN) { if (getChildCount() > 0) { int daBottom = getChildAt(0).getBottom(); int screenBottom = getScrollY() + getHeight(); if (daBottom - screenBottom < maxJump) { scrollDelta = daBottom - screenBottom; } } } if (scrollDelta == 0) { return false; } doScroll(0, direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); } } else { if (nextFocused != null) { nextFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(nextFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScroll(scrollDelta, 0); nextFocused.requestFocus(direction); } else { // no new focus int scrollDelta = maxJump; if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { scrollDelta = getScrollY(); } else if (direction == View.FOCUS_DOWN) { if (getChildCount() > 0) { int daBottom = getChildAt(0).getBottom(); int screenBottom = getScrollY() + getHeight(); if (daBottom - screenBottom < maxJump) { scrollDelta = daBottom - screenBottom; } } } if (scrollDelta == 0) { return false; } doScroll(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta, 0); } } return true; } /** * Smooth scroll by a Y delta * * @param deltaY the number of pixels to scroll by on the Y axis */ private void doScroll(int deltaX, int deltaY) { if (deltaX != 0 || deltaY != 0) { smoothScrollBy(deltaX, deltaY); } } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ public final void smoothScrollBy(int dx, int dy) { long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; if (duration > ANIMATED_SCROLL_GAP) { mScroller.startScroll(getScrollX(), getScrollY(), dx, dy); awakenScrollBars(mScroller.getDuration()); invalidate(); } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis */ public final void smoothScrollTo(int x, int y) { smoothScrollBy(x - getScrollX(), y - getScrollY()); } /** * <p>The scroll range of a scroll view is the overall height of all of its * children.</p> */ @Override protected int computeVerticalScrollRange() { int count = getChildCount(); return count == 0 ? getHeight() : (getChildAt(0)).getBottom(); } @Override protected int computeHorizontalScrollRange() { int count = getChildCount(); return count == 0 ? getWidth() : (getChildAt(0)).getRight(); } @Override protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { ViewGroup.LayoutParams lp = child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), lp.width); childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { // This is called at drawing time by ViewGroup. We don't want to // re-show the scrollbars at this point, which scrollTo will do, // so we replicate most of scrollTo here. // // It's a little odd to call onScrollChanged from inside the drawing. // // It is, except when you remember that computeScroll() is used to // animate scrolling. So unless we want to defer the onScrollChanged() // until the end of the animated scrolling, we don't really have a // choice here. // // I agree. The alternative, which I think would be worse, is to post // something and tell the subclasses later. This is bad because there // will be a window where mScrollX/Y is different from what the app // thinks it is. // int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (getChildCount() > 0) { View child = getChildAt(0); scrollTo(clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()), clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight())); } else { scrollTo(x, y); } if (oldX != getScrollX() || oldY != getScrollY()) { onScrollChanged(getScrollX(), getScrollY(), oldX, oldY); } // Keep on drawing until the animation has finished. postInvalidate(); } } /** * Scrolls the view to the given child. * * @param child the View to scroll to */ private void scrollToChild(View child) { child.getDrawingRect(mTempRect); /* Offset from child's local coordinates to TwoDScrollView coordinates */ offsetDescendantRectToMyCoords(child, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); if (scrollDelta != 0) { scrollBy(0, scrollDelta); } } /** * If rect is off screen, scroll just enough to get it (or at least the * first screen size chunk of it) on screen. * * @param rect The rectangle. * @param immediate True to scroll immediately without animation * @return true if scrolling was performed */ private boolean scrollToChildRect(Rect rect, boolean immediate) { final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); final boolean scroll = delta != 0; if (scroll) { if (immediate) { scrollBy(0, delta); } else { smoothScrollBy(0, delta); } } return scroll; } /** * Compute the amount to scroll in the Y direction in order to get * a rectangle completely on the screen (or, if taller than the screen, * at least the first screen size chunk of it). * * @param rect The rect. * @return The scroll delta. */ protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { if (getChildCount() == 0) return 0; int height = getHeight(); int screenTop = getScrollY(); int screenBottom = screenTop + height; int fadingEdge = getVerticalFadingEdgeLength(); // leave room for top fading edge as long as rect isn't at very top if (rect.top > 0) { screenTop += fadingEdge; } // leave room for bottom fading edge as long as rect isn't at very bottom if (rect.bottom < getChildAt(0).getHeight()) { screenBottom -= fadingEdge; } int scrollYDelta = 0; if (rect.bottom > screenBottom && rect.top > screenTop) { // need to move down to get it in view: move down just enough so // that the entire rectangle is in view (or at least the first // screen size chunk). if (rect.height() > height) { // just enough to get screen size chunk on scrollYDelta += (rect.top - screenTop); } else { // get entire rect at bottom of screen scrollYDelta += (rect.bottom - screenBottom); } // make sure we aren't scrolling beyond the end of our content int bottom = getChildAt(0).getBottom(); int distanceToBottom = bottom - screenBottom; scrollYDelta = Math.min(scrollYDelta, distanceToBottom); } else if (rect.top < screenTop && rect.bottom < screenBottom) { // need to move up to get it in view: move up just enough so that // entire rectangle is in view (or at least the first screen // size chunk of it). if (rect.height() > height) { // screen size chunk scrollYDelta -= (screenBottom - rect.bottom); } else { // entire rect at top scrollYDelta -= (screenTop - rect.top); } // make sure we aren't scrolling any further than the top our content scrollYDelta = Math.max(scrollYDelta, -getScrollY()); } return scrollYDelta; } @Override public void requestChildFocus(View child, View focused) { if (!mTwoDScrollViewMovedFocus) { if (!mIsLayoutDirty) { scrollToChild(focused); } else { // The child may not be laid out yet, we can't compute the scroll yet mChildToScrollTo = focused; } } super.requestChildFocus(child, focused); } /** * When looking for focus in children of a scroll view, need to be a little * more careful not to give focus to something that is scrolled off screen. * <p> * This is more expensive than the default {@link android.view.ViewGroup} * implementation, otherwise this behavior might have been made the default. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { // convert from forward / backward notation to up / down / left / right // (ugh). if (direction == View.FOCUS_FORWARD) { direction = View.FOCUS_DOWN; } else if (direction == View.FOCUS_BACKWARD) { direction = View.FOCUS_UP; } final View nextFocus = previouslyFocusedRect == null ? FocusFinder.getInstance().findNextFocus(this, null, direction) : FocusFinder.getInstance().findNextFocusFromRect(this, previouslyFocusedRect, direction); return nextFocus != null && nextFocus.requestFocus(direction, previouslyFocusedRect); } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // offset into coordinate space of this scroll view rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); return scrollToChildRect(rectangle, immediate); } @Override public void requestLayout() { mIsLayoutDirty = true; super.requestLayout(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); mIsLayoutDirty = false; // Give a child focus if it needs it if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { scrollToChild(mChildToScrollTo); } mChildToScrollTo = null; // Calling this with the present values causes it to re-clam them scrollTo(getScrollX(), getScrollY()); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); View currentFocused = findFocus(); if (null == currentFocused || this == currentFocused) return; // If the currently-focused view was visible on the screen when the // screen was at the old height, then scroll the screen to make that // view visible with the new screen height. currentFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(currentFocused, mTempRect); int scrollDeltaX = computeScrollDeltaToGetChildRectOnScreen(mTempRect); int scrollDeltaY = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScroll(scrollDeltaX, scrollDeltaY); } /** * Return true if child is an descendant of parent, (or equal to the parent). */ private boolean isViewDescendantOf(View child, View parent) { if (child == parent) { return true; } final ViewParent theParent = child.getParent(); return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); } /** * Fling the scroll view * * @param velocityY The initial velocity in the Y direction. Positive * numbers mean that the finger/curor is moving down the screen, * which means we want to scroll towards the top. */ public void fling(int velocityX, int velocityY) { if (getChildCount() > 0) { int height = getHeight() - getPaddingBottom() - getPaddingTop(); int bottom = getChildAt(0).getHeight(); int width = getWidth() - getPaddingRight() - getPaddingLeft(); int right = getChildAt(0).getWidth(); mScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY, 0, right - width, 0, bottom - height); final boolean movingDown = velocityY > 0; final boolean movingRight = velocityX > 0; View newFocused = findFocusableViewInMyBounds(movingRight, mScroller.getFinalX(), movingDown, mScroller.getFinalY(), findFocus()); if (newFocused == null) { newFocused = this; } if (newFocused != findFocus() && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) { mTwoDScrollViewMovedFocus = true; mTwoDScrollViewMovedFocus = false; } awakenScrollBars(mScroller.getDuration()); invalidate(); } } /** * {@inheritDoc} * <p> * <p>This version also clamps the scrolling to the bounds of our child. */ public void scrollTo(int x, int y) { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()); y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight()); if (x != getScrollX() || y != getScrollY()) { super.scrollTo(x, y); } } } private int clamp(int n, int my, int child) { if (my >= child || n < 0) { /* my >= child is this case: * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * * n < 0 is this case: * |------ me ------| * |-------- child --------| * |-- mScrollX --| */ return 0; } if ((my + n) > child) { /* this case: * |------ me ------| * |------ child ------| * |-- mScrollX --| */ return child - my; } return n; } }
49,608
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ITab.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/main/ITab.java
/* * ITab.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.main; import android.view.View; /** * Interface for tabs.<br> * Created by Frank Gaibler on 23.09.2016. */ interface ITab { /** * @return View */ View getView(); /** * @return String */ String getTitle(); /** * @return int */ int getIcon(); }
1,670
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ComponentView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/ComponentView.java
/* * ComponentView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipDescription; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import hcm.ssj.core.Component; import hcm.ssj.core.Consumer; import hcm.ssj.core.EventHandler; import hcm.ssj.core.Log; import hcm.ssj.core.Sensor; import hcm.ssj.core.SensorChannel; import hcm.ssj.core.Transformer; import hcm.ssj.creator.R; import hcm.ssj.creator.activity.FeedbackCollectionActivity; import hcm.ssj.creator.activity.OptionsActivity; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.core.container.FeedbackCollectionContainerElement; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.ml.Model; /** * Draws elements.<br> * Created by Frank Gaibler on 12.05.2016. */ public class ComponentView extends View { private final static int[] boxColor = {R.color.colorSensor, R.color.colorProvider, R.color.colorTransformer, R.color.colorConsumer, R.color.colorEventHandler, R.color.colorModel}; private final static int[] textColor = {Color.BLACK, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE}; private final static float STROKE_WIDTH = 0.25f; private static Paint[] paintsElementBox; private static Paint[] paintElementText; private static Paint paintElementBorder; // private Object element; private int[] streamConnectionHashes; private int[] eventConnectionHashes; private int[] modelConnectionHashes; private String text; private int gridX = -1; private int gridY = -1; // private int paintType; /** * @param context Context */ private ComponentView(Context context) { super(context); } /** * @param context Context * @param element Object */ public ComponentView(Context context, final Object element) { super(context); this.element = element; initPaint(); initName(); //add click listener if (this.element instanceof FeedbackCollection) { OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { openFeedbackCollectionDialog((FeedbackCollection)element); } }; this.setOnClickListener(onClickListener); } else { OnClickListener onClickListener = new OnClickListener() { /** * @param v View */ @Override public void onClick(View v) { openOptions(); } }; this.setOnClickListener(onClickListener); } //add touch listener OnLongClickListener onTouchListener = new OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item("DragEvent"); ClipData dragData = new ClipData("DragEvent", new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v); v.startDrag(dragData, shadowBuilder, v, 0); ((ViewGroup) v.getParent()).removeView(v); return true; } }; this.setOnLongClickListener(onTouchListener); } /** * @return Object */ protected Object getElement() { return element; } /** * @return int */ protected int getElementHash() { return element.hashCode(); } /** * @return int[] */ protected int[] getStreamConnectionHashes() { return streamConnectionHashes; } /** * @param connectionHashes int[] */ protected void setStreamConnectionHashes(int[] connectionHashes) { this.streamConnectionHashes = connectionHashes; } /** * @return int[] */ protected int[] getEventConnectionHashes() { return eventConnectionHashes; } /** * @param connectionHashes int[] */ protected void setEventConnectionHashes(int[] connectionHashes) { this.eventConnectionHashes = connectionHashes; } /** * @return int[] */ protected int[] getModelConnectionHashes() { return modelConnectionHashes; } /** * @param connectionHashes int[] */ protected void setModelConnectionHashes(int[] connectionHashes) { this.modelConnectionHashes = connectionHashes; } /** * @param text String */ protected void setText(String text) { this.text = text; } /** * @return int */ protected int getGridX() { return gridX; } /** * @param x int */ protected void setGridX(int x) { gridX = x; } /** * @return int */ protected int getGridY() { return gridY; } /** * @param y int */ protected void setGridY(int y) { gridY = y; } /** * @return boolean */ protected boolean isPositioned() { return gridY >= 0 && gridX >= 0; } /** * */ private void initPaint() { if (paintsElementBox == null) { paintsElementBox = new Paint[boxColor.length]; for (int i = 0; i < paintsElementBox.length; i++) { paintsElementBox[i] = new Paint(Paint.ANTI_ALIAS_FLAG); paintsElementBox[i].setStyle(Paint.Style.FILL); paintsElementBox[i].setColor(getResources().getColor(boxColor[i])); } } if (paintElementBorder == null) { DisplayMetrics dm = getResources().getDisplayMetrics(); float strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, STROKE_WIDTH, dm); paintElementBorder = new Paint(Paint.ANTI_ALIAS_FLAG); paintElementBorder.setStyle(Paint.Style.STROKE); paintElementBorder.setColor(Color.BLACK); paintElementBorder.setStrokeWidth(strokeWidth); } if (paintElementText == null) { paintElementText = new Paint[textColor.length]; for (int i = 0; i < paintElementText.length; i++) { paintElementText[i] = new Paint(Paint.ANTI_ALIAS_FLAG); paintElementText[i].setStyle(Paint.Style.FILL); paintElementText[i].setColor(textColor[i]); paintElementText[i].setTextAlign(Paint.Align.CENTER); } } // color depends on element type if (element instanceof Sensor) { paintType = 0; } else if (element instanceof SensorChannel) { paintType = 1; } else if (element instanceof Transformer) { paintType = 2; } else if (element instanceof Consumer) { paintType = 3; } else if (element instanceof EventHandler) { paintType = 4; } else if (element instanceof Model) { paintType = 5; } } /** * Take all upper case letters and fill remaining with trailing lower case letters */ protected void initName() { String componentName = ((Component) element).getComponentName(); componentName = componentName.substring(componentName.lastIndexOf("_") + 1); char[] acComponentName = componentName.toCharArray(); String shortName = ""; int j = 0, max = 3, last = 0; for (int i = 0; i < acComponentName.length && j < max; i++) { if (Character.isUpperCase(acComponentName[i])) { shortName += acComponentName[i]; j++; last = i; } } if (j < max) { while (j++ < max && ++last < acComponentName.length) { shortName += acComponentName[last]; } } if (shortName.equals("Com")) { Log.e("Name: " + element.getClass().getSimpleName()); } setText(shortName); } /** * @param canvas Canvas */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); canvas.drawRect(0, 0, getWidth(), getHeight(), paintsElementBox[paintType]); canvas.drawRect(1, 1, getWidth(), getHeight(), paintElementBorder); //draws the text in the middle of the box float textSize = getWidth() / 2.5f; paintElementText[paintType].setTextSize(textSize); canvas.drawText(text, textSize * (5.f / 4.f), textSize * (8.f / 5.f), paintElementText[paintType]); invalidate(); canvas.restore(); } protected void openOptions() { Activity activity = (Activity) getContext(); OptionsActivity.object = this.element; activity.startActivity(new Intent(activity, OptionsActivity.class)); } private void openFeedbackCollectionDialog(final FeedbackCollection element) { final FeedbackCollectionContainerElement feedbackCollectionContainerElement = PipelineBuilder.getInstance().getFeedbackCollectionContainerElement(element); Activity activity = (Activity) getContext(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.select_action) .setPositiveButton(R.string.str_options, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { openOptions(); } }) .setNeutralButton(android.R.string.cancel, null) .setNegativeButton(R.string.feedback, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Activity activity = (Activity) getContext(); FeedbackCollectionActivity.feedbackCollectionContainerElement = feedbackCollectionContainerElement; activity.startActivity(new Intent(activity, FeedbackCollectionActivity.class)); } }) .show(); } }
10,401
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipeListener.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/PipeListener.java
/* * PipeListener.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; /** * Pipe listener <br> * Created by Frank on 03.03.2017. */ public interface PipeListener { void viewChanged(); }
1,505
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
StreamView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/StreamView.java
/* * StreamView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import java.util.ArrayList; import hcm.ssj.core.stream.Stream; /** * Plots stream data on canvas. */ public class StreamView extends View { private static final int LAYOUT_HEIGHT = 350; private static final int LAYOUT_MARGIN_TOP = 20; private static final int LAYOUT_MARGIN_BOTTOM = 20; private static final int LAYOUT_MARGIN_LEFT = 25; private static final int LAYOUT_MARGIN_RIGHT = 0; private Stream stream; private Bitmap streamBitmap; private Rect drawRect; private int width; private int height; public StreamView(Context context, Stream s) { super(context); stream = s; init(); } public StreamView(Context context) { super(context); init(); } public StreamView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public StreamView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onSizeChanged(int w, int h, int oldW, int oldH) { width = getMeasuredWidth(); height = getMeasuredHeight(); init(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (streamBitmap != null) { canvas.drawBitmap(streamBitmap, null, drawRect, null); } } private void init() { drawRect = new Rect(0, 0, width, height); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LAYOUT_HEIGHT); layoutParams.setMargins(LAYOUT_MARGIN_LEFT, LAYOUT_MARGIN_TOP, LAYOUT_MARGIN_RIGHT, LAYOUT_MARGIN_BOTTOM); setLayoutParams(layoutParams); createPlot(); } private void createPlot() { if (width <= 0 || height <= 0 || stream == null) { return; } Canvas canvas; streamBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); canvas = new Canvas(streamBitmap); ArrayList<Path> streamPaths = drawStreams(); Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setStrokeWidth(1.5f); for (Path path : streamPaths) { canvas.drawPath(path, paint); } invalidate(); } private ArrayList<Path> drawStreams() { float[] data = stream.ptrF(); float max = findMax(data); float centerY = height / 2.0f; ArrayList<Path> paths = new ArrayList<>(); for (int i = 0; i < stream.dim; i++) { paths.add(new Path()); } float xStep = width / (float) stream.num; float[][] dataColumns = getDataColumns(data); for (int col = 0; col < stream.dim; col++) { paths.get(col).moveTo(0, centerY - ((dataColumns[col][0] / max) * centerY)); for (int row = 0; row < stream.num; row++) { paths.get(col).lineTo(xStep * row, centerY - ((dataColumns[col][row] / max) * centerY)); } } return paths; } private float findMax(float[] array) { float max = Float.MIN_VALUE; for (float element : array) { if (element > max) { max = element; } } return max; } private float[][] getDataColumns(float[] data) { float[][] dataCols = new float[stream.dim][stream.num]; for (int col = 0; col < stream.dim; col++) { for (int row = 0; row < stream.num; row++) { dataCols[col][row] = data[row * stream.dim + col]; } } return dataCols; } }
4,913
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
StreamLayout.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/StreamLayout.java
/* * StreamLayout.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Paint; import androidx.core.content.ContextCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import java.util.Locale; import hcm.ssj.creator.R; /** * Layout group that contains custom views representing different stream files. * This layout group draws time axis with corresponding time-steps as well as playback marker * that is moved forward as audio files are being played. */ public class StreamLayout extends LinearLayout { private static final int TIME_AXIS_OFFSET = 80; private static final int TIME_CODE_OFFSET = 25; private static final int PADDING = 25; private static final int TIME_STEP_PEG_LENGTH = 20; private static final int TEXT_SIZE = 36; private static final int AXIS_STROKE_WIDTH = 4; private static final int MARKER_ORIGIN = PADDING; private static final int MARKER_WIDTH = 4; private static final boolean ENABLE_ANTI_ALIAS = true; private int markerProgress = MARKER_ORIGIN; private int width; private int height; private int maxAudioLength; float xStep; private TextPaint textPaint; private Paint axisPaint; private Paint markerPaint; public StreamLayout(Context context) { super(context); init(context, null, 0); } public StreamLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public StreamLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } /** * Updates the position of the playback marker. * @param progress The playback progress of the audio file. */ public void setMarkerProgress(int progress) { markerProgress = progress; postInvalidate(); } /** * Puts the playback marker at the start position. */ public void resetMarker() { setMarkerProgress(MARKER_ORIGIN); } /** * Keeps track of maximal audio length and recalculates movement step of playback marker along * time axis. * @param length The new length of the longest audio file in StreamLayout. */ public void setMaxAudioLength(int length) { maxAudioLength = length; xStep = width / (maxAudioLength * 1.0f); } @Override public boolean performClick() { super.performClick(); return true; } @Override public void onViewAdded(View view) { int currentLength; try { currentLength = ((WaveformView) view).getAudioLength(); } catch (ClassCastException e) { return; } // Keep track of the length of the longest audio file. if (currentLength > maxAudioLength) { setMaxAudioLength(currentLength); } // Add horizontal line to separate multiple waveforms. if (getChildCount() > 1) { addSeparator(); } // Rescale width of all child views according to the length of the longest audio file. for (int i = 0; i < getChildCount(); i++) { try { WaveformView waveformView = (WaveformView) getChildAt(i); float factor = (float) waveformView.getAudioLength() / maxAudioLength; waveformView.setWidthScale(factor); } catch (ClassCastException e) { // Empty on purpose, as we only rescale waveform views and not horizontal lines. } } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (maxAudioLength == 0) { return; } drawTimeAxis(canvas); if (markerProgress > MARKER_ORIGIN && markerProgress < maxAudioLength) { float markerPosition = xStep * markerProgress + MARKER_ORIGIN; // Move marker forward as audio is being played. canvas.drawLine(markerPosition, 0, markerPosition, height - TIME_AXIS_OFFSET, markerPaint); } else { // Put marker at the origin. canvas.drawLine(MARKER_ORIGIN, 0, MARKER_ORIGIN, height - TIME_AXIS_OFFSET, markerPaint); } } @Override protected void onSizeChanged(int w, int h, int oldWidth, int oldHeight) { width = getMeasuredWidth(); height = getMeasuredHeight(); } /** * Retrieves custom XML attribute values of StreamLayout and initializes * colors and text size. * @param context Context of activity that uses the StreamLayout. * @param attrs Set of attributes. * @param defStyle Default style. */ private void init(Context context, AttributeSet attrs, int defStyle) { final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.StreamLayout, defStyle, 0); int timeCodeColor = a.getColor(R.styleable.StreamLayout_timeCodeColor, ContextCompat.getColor(context, R.color.colorBlack)); int axisColor = a.getColor(R.styleable.StreamLayout_axisColor, ContextCompat.getColor(context, R.color.colorBlack)); int markerColor = a.getColor(R.styleable.StreamLayout_markerColor, ContextCompat.getColor(context, R.color.colorBlack)); a.recycle(); textPaint = new TextPaint(); textPaint.setFlags(Paint.ANTI_ALIAS_FLAG); textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setColor(timeCodeColor); textPaint.setTextSize(TEXT_SIZE); axisPaint = new Paint(); axisPaint.setStyle(Paint.Style.STROKE); axisPaint.setStrokeWidth(AXIS_STROKE_WIDTH); axisPaint.setAntiAlias(ENABLE_ANTI_ALIAS); axisPaint.setColor(axisColor); markerPaint = new Paint(); markerPaint.setStrokeWidth(MARKER_WIDTH); markerPaint.setStyle(Paint.Style.STROKE); markerPaint.setPathEffect(new DashPathEffect(new float[] {5, 5}, 0)); markerPaint.setColor(markerColor); } /** * Draws time axis with appropriate time steps as labels. * @param canvas Canvas to draw the axis on. */ private void drawTimeAxis(Canvas canvas) { int seconds = maxAudioLength / 1000; float xStep = width / (maxAudioLength / 1000f); float textWidth = textPaint.measureText("10.00"); float secondStep = (textWidth * seconds * 2) / width; secondStep = Math.max(secondStep, 1) - 0.5f; for (float i = 0; i <= seconds; i += secondStep) { // Draw timestamp labels. canvas.drawText(String.format(Locale.ENGLISH, "%.1f", i), PADDING + i * xStep, height - TIME_CODE_OFFSET, textPaint); // Make every second time step peg half the length. int cutOff = i % 1 != 0 ? TIME_STEP_PEG_LENGTH / 2 : 0; canvas.drawLine(PADDING + i * xStep, height - TIME_AXIS_OFFSET, PADDING + i * xStep, height - TIME_AXIS_OFFSET + TIME_STEP_PEG_LENGTH - cutOff, axisPaint); } canvas.drawLine(0, height - TIME_AXIS_OFFSET, width, height - TIME_AXIS_OFFSET, axisPaint); } /** * Adds vertical line to separate multiple stream file visualizations. */ private void addSeparator() { View separator = new View(getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 4); separator.setLayoutParams(params); separator.setBackgroundColor(getResources().getColor(R.color.colorSeparator)); addView(separator, 1); } }
8,474
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipeOnDragListener.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/PipeOnDragListener.java
/* * PipeOnDragListener.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; import android.view.DragEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ImageView; import java.util.Map; import hcm.ssj.creator.R; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.main.TwoDScrollView; import hcm.ssj.creator.util.Util; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; /** * On drag listener for pipe <br> * Created by Frank on 03.03.2017. */ class PipeOnDragListener implements View.OnDragListener { private final Context context; private ImageView recycleBin; private boolean dropped; private float xCoord, yCoord; private enum Result { NOTHING, PLACED, DELETED, CONNECTED } PipeOnDragListener(Context context) { this.context = context; } /** * @param pipeView PipeView * @param event DragEvent */ private void cleanup(final PipeView pipeView, final DragEvent event) { //remove view from owner ComponentView componentView = (ComponentView) event.getLocalState(); Result result = Result.NOTHING; try { result = handleCollision(pipeView, componentView); } finally { //remove recycle bin ViewParent viewParent = recycleBin.getParent(); if (viewParent != null && viewParent instanceof ViewGroup) { ((ViewGroup) viewParent).removeView(recycleBin); } recycleBin.invalidate(); recycleBin = null; componentView.invalidate(); switch (result) { case NOTHING: break; case PLACED: pipeView.placeElements(); break; case CONNECTED: pipeView.createElements(); pipeView.placeElements(); break; case DELETED: pipeView.createElements(); pipeView.placeElements(); //inform listeners after delay to avoid null pointer exception on tab deletion Handler handler = new Handler(Looper.getMainLooper()); Runnable runnable = new Runnable() { public void run() { pipeView.informListeners(); } }; handler.postDelayed(runnable, 50); break; default: break; } } } /** * @param pipeView PipeView * @param componentView ComponentView * @return Result */ private Result handleCollision(final PipeView pipeView, final ComponentView componentView) { Result result = Result.NOTHING; //check collision Rect rectBin = new Rect(); recycleBin.getHitRect(rectBin); //delete element if (rectBin.contains((int) xCoord, (int) yCoord)) { pipeView.getGrid().setGridValue(componentView.getGridX(), componentView.getGridY(), false); PipelineBuilder.getInstance().remove(componentView.getElement()); if(componentView.getElement() instanceof FeedbackCollection) { openFeedbackCollectionDeleteDialog(pipeView, (FeedbackCollection)componentView.getElement()); } result = Result.DELETED; } //reposition else { int x = pipeView.getGridCoordinate(xCoord); int y = pipeView.getGridCoordinate(yCoord); if (dropped) { if (pipeView.getGrid().isGridFree(x, y)) { //change position pipeView.getGrid().setGridValue(componentView.getGridX(), componentView.getGridY(), false); componentView.setGridX(x); componentView.setGridY(y); pipeView.placeElementView(componentView); result = Result.PLACED; } else { //check for collision to add a connection boolean conn = pipeView.checkCollisionConnection(componentView.getElement(), x, y); if (conn) { result = Result.CONNECTED; } } } pipeView.addView(componentView); } return result; } private void openFeedbackCollectionDeleteDialog(final PipeView pipeView, final FeedbackCollection feedbackCollection) { AlertDialog.Builder builder = new AlertDialog.Builder(this.context); builder.setTitle(R.string.keep_inner_components) .setPositiveButton(R.string.yes, null) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { for(Map<Feedback, FeedbackCollection.LevelBehaviour> levelMap : feedbackCollection.getFeedbackList()) { for(Feedback feedback : levelMap.keySet()) { PipelineBuilder.getInstance().remove(feedback); } } pipeView.recalculate(Util.AppAction.CLEAR, null); pipeView.recalculate(Util.AppAction.DISPLAYED, null); } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } /** * @param pipeView PipeView */ private void createRecycleBin(final PipeView pipeView) { if (recycleBin != null) { ViewGroup parent = ((ViewGroup) recycleBin.getParent()); if (parent != null) { parent.removeView(recycleBin); } recycleBin.invalidate(); recycleBin = null; } recycleBin = new ImageView(pipeView.getContext()); recycleBin.setImageResource(android.R.drawable.ic_menu_delete); // Determine shown width of the view Rect rectSizeDisplayed = new Rect(); pipeView.getGlobalVisibleRect(rectSizeDisplayed); // Determine scroll changes int scrollX = 0, scrollY = 0; ViewParent viewParent = pipeView.getParent(); if (viewParent != null && viewParent instanceof TwoDScrollView) { scrollX = ((TwoDScrollView) viewParent).getScrollX(); scrollY = ((TwoDScrollView) viewParent).getScrollY(); } int height = rectSizeDisplayed.height() + scrollY; int gridBoxSize = pipeView.getGridBoxSize(); // Place recycle bin in the lower left corner of the canvas recycleBin.layout(scrollX, height - (gridBoxSize * 3), scrollX + (gridBoxSize * 3), height); pipeView.addView(recycleBin); } /** * @param v View * @param event DragEvent * @return boolean */ @Override public boolean onDrag(final View v, final DragEvent event) { if (v instanceof PipeView) { final PipeView pipeView = (PipeView) v; switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: { //init values xCoord = 0; yCoord = 0; dropped = false; createRecycleBin(pipeView); break; } case DragEvent.ACTION_DRAG_ENTERED: break; case DragEvent.ACTION_DRAG_EXITED: break; case DragEvent.ACTION_DROP: //update drop location xCoord = event.getX(); yCoord = event.getY(); dropped = true; ComponentView view = (ComponentView) event.getLocalState(); pipeView.getGrid().setGridValue(view.getGridX(), view.getGridY(), false); break; case DragEvent.ACTION_DRAG_ENDED: cleanup(pipeView, event); break; case DragEvent.ACTION_DRAG_LOCATION: { // //@todo add scroll behaviour to drag and drop // HorizontalScrollView horizontalScrollView = (HorizontalScrollView) pipeView.getParent(); // if (horizontalScrollView != null) // { // ScrollView scrollView = (ScrollView) horizontalScrollView.getParent(); // if (scrollView != null) // { // //way one // int y = Math.round(event.getY()); // int translatedY = y - scrollView.getScrollY(); // int threshold = 50; // // make a scrolling up due the y has passed the threshold // if (translatedY < threshold) { // // make a scroll up by 30 px // scrollView.smoothScrollBy(0, -30); // } // // make a autoscrolling down due y has passed the 500 px border // if (translatedY + threshold > 500) { // // make a scroll down by 30 px // scrollView.smoothScrollBy(0, 30); // } // //way two // int topOfDropZone = pipeView.getTop(); // int bottomOfDropZone = pipeView.getBottom(); // int scrollY = scrollView.getScrollY(); // int scrollViewHeight = scrollView.getMeasuredHeight(); // Log.d("location: Scroll Y: " + scrollY + " Scroll Y+Height: " + (scrollY + scrollViewHeight)); // Log.d(" top: " + topOfDropZone + " bottom: " + bottomOfDropZone); // if (bottomOfDropZone > (scrollY + scrollViewHeight - 100)) // { // scrollView.smoothScrollBy(0, 30); // } // if (topOfDropZone < (scrollY + 100)) // { // scrollView.smoothScrollBy(0, -30); // } // } // } break; } default: break; } return true; } return false; } }
12,671
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipeView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/PipeView.java
/* * PipeView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import hcm.ssj.core.Component; import hcm.ssj.core.Consumer; import hcm.ssj.core.Log; import hcm.ssj.core.Provider; import hcm.ssj.core.Sensor; import hcm.ssj.core.SensorChannel; import hcm.ssj.core.Transformer; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.main.TwoDScrollView; import hcm.ssj.creator.util.ConnectionType; import hcm.ssj.creator.util.Util; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.ml.IModelHandler; import hcm.ssj.ml.Model; /** * Draws a pipe<br> * Created by Frank Gaibler on 29.04.2016. */ public class PipeView extends ViewGroup { //layout private final static int PORTRAIT_NUMBER_OF_BOXES = 20; private final static int LANDSCAPE_NUMBER_OF_BOXES = 2 * PORTRAIT_NUMBER_OF_BOXES; //@todo adjust to different screen sizes (e.g. show all boxes on tablet) private final int iGridWidthNumberOfBoxes = 50; //chosen box number private final int iGridHeightNumberOfBoxes = 50; //chosen box number //elements private ArrayList<ComponentView> componentViewsSensor = new ArrayList<>(); private ArrayList<ComponentView> componentViewsSensorChannel = new ArrayList<>(); private ArrayList<ComponentView> componentViewsTransformer = new ArrayList<>(); private ArrayList<ComponentView> componentViewsConsumer = new ArrayList<>(); private ArrayList<ComponentView> componentViewsEventHandler = new ArrayList<>(); private ArrayList<ComponentView> componentViewsModel = new ArrayList<>(); //connections private ArrayList<ConnectionView> streamConnectionViews = new ArrayList<>(); private ArrayList<ConnectionView> eventConnectionViews = new ArrayList<>(); private ArrayList<ConnectionView> modelConnectionViews = new ArrayList<>(); //colors private Paint paintElementGrid; private Paint paintElementShadow; private int iOrientation = Configuration.ORIENTATION_UNDEFINED; //grid private GridLayout gridLayout; private int iGridBoxSize = 0; //box size depends on screen width private int iGridPadWPix = 0; //left and right padding to center grid private int iGridPadHPix = 0; //top and bottom padding to center grid private int iSizeWidth = 0; //draw size width private int iSizeHeight = 0; //draw size height //listeners private HashSet<PipeListener> hsPipeListener = new HashSet<>(); /** * @param context Context */ public PipeView(Context context) { super(context); init(context); } /** * @param context Context * @param attrs AttributeSet */ public PipeView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { Log.i("Init PipeView"); //children should not be clipped setClipToPadding(false); //create grid gridLayout = new GridLayout(iGridWidthNumberOfBoxes, iGridHeightNumberOfBoxes); //add drag listener setOnDragListener(new PipeOnDragListener(context)); //initiate colors paintElementGrid = new Paint(Paint.ANTI_ALIAS_FLAG); paintElementGrid.setStyle(Paint.Style.STROKE); paintElementGrid.setColor(Color.GRAY); // paintElementShadow = new Paint(Paint.ANTI_ALIAS_FLAG); paintElementShadow.setStyle(Paint.Style.FILL); paintElementShadow.setColor(Color.LTGRAY); // TODO: Adjust box count to DPI // DisplayMetrics metrics = getResources().getDisplayMetrics(); // Log.i("Metrics W: " + metrics.widthPixels + " H: " + metrics.heightPixels + " D: " + metrics.density + " DPI: " + metrics.densityDpi + " xDPI: " + metrics.xdpi + " yDPI: " + metrics.ydpi); } /** * @param appAction Util.AppAction * @param o Object */ public final void recalculate(Util.AppAction appAction, Object o) { switch (appAction) { case SAVE: { SaveLoad.save(o, componentViewsSensorChannel, componentViewsSensor, componentViewsTransformer, componentViewsConsumer, componentViewsEventHandler, componentViewsModel); break; } case LOAD: { createElements(); gridLayout.clear(); changeElementPositions(SaveLoad.load(o)); placeElements(); informListeners(); break; } case CLEAR: gridLayout.clear(); //fallthrough case ADD: //fallthrough case DISPLAYED: createElements(); placeElements(); informListeners(); break; default: break; } } /** * Inform listeners about changed components.<br> * Mainly used for informing tab holder about new or deleted painters or writers.<br> */ protected void informListeners() { for (PipeListener pipeListener : hsPipeListener) { pipeListener.viewChanged(); } } /** * @param pipeListener PipeListener */ public final void addViewListener(PipeListener pipeListener) { hsPipeListener.add(pipeListener); } /** * @param pipeListener PipeListener */ public final void removeViewListener(PipeListener pipeListener) { hsPipeListener.remove(pipeListener); } /** * */ protected void createElements() { // clear views removeAllViews(); //add connections streamConnectionViews.clear(); for (int i = 0; i < PipelineBuilder.getInstance().getNumberOfStreamConnections(); i++) { ConnectionView connectionView = new ConnectionView(getContext()); connectionView.setConnectionType(ConnectionType.STREAMCONNECTION); streamConnectionViews.add(connectionView); addView(streamConnectionViews.get(i)); } eventConnectionViews.clear(); for (int i = 0; i < PipelineBuilder.getInstance().getNumberOfEventConnections(); i++) { ConnectionView connectionView = new ConnectionView(getContext()); connectionView.setConnectionType(ConnectionType.EVENTCONNECTION); eventConnectionViews.add(connectionView); addView(eventConnectionViews.get(i)); } modelConnectionViews.clear(); for (int i = 0; i < PipelineBuilder.getInstance().getNumberOfModelConnections(); i++) { ConnectionView connectionView = new ConnectionView(getContext()); connectionView.setConnectionType(ConnectionType.MODELCONNECTION); modelConnectionViews.add(connectionView); addView(modelConnectionViews.get(i)); } //add providers componentViewsSensorChannel = fillList(componentViewsSensorChannel, PipelineBuilder.Type.SensorChannel); //add sensors componentViewsSensor = fillList(componentViewsSensor, PipelineBuilder.Type.Sensor); //add transformers componentViewsTransformer = fillList(componentViewsTransformer, PipelineBuilder.Type.Transformer); //add consumers componentViewsConsumer = fillList(componentViewsConsumer, PipelineBuilder.Type.Consumer); //add eventhandler componentViewsEventHandler = fillList(componentViewsEventHandler, PipelineBuilder.Type.EventHandler); //add models componentViewsModel = fillList(componentViewsModel, PipelineBuilder.Type.Model); } /** * @param alView ArrayList * @param type Linker.Type */ private ArrayList<ComponentView> fillList(ArrayList<ComponentView> alView, PipelineBuilder.Type type) { //get all pipe components of specific type Object[] objects = PipelineBuilder.getInstance().getAll(type); //copy to new list to delete unused components ArrayList<ComponentView> alInterim = new ArrayList<>(); for (Object object : objects) { //check of components already exist in list boolean found = false; for (ComponentView v : alView) { if (v.getElement().equals(object)) { found = true; v.setStreamConnectionHashes(PipelineBuilder.getInstance().getStreamConnectionHashes(object)); v.setEventConnectionHashes(PipelineBuilder.getInstance().getEventConnectionHashes(object)); v.setModelConnectionHashes(PipelineBuilder.getInstance().getModelConnectionHashes(object)); alInterim.add(v); break; } } //create new ComponentView if not if (!found) { ComponentView view = new ComponentView(getContext(), object); view.setStreamConnectionHashes(PipelineBuilder.getInstance().getStreamConnectionHashes(object)); view.setEventConnectionHashes(PipelineBuilder.getInstance().getEventConnectionHashes(object)); view.setModelConnectionHashes(PipelineBuilder.getInstance().getModelConnectionHashes(object)); alInterim.add(view); } } //replace old list alView = alInterim; //add views for (View view : alView) { addView(view); } return alView; } /** * */ protected void placeElements() { //elements int initHeight = 0; int divider = 5; setLayouts(componentViewsSensor, initHeight); initHeight += divider; setLayouts(componentViewsSensorChannel, initHeight); initHeight += divider; setLayouts(componentViewsTransformer, initHeight); initHeight += divider; setLayouts(componentViewsConsumer, initHeight); initHeight += divider; setLayouts(componentViewsEventHandler, initHeight); setLayouts(componentViewsModel, initHeight); //connections for (ConnectionView connectionView : streamConnectionViews) { connectionView.layout(0, 0, iSizeWidth, iSizeHeight); } for (ConnectionView connectionView : eventConnectionViews) { connectionView.layout(0, 0, iSizeWidth, iSizeHeight); } for (ConnectionView connectionView : modelConnectionViews) { connectionView.layout(0, 0, iSizeWidth, iSizeHeight); } int streamConnections = 0; int eventConnections = 0; int modelConnections = 0; for (ComponentView componentViewSensor : componentViewsSensor) { int[] streamHashes = componentViewSensor.getStreamConnectionHashes(); streamConnections = checkStreamConnections(streamHashes, streamConnections, componentViewSensor, componentViewsSensorChannel, false); int[] eventHashes = componentViewSensor.getEventConnectionHashes(); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensor, componentViewsSensor, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensor, componentViewsSensorChannel, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensor, componentViewsTransformer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensor, componentViewsConsumer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensor, componentViewsEventHandler, true); } for (ComponentView componentViewSensorChannel : componentViewsSensorChannel) { int[] eventHashes = componentViewSensorChannel.getEventConnectionHashes(); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensorChannel, componentViewsSensor, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensorChannel, componentViewsSensorChannel, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensorChannel, componentViewsTransformer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensorChannel, componentViewsConsumer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewSensorChannel, componentViewsEventHandler, true); } for (ComponentView componentViewTransformer : componentViewsTransformer) { int[] streamHashes = componentViewTransformer.getStreamConnectionHashes(); streamConnections = checkStreamConnections(streamHashes, streamConnections, componentViewTransformer, componentViewsSensorChannel, true); streamConnections = checkStreamConnections(streamHashes, streamConnections, componentViewTransformer, componentViewsTransformer, true); int[] eventHashes = componentViewTransformer.getEventConnectionHashes(); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewTransformer, componentViewsSensor, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewTransformer, componentViewsSensorChannel, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewTransformer, componentViewsTransformer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewTransformer, componentViewsConsumer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewTransformer, componentViewsEventHandler, true); } for (ComponentView componentViewConsumer : componentViewsConsumer) { int[] streamHashes = componentViewConsumer.getStreamConnectionHashes(); streamConnections = checkStreamConnections(streamHashes, streamConnections, componentViewConsumer, componentViewsSensorChannel, true); streamConnections = checkStreamConnections(streamHashes, streamConnections, componentViewConsumer, componentViewsTransformer, true); int[] eventHashes = componentViewConsumer.getEventConnectionHashes(); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewConsumer, componentViewsSensor, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewConsumer, componentViewsSensorChannel, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewConsumer, componentViewsTransformer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewConsumer, componentViewsConsumer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewConsumer, componentViewsEventHandler, true); } for (ComponentView componentViewEventHandler : componentViewsEventHandler) { int[] eventHashes = componentViewEventHandler.getEventConnectionHashes(); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewEventHandler, componentViewsSensor, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewEventHandler, componentViewsSensorChannel, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewEventHandler, componentViewsTransformer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewEventHandler, componentViewsConsumer, true); eventConnections = checkEventConnections(eventHashes, eventConnections, componentViewEventHandler, componentViewsEventHandler, true); } for (ComponentView componentViewModel : componentViewsModel) { int[] connectionHashes = componentViewModel.getModelConnectionHashes(); modelConnections = checkModelConnections(connectionHashes, modelConnections, componentViewModel, componentViewsSensor); modelConnections = checkModelConnections(connectionHashes, modelConnections, componentViewModel, componentViewsSensorChannel); modelConnections = checkModelConnections(connectionHashes, modelConnections, componentViewModel, componentViewsTransformer); modelConnections = checkModelConnections(connectionHashes, modelConnections, componentViewModel, componentViewsConsumer); modelConnections = checkModelConnections(connectionHashes, modelConnections, componentViewModel, componentViewsEventHandler); } } /** * @param alPoints ArrayList<Point */ private void changeElementPositions(ArrayList<Point> alPoints) { if (alPoints != null) { int count = 0; count = changeElementPositions(alPoints, componentViewsSensorChannel, count); count = changeElementPositions(alPoints, componentViewsSensor, count); count = changeElementPositions(alPoints, componentViewsTransformer, count); count = changeElementPositions(alPoints, componentViewsConsumer, count); count = changeElementPositions(alPoints, componentViewsEventHandler, count); changeElementPositions(alPoints, componentViewsModel, count); } } /** * @param alPoints ArrayList<Point> * @param alComponentView ArrayList<ComponentView> * @param count int */ private int changeElementPositions(ArrayList<Point> alPoints, ArrayList<ComponentView> alComponentView, int count) { for (int i = 0; i < alComponentView.size() && count < alPoints.size(); i++, count++) { alComponentView.get(i).setGridX(alPoints.get(count).x); alComponentView.get(i).setGridY(alPoints.get(count).y); } return count; } /** * @param hashes int[] * @param connections int * @param destination View * @param componentViews ArrayList * @param standardOrientation boolean * @return int */ private int checkStreamConnections(int[] hashes, int connections, ComponentView destination, ArrayList<ComponentView> componentViews, boolean standardOrientation) { if (hashes != null) { for (int hash : hashes) { for (ComponentView componentView : componentViews) { if (hash == componentView.getElementHash()) { ConnectionView connectionView = streamConnectionViews.get(connections); //arrow from child to parent (e.g. transformer to consumer) if (standardOrientation) { connectionView.drawConnectionViews(componentView, destination, iGridBoxSize); connectionView.invalidate(); } else //arrow from parent to child (e.g. sensor to sensorChannel) { connectionView.drawConnectionViews(destination, componentView, iGridBoxSize); connectionView.invalidate(); } connections++; break; } } } } return connections; } /** * @param hashes int[] * @param connections int * @param destination View * @param componentViews ArrayList * @param standardOrientation boolean * @return int */ private int checkEventConnections(int[] hashes, int connections, ComponentView destination, ArrayList<ComponentView> componentViews, boolean standardOrientation) { if(destination.getElement() instanceof Feedback && PipelineBuilder.getInstance().isManagedFeedback(destination.getElement())) { return connections; } if (hashes != null) { for (int hash : hashes) { for (ComponentView componentView : componentViews) { if (hash == componentView.getElementHash()) { ConnectionView connectionView = eventConnectionViews.get(connections); //arrow from child to parent (e.g. transformer to consumer) if (standardOrientation) { connectionView.drawConnectionViews(componentView, destination, iGridBoxSize); connectionView.invalidate(); } else //arrow from parent to child (e.g. sensor to sensorChannel) { connectionView.drawConnectionViews(destination, componentView, iGridBoxSize); connectionView.invalidate(); } connections++; if(PipelineBuilder.getInstance().isManagedFeedback(componentView.getElement())) { connectionView.setVisibility(GONE); } else { setVisibility(VISIBLE); } break; } } } } return connections; } /** * @param hashes int[] * @param connections int * @param destination View * @param componentViews ArrayList * @return int */ private int checkModelConnections(int[] hashes, int connections, ComponentView destination, ArrayList<ComponentView> componentViews) { if (hashes != null) { for (int hash : hashes) { for (ComponentView componentView : componentViews) { if (hash == componentView.getElementHash()) { ConnectionView connectionView = modelConnectionViews.get(connections); connectionView.drawConnectionViews(componentView, destination, iGridBoxSize); connectionView.invalidate(); connections++; break; } } } } return connections; } /** * @param views ArrayList * @param initHeight int */ private void setLayouts(ArrayList<ComponentView> views, int initHeight) { for (ComponentView view : views) { // Prevent managed feedback to be drawn if(view.getElement() instanceof Feedback) { if(PipelineBuilder.getInstance().isManagedFeedback(view.getElement())) { view.setVisibility(GONE); continue; } else { view.setVisibility(VISIBLE); } } if (view.isPositioned()) { placeElementView(view); } else { boolean placed = false; //place elements as chess grid for (int j = initHeight; !placed && j < iGridHeightNumberOfBoxes; j += 2) { for (int i = j % 2; !placed && i < iGridWidthNumberOfBoxes; i += 4) { if (gridLayout.isGridFree(i, j)) { view.setGridX(i); view.setGridY(j); placeElementView(view); placed = true; } } } //try from zero if placement didn't work for (int j = 0; !placed && j < iGridHeightNumberOfBoxes && j < initHeight; j++) { for (int i = 0; !placed && i < iGridWidthNumberOfBoxes; i++) { if (gridLayout.isGridFree(i, j)) { view.setGridX(i); view.setGridY(j); placeElementView(view); placed = true; } } } if (!placed) { Log.e("Too many elements in view. Could not place all."); } } } } /** * @param view ElementView */ protected void placeElementView(ComponentView view) { gridLayout.setGridValue(view.getGridX(), view.getGridY(), true); int xPos = view.getGridX() * iGridBoxSize + iGridPadWPix; int yPos = view.getGridY() * iGridBoxSize + iGridPadHPix; int componentSize = iGridBoxSize * 2; view.layout(xPos, yPos, xPos + componentSize, yPos + componentSize); } /** * @return int */ protected int getGridBoxSize() { return iGridBoxSize; } /** * Translates one pixel axis position to grid coordinate * * @param pos float * @return int */ protected int getGridCoordinate(float pos) { int i = (int) (pos / iGridBoxSize + 0.5f) - 1; return i < 0 ? 0 : i; } /** * @param object Object * @param x int * @param y int * @return boolean */ protected boolean checkCollisionConnection(Object object, int x, int y) { boolean result; if (object instanceof Sensor) { result = addCollisionConnection(object, x, y, componentViewsSensorChannel, false); } else { result = addCollisionConnection(object, x, y, componentViewsSensorChannel, true); } if (!result && object instanceof IModelHandler) { result = addCollisionConnection(object, x, y, componentViewsModel, true); } if (!result) { result = addCollisionConnection(object, x, y, componentViewsSensor, true); } if (!result) { result = addCollisionConnection(object, x, y, componentViewsTransformer, true); } if (!result) { result = addCollisionConnection(object, x, y, componentViewsConsumer, true); } if (!result) { result = addCollisionConnection(object, x, y, componentViewsEventHandler, true); } return result; } /** * @param object Object * @param x int * @param y int * @param componentViews ArrayList * @param standard boolean * @return boolean */ private boolean addCollisionConnection(Object object, int x, int y, ArrayList<ComponentView> componentViews, boolean standard) { for (ComponentView componentView : componentViews) { int colX = componentView.getGridX(); int colY = componentView.getGridY(); if ((colX == x || colX == x - 1 || colX == x + 1) && (colY == y || colY == y - 1 || colY == y + 1)) { if(object instanceof Feedback && componentView.getElement() instanceof FeedbackCollection) { PipelineBuilder.getInstance().addFeedbackToCollectionContainer( (FeedbackCollection) componentView.getElement(), (Feedback)object, 0, FeedbackCollection.LevelBehaviour.Neutral); // Unposition managed feedback for (ComponentView view : componentViewsEventHandler) { if(view.getElement().equals(object)) { view.setGridX(-1); view.setGridY(-1); } } this.informListeners(); } else if (isValidConnection((Component) object, (Component) componentView.getElement(), ConnectionType.STREAMCONNECTION)) { if (standard) { PipelineBuilder.getInstance().addStreamConnection(componentView.getElement(), (Provider) object); } else { PipelineBuilder.getInstance().addStreamConnection(object, (Provider) componentView.getElement()); } } else if (isValidConnection((Component) object, (Component) componentView.getElement(), ConnectionType.MODELCONNECTION)) { PipelineBuilder.getInstance().addModelConnection((Component) object, (Component) componentView.getElement()); } else if (isValidConnection((Component) object, (Component) componentView.getElement(), ConnectionType.EVENTCONNECTION)) { PipelineBuilder.getInstance().addEventConnection(componentView.getElement(), (Component) object); } return true; } } return false; } /** * @return GridLayout */ protected GridLayout getGrid() { return gridLayout; } /** * @param canvas Canvas */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); calculateLayout(); int left = iGridPadWPix; int right = iSizeWidth - iGridPadWPix; int top = iGridPadHPix; int bottom = iSizeHeight - iGridPadHPix; for (int i = 0; i < iGridWidthNumberOfBoxes + 1; i++) { canvas.drawLine(iGridPadWPix + i * iGridBoxSize, top, iGridPadWPix + i * iGridBoxSize, bottom, paintElementGrid); } for (int i = 0; i < iGridHeightNumberOfBoxes + 1; i++) { canvas.drawLine(left, iGridPadHPix + i * iGridBoxSize, right, iGridPadHPix + i * iGridBoxSize, paintElementGrid); } for (int i = 0; i < gridLayout.getWidth(); i++) { for (int j = 0; j < gridLayout.getHeight(); j++) { if (gridLayout.getValue(i, j)) { float xS = iGridBoxSize * i + iGridPadWPix; float yS = iGridBoxSize * j + iGridPadHPix; float xE = iGridBoxSize * i + iGridPadWPix + iGridBoxSize; float yE = iGridBoxSize * j + iGridPadHPix + iGridBoxSize; canvas.drawRect(xS, yS, xE, yE, paintElementShadow); } } } canvas.restore(); } /** * @param w int * @param h int * @param oldw int * @param oldh int */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { invalidate(); } } /** * @param changed boolean * @param l int * @param t int * @param r int * @param b int */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // Log.i("OnLayout l: " + l + " t: " + t + " r: " + r + " b: " + b + " " + System.currentTimeMillis()); } private void calculateLayout() { int orientation = getResources().getConfiguration().orientation; // Only change grid box size on orientation change if (iOrientation != orientation) { iOrientation = orientation; // Reset scroll ViewParent viewParent = getParent(); if (viewParent != null && viewParent instanceof TwoDScrollView) { ((TwoDScrollView) viewParent).setScrollX(0); ((TwoDScrollView) viewParent).setScrollY(0); } // Get displayed screen size Rect rectSizeDisplayed = new Rect(); getGlobalVisibleRect(rectSizeDisplayed); int width = rectSizeDisplayed.width(); int height = rectSizeDisplayed.height(); // Log.i("Width: " + width + " Height: " + height + " " + System.currentTimeMillis()); iGridBoxSize = width > height ? height / PORTRAIT_NUMBER_OF_BOXES : width / PORTRAIT_NUMBER_OF_BOXES; if (iGridBoxSize <= 0) { iGridBoxSize = 50; } calcDerivedSizes(width, height); //check if display wouldn't be filled if (iSizeWidth < width) { iGridBoxSize = width / (iGridWidthNumberOfBoxes); } else if (iSizeHeight < height) { iGridBoxSize = height / (iGridHeightNumberOfBoxes); } calcDerivedSizes(width, height); //set size in handler to force correct size and scroll view behaviour Handler handler = new Handler(Looper.getMainLooper()); Runnable runnable = new Runnable() { public void run() { setMinimumHeight(iSizeHeight); setMinimumWidth(iSizeWidth); //place elements anew placeElements(); } }; handler.postDelayed(runnable, 50); } } /** * @param width int * @param height int */ private void calcDerivedSizes(int width, int height) { iGridPadWPix = width % iGridBoxSize / 2; iGridPadHPix = height % iGridBoxSize / 2; iSizeWidth = iGridBoxSize * iGridWidthNumberOfBoxes + (2 * iGridPadWPix); iSizeHeight = iGridBoxSize * iGridHeightNumberOfBoxes + (2 * iGridPadHPix); } @Override public boolean onInterceptTouchEvent(MotionEvent motionEvent) { boolean returnValue = false; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child instanceof ComponentView) { // Check if motionEvent occured on CompontenView if (motionEvent.getX() >= child.getX() && motionEvent.getX() <= child.getX() + child.getWidth() && motionEvent.getY() >= child.getY() && motionEvent.getY() <= child.getY() + child.getHeight()) { return false; } } } List<ConnectionView> connectionViewList = new ArrayList<>(); connectionViewList.addAll(streamConnectionViews); connectionViewList.addAll(eventConnectionViews); for (ConnectionView connectionView : connectionViewList) { if (connectionView.isOnPath(motionEvent)) { toggleConnectionType(connectionView); returnValue = true; } } return returnValue; } private void toggleConnectionType(ConnectionView connectionView) { ComponentView start = connectionView.getStartComponentView(); ComponentView destination = connectionView.getDestinationComponentView(); if (start == null || destination == null) { return; } Component startComponent = PipelineBuilder.getInstance().getComponentForHash(start.getElementHash()); Component destinationComponent = PipelineBuilder.getInstance().getComponentForHash(destination.getElementHash()); // Check if the toggled connection would be valid. if (!isValidConnection(startComponent, destinationComponent, connectionView.getConnectionType() == ConnectionType.EVENTCONNECTION ? ConnectionType.STREAMCONNECTION : ConnectionType.EVENTCONNECTION)) { return; } //Swap start and destination if sensor is involved, because then it's drawn the other way round. switch (connectionView.getConnectionType()) { case STREAMCONNECTION: if (startComponent instanceof Sensor) { PipelineBuilder.getInstance().removeStreamConnection(startComponent, (Provider) destinationComponent); } else { PipelineBuilder.getInstance().removeStreamConnection(destinationComponent, (Provider) startComponent); } PipelineBuilder.getInstance().addEventConnection(destinationComponent, startComponent); break; case EVENTCONNECTION: PipelineBuilder.getInstance().removeEventConnection(destinationComponent, startComponent); if (startComponent instanceof Sensor) { PipelineBuilder.getInstance().addStreamConnection(startComponent, (Provider) destinationComponent); } else { PipelineBuilder.getInstance().addStreamConnection(destinationComponent, (Provider) startComponent); } break; default: throw new RuntimeException(); } this.recalculate(Util.AppAction.DISPLAYED, null); } public static boolean isValidConnection(Component src, Component dst, ConnectionType type) { if (type == ConnectionType.EVENTCONNECTION && !(src instanceof Model)) { return true; } if (type == ConnectionType.MODELCONNECTION && ((src instanceof Model && dst instanceof IModelHandler) || (src instanceof IModelHandler && dst instanceof Model))) { return true; } if (src instanceof Sensor && dst instanceof SensorChannel) { return true; } if (src instanceof SensorChannel && (dst instanceof Transformer || dst instanceof Consumer)) { return true; } if (src instanceof Transformer && (dst instanceof Transformer || dst instanceof Consumer)) { return true; } return false; } }
34,303
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
GridLayout.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/GridLayout.java
/* * GridLayout.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import java.util.Arrays; /** * Grid layout for pipe <br> * Created by Frank on 03.03.2017. */ class GridLayout { private final boolean[][] grid; GridLayout(int width, int height) { grid = new boolean[width][height]; } /** * @return int */ int getWidth() { return grid.length; } /** * @return int */ int getHeight() { return grid[0].length; } /** * @param x int * @param y int * @return boolean */ boolean getValue(int x, int y) { return grid[x][y]; } /** * Checks free grid from top left corner * * @param x int * @param y int * @return boolean */ boolean isGridFree(int x, int y) { //check for valid input return x + 1 < grid.length && y + 1 < grid[0].length && //check grid !grid[x][y] && !grid[x + 1][y] && !grid[x][y + 1] && !grid[x + 1][y + 1]; } /** * @param x int * @param y int * @param placed boolean */ void setGridValue(int x, int y, boolean placed) { //check for valid input if (x>= 0 && x + 1 < grid.length && y >= 0 && y + 1 < grid[0].length) { grid[x][y] = placed; grid[x + 1][y] = placed; grid[x][y + 1] = placed; grid[x + 1][y + 1] = placed; } } /** * */ void clear() { for (boolean[] booleans : grid) { Arrays.fill(booleans, false); } } }
2,966
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SaveLoad.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/SaveLoad.java
/* * SaveLoad.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.graphics.Point; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import hcm.ssj.core.Log; import hcm.ssj.creator.util.Util; /** * Save and load files for {@link hcm.ssj.creator.view.PipeView} placements.<br> * Created by Frank Gaibler on 15.03.2017. */ abstract class SaveLoad { private final static String SUFFIX = ".layout"; private final static String ROOT = "ssjCreator"; private final static String PIPE_GROUP = "pipeLayout"; private final static String NAME = "name"; private final static String VERSION = "version"; private final static String VERSION_NUMBER = "1"; private final static String COMPONENT = "component"; private final static String X = "X"; private final static String Y = "Y"; /** * @param o Object * @param providers ArrayList<ComponentView> * @param sensors ArrayList<ComponentView> * @param transformers ArrayList<ComponentView> * @param consumers ArrayList<ComponentView> * @return boolean */ static boolean save(Object o, ArrayList<ComponentView> providers, ArrayList<ComponentView> sensors, ArrayList<ComponentView> transformers, ArrayList<ComponentView> consumers, ArrayList<ComponentView> eventHandlers, ArrayList<ComponentView> models) { File fileOrig = (File) o; File file = new File(fileOrig.getParentFile().getPath(), fileOrig.getName().replace(Util.SUFFIX, "") + SUFFIX); try { file.createNewFile(); } catch (IOException ex) { Log.e("could not create file"); return false; } //open stream FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(file); } catch (FileNotFoundException e) { Log.e("file not found"); return false; } XmlSerializer serializer = Xml.newSerializer(); try { //start document serializer.setOutput(fileOutputStream, "UTF-8"); serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, ROOT); serializer.attribute(null, VERSION, VERSION_NUMBER); //pipe layout serializer.startTag(null, PIPE_GROUP); //sensorChannels for (ComponentView componentView : providers) { addComponentView(serializer, componentView); } //sensors for (ComponentView componentView : sensors) { addComponentView(serializer, componentView); } //transformers for (ComponentView componentView : transformers) { addComponentView(serializer, componentView); } //consumers for (ComponentView componentView : consumers) { addComponentView(serializer, componentView); } //eventHandlers for (ComponentView componentView : eventHandlers) { addComponentView(serializer, componentView); } //models for (ComponentView componentView : models) { addComponentView(serializer, componentView); } serializer.endTag(null, PIPE_GROUP); //finish document serializer.endTag(null, ROOT); serializer.endDocument(); serializer.flush(); } catch (IOException ex) { Log.e("could not save file"); return false; } finally { try { fileOutputStream.close(); } catch (IOException ex) { Log.e("could not close stream"); } } return true; } /** * @param o Object * @return ArrayList */ static ArrayList<Point> load(Object o) { File fileOrig = (File) o; File file = new File(fileOrig.getParentFile().getPath(), fileOrig.getName().replace(Util.SUFFIX, "") + SUFFIX); if (!file.exists()) { return null; } FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { Log.e("file not found"); return null; } return load(fileInputStream); } /** * @param fileInputStream FileInputStream * @return ArrayList */ static ArrayList<Point> load(FileInputStream fileInputStream) { try { //check file version XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(fileInputStream, null); parser.nextTag(); if (parser.getName().equals(ROOT)) { String value = parser.getAttributeValue(null, VERSION); if (!value.equals(VERSION_NUMBER)) { return null; } } else { return null; } //load classes parser.nextTag(); String tag; ArrayList<Point> alPoints = new ArrayList<>(); while (!(tag = parser.getName()).equals(ROOT)) { if (parser.getEventType() == XmlPullParser.START_TAG) { switch (tag) { case COMPONENT: { String x = parser.getAttributeValue(null, X); String y = parser.getAttributeValue(null, Y); alPoints.add(new Point(Integer.valueOf(x), Integer.valueOf(y))); break; } } } parser.nextTag(); } return alPoints; } catch (IOException | XmlPullParserException ex) { Log.e("could not parse file", ex); return null; } finally { try { fileInputStream.close(); } catch (IOException ex) { Log.e("could not close stream", ex); } } } /** * @param serializer XmlSerializer * @param componentView ComponentView */ private static void addComponentView(XmlSerializer serializer, ComponentView componentView) throws IOException { serializer.startTag(null, COMPONENT); serializer.attribute(null, X, String.valueOf(componentView.getGridX())); serializer.attribute(null, Y, String.valueOf(componentView.getGridY())); serializer.endTag(null, COMPONENT); } }
8,811
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
WaveformView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/WaveformView.java
/* * WaveformView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import hcm.ssj.audio.AudioUtils; import hcm.ssj.creator.R; /** * View that draws audio file waveform. */ public class WaveformView extends View { private static final boolean ENABLE_ANTI_ALIAS = true; private static final float STROKE_THICKNESS = 4; private static final int LAYOUT_HEIGHT = 350; private static final int LAYOUT_MARGIN_TOP = 20; private static final int LAYOUT_MARGIN_BOTTOM = 20; private static final int LAYOUT_MARGIN_LEFT = 25; private static final int LAYOUT_MARGIN_RIGHT = 0; private Paint strokePaint; private Paint fillPaint; private Rect drawRect; private int width; private int height; private int audioLength; private float scalingFactor = 1; private short[] samples; private Bitmap waveformBitmap; public WaveformView(Context context) { super(context); init(null, 0); } public WaveformView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public WaveformView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } /** * Sets samples that are used to draw the waveform and draws the waveform based on samples given. * @param s The result of {@link hcm.ssj.audio.AudioDecoder#getSamples()} */ public void setSamples(short[] s) { samples = s; createWaveform(); } /** * Sets the length of the audio file to visualize. * @param length The length of the audio file that this WaveformView is visualizing. */ public void setAudioLength(int length) { audioLength = length; } /** * Returns the length of the audio file that this WaveformView is visualizing. * @return Length of the audio file in milliseconds. */ public int getAudioLength() { return audioLength; } /** * Rescales the width of this WaveformView according to the given factor. * The new width is calculated as a product of old width and a given scaling factor, thereafter * the view is redrawn for the changes to take effect. * @param factor Factor to scale the width of WaveformView by. Should be bigger than 0 and less * than 1. */ public void setWidthScale(float factor) { scalingFactor = factor; rescale(); invalidate(); } @Override protected void onSizeChanged(int w, int h, int oldW, int oldH) { width = getMeasuredWidth(); height = getMeasuredHeight(); rescale(); createWaveform(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (waveformBitmap != null) { canvas.drawBitmap(waveformBitmap, null, drawRect, null); } } /** * Shrinks the width of this WaveformView according to scaling factor. */ private void rescale() { int newWidth = (int) (width * scalingFactor); drawRect = new Rect(getPaddingLeft(), getPaddingTop(), newWidth - getPaddingLeft() - getPaddingRight(), height - getPaddingTop() - getPaddingBottom()); } /** * Reads XML attribute values of WaveformView and initializes colors. * @param attrs Set of XML attributes for customization options. * @param defStyle Integer which represents the default style. */ private void init(AttributeSet attrs, int defStyle) { final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.WaveformView, defStyle, 0); int strokeColor = getResources().getColor(R.color.colorWaveform); int fillColor = getResources().getColor(R.color.colorWaveformFill); a.recycle(); strokePaint = new Paint(); strokePaint.setColor(strokeColor); strokePaint.setStyle(Paint.Style.STROKE); strokePaint.setStrokeWidth(STROKE_THICKNESS); strokePaint.setAntiAlias(ENABLE_ANTI_ALIAS); fillPaint = new Paint(); fillPaint.setStyle(Paint.Style.FILL); fillPaint.setAntiAlias(ENABLE_ANTI_ALIAS); fillPaint.setColor(fillColor); drawRect = new Rect(0, 0, width, height); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LAYOUT_HEIGHT); layoutParams.setMargins(LAYOUT_MARGIN_LEFT, LAYOUT_MARGIN_TOP, LAYOUT_MARGIN_RIGHT, LAYOUT_MARGIN_BOTTOM); setLayoutParams(layoutParams); } /** * Shows audio waveform on screen. */ private void createWaveform() { if (width <= 0 || height <= 0 || samples == null) { return; } Canvas canvas; waveformBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); canvas = new Canvas(waveformBitmap); Path waveformPath = drawWaveform(width, height, samples); canvas.drawPath(waveformPath, fillPaint); canvas.drawPath(waveformPath, strokePaint); invalidate(); } /** * Draws waveform as a line path from given audio samples. * @param width Width of view. * @param height Height of view. * @param buffer Audio samples. * @return Waveform path. */ private Path drawWaveform(int width, int height, short[] buffer) { Path waveformPath = new Path(); float centerY = height / 2.0f; float max = Short.MAX_VALUE; short[][] extremes = AudioUtils.getExtremes(buffer, width); // Start path at the origin. waveformPath.moveTo(0, centerY); // Draw maximums. for (int x = 0; x < width; x++) { short sample = extremes[x][0]; float y = centerY - ((sample / max) * centerY); waveformPath.lineTo(x, y); } // Draw minimums. for (int x = width - 1; x >= 0; x--) { short sample = extremes[x][1]; float y = centerY - ((sample / max) * centerY); waveformPath.lineTo(x, y); } waveformPath.close(); return waveformPath; } }
7,223
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ConnectionView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/ConnectionView.java
/* * ConnectionView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import hcm.ssj.creator.util.ConnectionType; /** * Draws connections between elements. Directions are shown with an arrow.<br> * Created by Frank Gaibler on 12.05.2016. */ public class ConnectionView extends View { private final static float STROKE_WIDTH = 2.0f; private final static int ARROW_ANGLE = 35; private final static int HITBOX_FACTOR = 5; private static Bitmap intersectionBitmap; private static Canvas intersectionCanvas; private Paint paintConnection; private Path path; private ConnectionType connectionType; private ComponentView startComponentView; private ComponentView destinationComponentView; /** * @param context Context */ public ConnectionView(Context context) { super(context); if (paintConnection == null) { DisplayMetrics dm = getResources().getDisplayMetrics(); float strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, STROKE_WIDTH, dm); paintConnection = new Paint(Paint.ANTI_ALIAS_FLAG); paintConnection.setStyle(Paint.Style.STROKE); paintConnection.setStrokeWidth(strokeWidth); } } public ConnectionType getConnectionType() { return connectionType; } public void setConnectionType(ConnectionType connectionType) { this.connectionType = connectionType; // PathEffect paintConnection.setPathEffect(connectionType.getPathEffect()); //Color paintConnection.setColor(getResources().getColor(connectionType.getColor())); } public ComponentView getStartComponentView() { return startComponentView; } public ComponentView getDestinationComponentView() { return destinationComponentView; } protected void drawConnectionViews(ComponentView start, ComponentView destination, final int boxSize) { this.startComponentView = start; this.destinationComponentView = destination; setLine(destinationComponentView.getX(), destinationComponentView.getY(), startComponentView.getX(), startComponentView.getY(), boxSize, connectionType == ConnectionType.EVENTCONNECTION, connectionType != ConnectionType.MODELCONNECTION); } /** * @param stopX float * @param stopY float * @param startX float * @param startY float * @param boxSize int */ private void setLine(float stopX, float stopY, float startX, float startY, final int boxSize, boolean curved, boolean arrow) { //calc triangle int arrowLength = (int) (boxSize / 1.42f + 0.5f); double triangleA = arrowLength * Math.cos(Math.toRadians(90 - ARROW_ANGLE)); double triangleB = Math.sqrt(Math.pow(arrowLength, 2) - Math.pow(triangleA, 2)); double triangleAlpha = Math.toRadians(ARROW_ANGLE); //draw line //start and end are in the middle of the element box stopX += boxSize; stopY += boxSize; startX += boxSize; startY += boxSize; path = new Path(); //direction float dx = stopX - startX; float dy = stopY - startY; double theta = Math.atan2(dy, dx); //get middle of line double middleX = (stopX + startX) / 2; double middleY = (stopY + startY) / 2; path.moveTo(stopX, stopY); // Draw connection as a curve if it's a event connection if (curved) { float vLength = (float) Math.sqrt(dx * dx + dy * dy); float normX = (dx / vLength) * boxSize * 2.0f; float normY = (dy / vLength) * boxSize * 2.0f; path.quadTo((float) (normY + middleX), (float) (-normX + middleY), startX, startY); middleX += (normY / 2.0); middleY += (-normX / 2.0); } else { path.lineTo(startX, startY); } //draw arrow if(arrow) { //position arrow in the middle middleX += triangleB / 2 * Math.cos(theta); middleY += triangleB / 2 * Math.sin(theta); //draw first line double x = middleX - arrowLength * Math.cos(theta + triangleAlpha); double y = middleY - arrowLength * Math.sin(theta + triangleAlpha); path.moveTo((float) middleX, (float) middleY); path.lineTo((float) x, (float) y); //draw second line double x2 = middleX - arrowLength * Math.cos(theta - triangleAlpha); double y2 = middleY - arrowLength * Math.sin(theta - triangleAlpha); path.moveTo((float) middleX, (float) middleY); path.lineTo((float) x2, (float) y2); } } /** * @param canvas Canvas */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); if (path != null) { canvas.drawPath(path, paintConnection); } canvas.restore(); } /** * Checks if the motionEvent is on the drawn hidden bitmap. * * @param motionEvent MotionEvent * @return Motion event is on path. */ protected boolean isOnPath(MotionEvent motionEvent) { if (path == null) { return false; } // Create intersection bitmap and canvas if not yet done. if (intersectionBitmap == null || intersectionCanvas == null) { intersectionBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.RGB_565); intersectionCanvas = new Canvas(intersectionBitmap); } // Fill bitmap with white. ("reset") intersectionBitmap.eraseColor(Color.WHITE); // Draw with higher strokewith in a hidden bitmap. ConnectionType oldType = connectionType; setConnectionType(ConnectionType.STREAMCONNECTION); paintConnection.setStrokeWidth(paintConnection.getStrokeWidth() * HITBOX_FACTOR); intersectionCanvas.drawPath(path, paintConnection); paintConnection.setStrokeWidth(paintConnection.getStrokeWidth() / HITBOX_FACTOR); setConnectionType(oldType); // Get color of the touched point and check whether it's WHITE or not. int touchPointColor = intersectionBitmap.getPixel((int) motionEvent.getX(), (int) motionEvent.getY()); return touchPointColor != Color.WHITE; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { // set intersectionBitmap and -Canvas to null, to have them reinstantiated on resize intersectionBitmap = null; intersectionCanvas = null; } }
7,535
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackListener.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/Feedback/FeedbackListener.java
/* * FeedbackListener.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view.Feedback; /** * Created by Antonio Grieco on 05.10.2017. */ public interface FeedbackListener { void onComponentAdded(); }
1,511
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackComponentView.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/Feedback/FeedbackComponentView.java
/* * FeedbackComponentView.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view.Feedback; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipDescription; import android.content.DialogInterface; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import androidx.annotation.IdRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import java.util.Arrays; import java.util.Map; import hcm.ssj.creator.R; import hcm.ssj.creator.activity.FeedbackCollectionActivity; import hcm.ssj.creator.view.ComponentView; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; /** * Created by Antonio Grieco on 04.10.2017. */ public class FeedbackComponentView extends ComponentView { private final FeedbackCollectionActivity feedbackCollectionActivity; private final float TRIANGLE_OFFSET_FACTOR = 0.05f; private final float TRIANGLE_HEIGHT_FACTOR = 0.15f; private Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry; private Paint levelBehaviourPaint; private Paint dragBoxPaint; private Path topTriangleArrow; private Path bottomTriangleArrow; private boolean currentlyDraged = false; public FeedbackComponentView(FeedbackCollectionActivity feedbackCollectionActivity, Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry) { super(feedbackCollectionActivity, feedbackLevelBehaviourEntry.getKey()); this.feedbackCollectionActivity = feedbackCollectionActivity; this.feedbackLevelBehaviourEntry = feedbackLevelBehaviourEntry; initListeners(); initPaints(); } private void initListeners() { OnLongClickListener onTouchListener = new OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item("DragEvent"); ClipData dragData = new ClipData("DragEvent", new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item); DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v); v.startDrag(dragData, shadowBuilder, v, 0); ((FeedbackComponentView) v).setCurrentlyDraged(true); return true; } }; this.setOnLongClickListener(onTouchListener); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openLevelBehaviourDialog(); } }); } private void initPaints() { dragBoxPaint = new Paint(Paint.ANTI_ALIAS_FLAG); dragBoxPaint.setStyle(Paint.Style.FILL); dragBoxPaint.setColor(Color.DKGRAY); levelBehaviourPaint = new Paint(Paint.ANTI_ALIAS_FLAG); levelBehaviourPaint.setStyle(Paint.Style.FILL); levelBehaviourPaint.setStrokeWidth(10); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (!changed) { return; } initTriangleArrows(); } private void initTriangleArrows() { if (topTriangleArrow == null) { topTriangleArrow = new Path(); } else { topTriangleArrow.rewind(); } topTriangleArrow.moveTo(0, 0); topTriangleArrow.lineTo(getWidth(), 0); topTriangleArrow.lineTo(getWidth() / 2, -getHeight() * TRIANGLE_HEIGHT_FACTOR); topTriangleArrow.offset(0, -getHeight() * TRIANGLE_OFFSET_FACTOR); if (bottomTriangleArrow == null) { bottomTriangleArrow = new Path(); } else { bottomTriangleArrow.rewind(); } bottomTriangleArrow.moveTo(0, getHeight()); bottomTriangleArrow.lineTo(getWidth(), getHeight()); bottomTriangleArrow.lineTo(getWidth() / 2, getHeight() + getHeight() * TRIANGLE_HEIGHT_FACTOR); bottomTriangleArrow.offset(0, getHeight() * TRIANGLE_OFFSET_FACTOR); } public Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> getFeedbackLevelBehaviourEntry() { return feedbackLevelBehaviourEntry; } public void setCurrentlyDraged(boolean currentlyDraged) { this.currentlyDraged = currentlyDraged; } @Override public void onDraw(Canvas canvas) { if (!currentlyDraged) { super.onDraw(canvas); canvas.save(); if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Progress)) { // RED BOTTOM ARROW levelBehaviourPaint.setColor(Color.RED); canvas.drawPath(bottomTriangleArrow, levelBehaviourPaint); } else if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Regress)) { // GREEN TOP ARROW levelBehaviourPaint.setColor(Color.GREEN); canvas.drawPath(topTriangleArrow, levelBehaviourPaint); } canvas.restore(); } else { canvas.save(); canvas.drawRect(0, 0, getWidth(), getHeight(), dragBoxPaint); invalidate(); canvas.restore(); } } private void openLevelBehaviourDialog() { AlertDialog.Builder builder = new android.app.AlertDialog.Builder(feedbackCollectionActivity); final FeedbackCollection.LevelBehaviour oldLevelBehaviour = feedbackLevelBehaviourEntry.getValue(); builder.setTitle(feedbackLevelBehaviourEntry.getKey().getComponentName() + " - " + FeedbackCollection.LevelBehaviour.class.getSimpleName()) .setView(getDialogContentView()) .setNeutralButton(R.string.str_options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openOptions(); } }) .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { feedbackLevelBehaviourEntry.setValue(oldLevelBehaviour); } }) .setPositiveButton(R.string.str_ok, null) .show(); } private View getDialogContentView() { LayoutInflater inflater = LayoutInflater.from(feedbackCollectionActivity); View contentView = inflater.inflate(R.layout.dialog_level_behaviour, null); TextView messageTextView = (TextView) contentView.findViewById(R.id.messageTextView); messageTextView.setText(R.string.level_behaviour_message); LinearLayout.LayoutParams radioButtonLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); radioButtonLayoutParams.weight = 1; final RadioGroup radioGroup = (RadioGroup) contentView.findViewById(R.id.levelBehaviourRadioGroup); radioGroup.removeAllViews(); String[] values = Arrays .toString(FeedbackCollection.LevelBehaviour.values()) .replaceAll("^.|.$", "").split(", "); for (String value : values) { RadioButton radioButton = new RadioButton(feedbackCollectionActivity); radioButton.setText(value); radioButton.setLayoutParams(radioButtonLayoutParams); radioGroup.addView(radioButton); if (value.equals(feedbackLevelBehaviourEntry.getValue().toString())) { radioGroup.check(radioButton.getId()); } } radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { RadioButton radioButton = (RadioButton) radioGroup.findViewById(checkedId); feedbackLevelBehaviourEntry.setValue( FeedbackCollection.LevelBehaviour.valueOf(radioButton.getText().toString()) ); } }); return contentView; } }
8,753
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackLevelLayout.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/Feedback/FeedbackLevelLayout.java
/* * FeedbackLevelLayout.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view.Feedback; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver; import android.widget.GridLayout; import android.widget.LinearLayout; import android.widget.TextView; import java.util.LinkedHashMap; import java.util.Map; import hcm.ssj.creator.R; import hcm.ssj.creator.activity.FeedbackCollectionActivity; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; /** * Created by Antonio Grieco on 18.09.2017. */ public class FeedbackLevelLayout extends LinearLayout { private android.widget.GridLayout feedbackComponentGrid; private TextView levelTextView; private FeedbackListener feedbackListener; public FeedbackLevelLayout(FeedbackCollectionActivity feedbackCollectionActivity, int level, final Map<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourMap) { super(feedbackCollectionActivity); LinearLayout.inflate(feedbackCollectionActivity, R.layout.single_level_layout, this); levelTextView = (TextView) this.findViewById(R.id.levelText); feedbackComponentGrid = (android.widget.GridLayout) this.findViewById(R.id.feedbackComponentGrid); setLevel(level); relayoutGrid(feedbackCollectionActivity, feedbackLevelBehaviourMap); } public Map<Feedback, FeedbackCollection.LevelBehaviour> getFeedbackLevelBehaviourMap() { Map<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourMap = new LinkedHashMap<>(); for (int childCount = 0; childCount < feedbackComponentGrid.getChildCount(); childCount++) { View childView = feedbackComponentGrid.getChildAt(childCount); if (childView instanceof FeedbackComponentView) { Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry = ((FeedbackComponentView) childView).getFeedbackLevelBehaviourEntry(); feedbackLevelBehaviourMap.put(feedbackLevelBehaviourEntry.getKey(), feedbackLevelBehaviourEntry.getValue()); } } return feedbackLevelBehaviourMap; } public void setLevel(int level) { levelTextView.setText(String.valueOf(level)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } private void relayoutGrid( final FeedbackCollectionActivity containerActivity, final Map<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourMap) { if (feedbackLevelBehaviourMap == null || feedbackLevelBehaviourMap.isEmpty()) { return; } levelTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { feedbackComponentGrid.removeAllViews(); int height = levelTextView.getMeasuredHeight(); LinearLayout.LayoutParams componentLayoutParams = new LinearLayout.LayoutParams(height, height); componentLayoutParams.gravity = Gravity.CENTER_VERTICAL; int margin = levelTextView.getPaddingStart(); componentLayoutParams.setMargins(margin, margin, margin, margin); for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> entry : feedbackLevelBehaviourMap.entrySet()) { FeedbackComponentView feedbackComponentView = new FeedbackComponentView(containerActivity, entry); feedbackComponentView.setLayoutParams(componentLayoutParams); feedbackComponentGrid.addView(feedbackComponentView); } reorder(); levelTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); levelTextView.requestLayout(); } public void reorder() { feedbackComponentGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { final View firstChild = feedbackComponentGrid.getChildAt(0); if (firstChild == null) { return; } android.widget.GridLayout.LayoutParams lp1 = (android.widget.GridLayout.LayoutParams) firstChild.getLayoutParams(); final int columns = (feedbackComponentGrid.getMeasuredWidth() / (firstChild.getMeasuredWidth() + lp1.leftMargin + lp1.rightMargin)); feedbackComponentGrid.post(new Runnable() { @Override public void run() { feedbackComponentGrid.setColumnCount(Integer.MAX_VALUE); for (int i = 0; i < feedbackComponentGrid.getChildCount(); i++) { final android.widget.GridLayout.LayoutParams lp = (android.widget.GridLayout.LayoutParams) feedbackComponentGrid.getChildAt(i).getLayoutParams(); lp.columnSpec = GridLayout.spec(i % columns, GridLayout.CENTER); lp.rowSpec = GridLayout.spec(i - (i % columns), GridLayout.CENTER); lp.setGravity(Gravity.FILL_VERTICAL); final View v = feedbackComponentGrid.getChildAt(i); v.post(new Runnable() { @Override public void run() { v.setLayoutParams(lp); } }); } feedbackComponentGrid.setColumnCount(columns); } }); feedbackComponentGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); feedbackComponentGrid.requestLayout(); } public void setFeedbackListener(FeedbackListener feedbackListener) { this.feedbackListener = feedbackListener; } protected void addGridComponent(FeedbackComponentView feedbackComponentView) { if (feedbackComponentView.getParent() != feedbackComponentGrid) { FeedbackLevelLayout formerFeedbackLevelLayout = (FeedbackLevelLayout) feedbackComponentView.getParent().getParent().getParent(); formerFeedbackLevelLayout.removeFeedbackComponentView(feedbackComponentView); feedbackComponentGrid.addView(feedbackComponentView); feedbackListener.onComponentAdded(); this.reorder(); } } protected void removeFeedbackComponentView(FeedbackComponentView feedbackComponentView) { feedbackComponentGrid.removeView(feedbackComponentView); this.reorder(); } }
7,243
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackCollectionOnDragListener.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/view/Feedback/FeedbackCollectionOnDragListener.java
/* * FeedbackCollectionOnDragListener.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.view.Feedback; import android.view.DragEvent; import android.view.View; import android.view.ViewGroup; import hcm.ssj.creator.activity.FeedbackCollectionActivity; import hcm.ssj.creator.core.PipelineBuilder; import static android.view.DragEvent.ACTION_DRAG_ENDED; import static android.view.DragEvent.ACTION_DRAG_STARTED; import static android.view.DragEvent.ACTION_DROP; /** * Created by Antonio Grieco on 04.10.2017. */ public class FeedbackCollectionOnDragListener implements View.OnDragListener { private final FeedbackCollectionActivity feedbackCollectionActivity; public FeedbackCollectionOnDragListener(FeedbackCollectionActivity feedbackCollectionActivity) { this.feedbackCollectionActivity = feedbackCollectionActivity; } @Override public boolean onDrag(final View v, DragEvent event) { if (event.getLocalState() instanceof FeedbackComponentView) { final FeedbackComponentView feedbackComponentView = ((FeedbackComponentView) event.getLocalState()); switch (event.getAction()) { case ACTION_DRAG_STARTED: feedbackCollectionActivity.showDragIcons(feedbackComponentView.getWidth(), feedbackComponentView.getHeight()); break; case ACTION_DROP: if (v instanceof FeedbackLevelLayout) { ((FeedbackLevelLayout) v).addGridComponent(feedbackComponentView); } else if (v.equals(feedbackCollectionActivity.getRecycleBin())) { feedbackComponentView.post(new Runnable() { @Override public void run() { ((ViewGroup) feedbackComponentView.getParent()).removeView(feedbackComponentView); feedbackCollectionActivity.requestReorder(); } }); PipelineBuilder.getInstance().remove( feedbackComponentView.getFeedbackLevelBehaviourEntry().getKey() ); } break; case ACTION_DRAG_ENDED: // Set currently draged to false no matter where the drag ended, to force normal painting. feedbackComponentView.setCurrentlyDraged(false); feedbackCollectionActivity.hideDragIcons(); break; } return true; } return false; } }
3,498
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
OptionsActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/OptionsActivity.java
/* * OptionsActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import hcm.ssj.core.Consumer; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Sensor; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.Option; import hcm.ssj.creator.R; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.util.ArrayAdapterWithNull; import hcm.ssj.creator.util.OptionTable; import hcm.ssj.creator.util.ProviderTable; import hcm.ssj.ml.IModelHandler; import hcm.ssj.ml.Model; import hcm.ssj.ml.Trainer; public class OptionsActivity extends AppCompatActivity { public static Object object; private Object innerObject; /** * */ private void init() { innerObject = object; object = null; Option[] options; if (innerObject == null) { //change title setTitle(R.string.str_options_pipe); options = PipelineBuilder.getOptionList(Pipeline.getInstance()); } else { //change title setTitle(((hcm.ssj.core.Component) innerObject).getComponentName()); options = PipelineBuilder.getOptionList(innerObject); } //stretch columns TableLayout tableLayout = (TableLayout) findViewById(R.id.id_tableLayout); tableLayout.setStretchAllColumns(true); //add frame size and delta for transformer and consumer if (innerObject != null && (innerObject instanceof Transformer || innerObject instanceof Consumer)) { //add frame size and delta TableRow frameSizeTableRow = createTextView(true); TableRow deltaTableRow = createTextView(false); tableLayout.addView(frameSizeTableRow); tableLayout.addView(deltaTableRow); if (innerObject instanceof Consumer) { boolean triggeredByEvent = PipelineBuilder.getInstance().getEventTrigger(innerObject) != null; setEnabledRecursive(frameSizeTableRow, !triggeredByEvent); setEnabledRecursive(deltaTableRow, !triggeredByEvent); tableLayout.addView(createConsumerTextView(innerObject, frameSizeTableRow, deltaTableRow)); } } //add options if (options != null && options.length > 0) { tableLayout.addView(OptionTable.createTable(this, options, innerObject)); } //add possible providers for sensor, transformer or consumer if (innerObject != null && innerObject instanceof Sensor) { //add possible stream providers TableRow streamTableRow = ProviderTable.createStreamTable(this, innerObject, (innerObject instanceof Transformer || innerObject instanceof Consumer) || (innerObject instanceof Sensor && options != null && options.length > 0), R.string.str_stream_output); if (streamTableRow != null) { tableLayout.addView(streamTableRow); } } if (innerObject != null && (innerObject instanceof Transformer || innerObject instanceof Consumer)) { //add possible stream providers TableRow streamTableRow = ProviderTable.createStreamTable(this, innerObject, (innerObject instanceof Transformer || innerObject instanceof Consumer) || (innerObject instanceof Sensor && options != null && options.length > 0), R.string.str_stream_input); if (streamTableRow != null) { tableLayout.addView(streamTableRow); } } if (innerObject != null && (innerObject instanceof IModelHandler || innerObject instanceof Model)) { //add possible model connections TableRow modelTableRow = ProviderTable.createModelTable(this, innerObject,true, (innerObject instanceof IModelHandler ? R.string.str_model_conn : R.string.str_modelhandler_conn)); if (modelTableRow != null) { tableLayout.addView(modelTableRow); } } if (innerObject != null && !(innerObject instanceof Model)) { //add possible event providers // Do not add event provider for managed feedback if(!PipelineBuilder.getInstance().isManagedFeedback(innerObject)) { TableRow eventTableRow = ProviderTable.createEventTable(this, innerObject, (innerObject instanceof Transformer || innerObject instanceof Consumer) || (innerObject instanceof Sensor && options != null && options.length > 0)); if (eventTableRow != null) { tableLayout.addView(eventTableRow); } } } } /** * @param isFrameSize boolean * @return TableRow */ private TableRow createTextView(final boolean isFrameSize) { TableRow tableRow = new TableRow(this); tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT)); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setWeightSum(1.0f); // EditText editText = new EditText(this); editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL); editText.setEms(10); editText.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.6f)); editText.setHint(R.string.str_frameSizeSmallest); editText.setText(isFrameSize ? ((PipelineBuilder.getInstance().getFrameSize(innerObject) != null) ? String.valueOf(PipelineBuilder.getInstance().getFrameSize(innerObject)) : null) : String.valueOf(PipelineBuilder.getInstance().getDelta(innerObject))); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (isFrameSize) { try { if (s == null || s.length() == 0) { PipelineBuilder.getInstance().setFrameSize(innerObject, null); } else { double d = Double.parseDouble(s.toString()); if (d > 0) { PipelineBuilder.getInstance().setFrameSize(innerObject, d); } } } catch (NumberFormatException ex) { Log.w("Invalid input for frameSize double: " + s.toString()); } } else { try { double d = Double.parseDouble(s.toString()); if (d >= 0) { PipelineBuilder.getInstance().setDelta(innerObject, d); } } catch (NumberFormatException ex) { Log.w("Invalid input for delta double: " + s.toString()); } } } }); linearLayout.addView(editText); // TextView textView = new TextView(this); textView.setText(isFrameSize ? R.string.str_frameSize : R.string.str_delta); textView.setTextAppearance(this, android.R.style.TextAppearance_Medium); textView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.4f)); linearLayout.addView(textView); tableRow.addView(linearLayout); return tableRow; } /** * @param frameSizeTableRow * @param deltaTableRow * @return */ private TableRow createConsumerTextView(Object mainObject, final TableRow frameSizeTableRow, final TableRow deltaTableRow) { TableRow tableRow = new TableRow(this); tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT)); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setWeightSum(1.0f); TextView textView = new TextView(this); textView.setText(R.string.str_eventrigger); textView.setTextAppearance(this, android.R.style.TextAppearance_Medium); linearLayout.addView(textView); final Spinner eventTriggerList = new Spinner(this); ArrayList<Object> items = new ArrayList<>(); items.add(null); //default element if(mainObject instanceof Trainer) items.add(PipelineBuilder.getInstance().getAnnotation()); //annotation channel items.addAll(Arrays.asList(PipelineBuilder.getInstance().getPossibleEventConnections(mainObject))); eventTriggerList.setAdapter(new ArrayAdapterWithNull(this, android.R.layout.simple_spinner_item, items, "<none>")); //preselect item Object selection = PipelineBuilder.getInstance().getEventTrigger(mainObject); if(selection == null) { eventTriggerList.setSelection(0); } else { for (int i = 0; i < items.size(); i++) { if (items.get(i) != null && items.get(i).equals(selection)) { eventTriggerList.setSelection(i); break; } } } eventTriggerList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { setEnabledRecursive(frameSizeTableRow, position == 0); setEnabledRecursive(deltaTableRow, position == 0); Object src = parent.getItemAtPosition(position); PipelineBuilder.getInstance().setEventTrigger(innerObject, src); } @Override public void onNothingSelected(AdapterView parent) { } }); linearLayout.addView(eventTriggerList); tableRow.addView(linearLayout); return tableRow; } private void setEnabledRecursive(final View view, final boolean enabled) { if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { setEnabledRecursive(((ViewGroup) view).getChildAt(i), enabled); } } else { view.post(new Runnable() { @Override public void run() { view.setEnabled(enabled); } }); } } /** * @param savedInstanceState Bundle */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_options); init(); } }
11,744
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackCollectionActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/FeedbackCollectionActivity.java
/* * FeedbackCollectionActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.content.res.Configuration; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import hcm.ssj.creator.R; import hcm.ssj.creator.core.container.FeedbackCollectionContainerElement; import hcm.ssj.creator.view.Feedback.FeedbackCollectionOnDragListener; import hcm.ssj.creator.view.Feedback.FeedbackLevelLayout; import hcm.ssj.creator.view.Feedback.FeedbackListener; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; /** * Created by Antonio Grieco on 19.09.2017. */ public class FeedbackCollectionActivity extends AppCompatActivity { public static FeedbackCollectionContainerElement feedbackCollectionContainerElement = null; private FeedbackCollectionContainerElement innerFeedbackCollectionContainerElement = null; private LinearLayout levelLinearLayout; private List<FeedbackLevelLayout> feedbackLevelLayoutList; private FeedbackListener feedbackListener; private ImageView recycleBin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback_container); init(); createLevels(); } @Override protected void onPause() { super.onPause(); if (innerFeedbackCollectionContainerElement != null) { innerFeedbackCollectionContainerElement.removeAllFeedbacks(); for (int level = 0; level < feedbackLevelLayoutList.size(); level++) { Map<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourMap = feedbackLevelLayoutList.get(level).getFeedbackLevelBehaviourMap(); if (feedbackLevelBehaviourMap != null && !feedbackLevelBehaviourMap.isEmpty()) { for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackLevelBehaviourMap.entrySet()) { innerFeedbackCollectionContainerElement.addFeedback(feedbackLevelBehaviourEntry.getKey(), level, feedbackLevelBehaviourEntry.getValue()); } } } } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); for (final FeedbackLevelLayout feedbackLevelLayout : feedbackLevelLayoutList) { feedbackLevelLayout.postDelayed(new Runnable() { @Override public void run() { feedbackLevelLayout.reorder(); } }, 250); } } private void init() { innerFeedbackCollectionContainerElement = feedbackCollectionContainerElement; feedbackCollectionContainerElement = null; if (innerFeedbackCollectionContainerElement == null) { finish(); throw new RuntimeException("no feedbackcontainer given"); } levelLinearLayout = (LinearLayout) findViewById(R.id.feedbackLinearLayout); recycleBin = (ImageView) findViewById(R.id.recycleBin); recycleBin.setOnDragListener(new FeedbackCollectionOnDragListener(this)); setTitle(((FeedbackCollection) innerFeedbackCollectionContainerElement.getElement()).getComponentName()); feedbackLevelLayoutList = new ArrayList<>(); this.feedbackListener = new FeedbackListener() { @Override public void onComponentAdded() { deleteEmptyLevels(); addEmptyLevel(); } }; } private void createLevels() { feedbackLevelLayoutList.clear(); levelLinearLayout.removeAllViews(); List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackLevelList = innerFeedbackCollectionContainerElement.getFeedbackList(); for (int i = 0; i < feedbackLevelList.size(); i++) { FeedbackLevelLayout feedbackLevelLayout = new FeedbackLevelLayout(this, i, feedbackLevelList.get(i)); feedbackLevelLayout.setOnDragListener(new FeedbackCollectionOnDragListener(this)); feedbackLevelLayout.setFeedbackListener(this.feedbackListener); feedbackLevelLayoutList.add(feedbackLevelLayout); levelLinearLayout.addView(feedbackLevelLayout); } addEmptyLevel(); } private void addEmptyLevel() { FeedbackLevelLayout feedbackLevelLayout = new FeedbackLevelLayout(this, levelLinearLayout.getChildCount(), null); feedbackLevelLayout.setOnDragListener(new FeedbackCollectionOnDragListener(this)); feedbackLevelLayout.setFeedbackListener(this.feedbackListener); feedbackLevelLayoutList.add(feedbackLevelLayout); levelLinearLayout.addView(feedbackLevelLayout); } private void deleteEmptyLevels() { int counter = 0; Iterator<FeedbackLevelLayout> iterator = feedbackLevelLayoutList.iterator(); while (iterator.hasNext()) { FeedbackLevelLayout feedbackLevelLayout = iterator.next(); if (feedbackLevelLayout.getFeedbackLevelBehaviourMap() != null && !feedbackLevelLayout.getFeedbackLevelBehaviourMap().isEmpty()) { feedbackLevelLayout.setLevel(counter); counter++; } else { levelLinearLayout.removeView(feedbackLevelLayout); iterator.remove(); } } } public void showDragIcons(int width, int height) { ViewGroup.LayoutParams layoutParamsDragIcon = this.recycleBin.getLayoutParams(); layoutParamsDragIcon.width = width; layoutParamsDragIcon.height = height; this.recycleBin.setLayoutParams(layoutParamsDragIcon); this.recycleBin.setVisibility(View.VISIBLE); this.recycleBin.invalidate(); } public void hideDragIcons() { this.recycleBin.setVisibility(View.GONE); } public ImageView getRecycleBin() { return recycleBin; } public void requestReorder() { for (final FeedbackLevelLayout feedbackLevelLayout : feedbackLevelLayoutList) { feedbackLevelLayout.post(new Runnable() { @Override public void run() { feedbackLevelLayout.reorder(); } }); } deleteEmptyLevels(); addEmptyLevel(); } }
7,202
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
MainActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/MainActivity.java
/* * MainActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.provider.Settings; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.Toast; import com.microsoft.band.tiles.TileButtonEvent; import com.microsoft.band.tiles.TileEvent; import java.util.ArrayList; import java.util.List; import hcm.ssj.core.ExceptionHandler; import hcm.ssj.core.Log; import hcm.ssj.core.Monitor; import hcm.ssj.core.Pipeline; import hcm.ssj.core.PipelineStateListener; import hcm.ssj.creator.R; import hcm.ssj.creator.core.BandComm; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.core.SSJDescriptor; import hcm.ssj.creator.dialogs.AddDialog; import hcm.ssj.creator.dialogs.FileDialog; import hcm.ssj.creator.dialogs.Listener; import hcm.ssj.creator.main.AnnotationTab; import hcm.ssj.creator.main.TabHandler; import hcm.ssj.creator.util.DemoHandler; import hcm.ssj.creator.util.Util; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, PipelineStateListener, ActivityCompat.OnRequestPermissionsResultCallback { private static final int REQUEST_DANGEROUS_PERMISSIONS = 108; private static boolean ready = true; private boolean firstStart = false; //tabs private TabHandler tabHandler; private boolean actionButtonsVisible = false; private LinearLayout sensorLayout; private LinearLayout sensorChannelLayout; private LinearLayout transformerLayout; private LinearLayout consumerLayout; private LinearLayout eventHandlerLayout; private LinearLayout modelLayout; private Animation showButton; private Animation hideButton; private Animation showLayout; private Animation hideLayout; private FloatingActionButton fab; private BroadcastReceiver msBandReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { android.util.Log.i("SSJCreator", "received tile event"); TileButtonEvent data = intent.getParcelableExtra(TileEvent.TILE_EVENT_DATA); if (!data.getPageID().equals(BandComm.pageId)) { return; } //toggle button AnnotationTab anno = tabHandler.getAnnotation(); if (anno == null) { return; } anno.toggleAnnoButton(anno.getBandAnnoButton(), data.getElementID() == BandComm.BTN_YES); } }; /** * */ private void init() { // Initialize action button layouts with their corresponding event listeners. initAddComponentButtons(); initActionButtonLayouts(); initFloatingActionButton(); // Init tabs tabHandler = new TabHandler(MainActivity.this); // Display location popup showLocationDialog(); // Handle permissions // checkPermissions(); // Set exception handler setExceptionHandler(); // Register receiver for ms band events IntentFilter filter = new IntentFilter(); filter.addAction("com.microsoft.band.action.ACTION_TILE_BUTTON_PRESSED"); registerReceiver(msBandReceiver, filter); } private void showLocationDialog() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.str_location_title) .setMessage(R.string.str_location_message) .setPositiveButton(R.string.str_location_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { checkPermissions(); } }) .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { checkPermissions(); } }) .show(); } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { checkPermissions(); } } /** * */ private void setExceptionHandler() { ExceptionHandler exceptionHandler = new ExceptionHandler() { @Override public void handle(final String location, final String msg, final Throwable t) { Monitor.notifyMonitor(); Handler handler = new Handler(Looper.getMainLooper()); Runnable runnable = new Runnable() { public void run() { String text = location + ": " + msg; Throwable cause = t; while (cause != null) { text += "\ncaused by: " + cause.getMessage(); cause = cause.getCause(); } new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.str_error) .setMessage(text) .setPositiveButton(R.string.str_ok, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } }; handler.post(runnable); } }; Pipeline.getInstance().setExceptionHandler(exceptionHandler); } /** * Request permissions through system dialog */ private void checkPermissions() { if (Build.VERSION.SDK_INT >= 23) { String[] permissions = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BODY_SENSORS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { permissions = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.BODY_SENSORS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { permissions = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BODY_SENSORS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { permissions = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BODY_SENSORS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT, }; } // Dangerous permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, permissions, REQUEST_DANGEROUS_PERMISSIONS); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_DANGEROUS_PERMISSIONS) { List<String> permissionList = new ArrayList<>(); for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED && !permissions[i].equalsIgnoreCase("android.permission.FOREGROUND_SERVICE") && !permissions[i].equalsIgnoreCase("android.permission.MANAGE_EXTERNAL_STORAGE") && !permissions[i].equalsIgnoreCase("com.samsung.WATCH_APP_TYPE.Companion") && !permissions[i].equalsIgnoreCase("com.samsung.accessory.permission.ACCESSORY_FRAMEWORK")) { permissionList.add(permissions[i]); Log.i("Missing permission: " + permissions[i]); } } // Request all file access if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (!Environment.isExternalStorageManager()) { Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivity(intent); } } } } /** * @param view View */ public void buttonPressed(View view) { switch (view.getId()) { case R.id.id_imageButton: { handlePipeOld(); break; } } } /** * Start or stop pipe */ private void handlePipeOld() { if (ready) { ready = false; new Thread() { @Override public void run() { //change button text changeImageButton(android.R.drawable.ic_popup_sync, false); //save framework options Pipeline pipeline = Pipeline.getInstance(); //remove old content pipeline.clear(); pipeline.resetCreateTime(); //add components try { PipelineBuilder.getInstance().buildPipe(); } catch (Exception e) { Log.e(getString(R.string.err_buildPipe), e); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.err_buildPipe, Toast.LENGTH_LONG).show(); } }); ready = true; changeImageButton(android.R.drawable.ic_media_play, true); return; } //change button text changeImageButton(android.R.drawable.ic_media_pause, true); //notify tabs tabHandler.preStart(); //start framework pipeline.start(); //run if (pipeline.isRunning()) { Monitor.waitMonitor(); } //stop framework try { tabHandler.preStop(); pipeline.stop(); } catch (Exception e) { e.printStackTrace(); } ready = true; //change button text changeImageButton(android.R.drawable.ic_media_play, true); } }.start(); } else { Monitor.notifyMonitor(); } } /** * Start or stop pipe */ private void handlePipe() { if (ready) { ready = false; new Thread() { @Override public void run() { // Change button text changeImageButton(android.R.drawable.ic_popup_sync, false); // Save framework options Pipeline pipeline = Pipeline.getInstance(); // Remove old content pipeline.clear(); pipeline.resetCreateTime(); pipeline.registerStateListener(MainActivity.this); // Add components try { PipelineBuilder.getInstance().buildPipe(); } catch (Exception e) { Log.e(getString(R.string.err_buildPipe), e); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.err_buildPipe, Toast.LENGTH_LONG).show(); } }); ready = true; changeImageButton(android.R.drawable.ic_media_play, true); return; } // Change button text changeImageButton(android.R.drawable.ic_media_pause, true); //Notify tabs tabHandler.preStart(); // Start framework startPipelineService(); // Run Monitor.waitMonitor(); // Stop framework try { stopPipelineService(); tabHandler.preStop(); pipeline.stop(); } catch (Exception e) { e.printStackTrace(); } ready = true; //change button text changeImageButton(android.R.drawable.ic_media_play, true); } }.start(); } else { Monitor.notifyMonitor(); } } @Override public void stateUpdated(Pipeline.State state) { if (!ready) { switch (state) { case STARTING: break; case RUNNING: break; case INACTIVE: case STOPPING: Monitor.notifyMonitor(); break; } } } private void startPipelineService() { Intent serviceIntent = new Intent(this, PipelineService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(serviceIntent); } else { startService(serviceIntent); } } private void stopPipelineService() { Intent serviceIntent = new Intent(this, PipelineService.class); stopService(serviceIntent); } /** * @param idImage int */ private void changeImageButton(final int idImage, final boolean enabled) { final ImageButton imageButton = (ImageButton) findViewById(R.id.id_imageButton); if (imageButton != null) { imageButton.post(new Runnable() { public void run() { imageButton.setImageResource(idImage); imageButton.setEnabled(enabled); } }); } } /** * @param resource int * @param list ArrayList */ private void showAddDialog(int resource, ArrayList<Class> list) { final AddDialog addDialog = new AddDialog(); addDialog.setTitleMessage(resource); addDialog.setOption(list); Listener listener = new Listener() { @Override public void onPositiveEvent(Object[] o) { addDialog.removeListener(this); actualizeContent(Util.AppAction.ADD, o != null ? o[0] : null); } @Override public void onNegativeEvent(Object[] o) { addDialog.removeListener(this); } }; addDialog.addListener(listener); addDialog.show(getSupportFragmentManager(), MainActivity.this.getClass().getSimpleName()); } /** * @param title int * @param type FileDialog.Type * @param message int */ private void showFileDialog(final int title, final FileDialog.Type type, final int message) { if (firstStart) { DemoHandler.copyFiles(MainActivity.this); } final FileDialog fileDialog = new FileDialog(); fileDialog.setTitleMessage(title); fileDialog.setType(type); fileDialog.show(getSupportFragmentManager(), MainActivity.this.getClass().getSimpleName()); Listener listener = new Listener() { @Override public void onPositiveEvent(Object[] o) { fileDialog.removeListener(this); if (type == FileDialog.Type.LOAD_PIPELINE || type == FileDialog.Type.LOAD_STRATEGY) { actualizeContent(Util.AppAction.LOAD, o != null ? o[0] : null); } else if (type == FileDialog.Type.SAVE) { actualizeContent(Util.AppAction.SAVE, o != null ? o[0] : null); } } @Override public void onNegativeEvent(Object[] o) { if (o != null) { Log.e(getResources().getString(message)); new AlertDialog.Builder(MainActivity.this) .setTitle(message) .setPositiveButton(R.string.str_ok, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } fileDialog.removeListener(this); } }; fileDialog.addListener(listener); } /** * @param appAction Util.AppAction * @param o Object */ private void actualizeContent(Util.AppAction appAction, Object o) { tabHandler.actualizeContent(appAction, o); } @Override protected void onResume() { super.onResume(); actualizeContent(Util.AppAction.DISPLAYED, null); if (!ready) { changeImageButton(android.R.drawable.ic_media_pause, true); } } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { unregisterReceiver(msBandReceiver); tabHandler.cleanUp(); Pipeline framework = Pipeline.getInstance(); if (framework.isRunning()) { framework.stop(); stopPipelineService(); } PipelineBuilder.getInstance().clear(); super.onDestroy(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // check if the activity has started before on this app version... String name = "LAST_VERSION"; String ssjVersion = Pipeline.getVersion(); SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); firstStart = !getPrefs.getString(name, "").equalsIgnoreCase(ssjVersion); //save current version in preferences so the next time this won't run again SharedPreferences.Editor e = getPrefs.edit(); e.putString(name, ssjVersion); e.apply(); if(firstStart) startTutorial(); setContentView(R.layout.activity_main); loadAnimations(); init(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); final TabHost tabHost = (TabHost) findViewById(R.id.id_tabHost); tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { int currentTabId = tabHost.getCurrentTab(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); // Show floating action button only if canvas tab is selected. if (currentTabId == 0) { fab.show(); fab.setEnabled(true); } else { if (actionButtonsVisible) { toggleActionButtons(false); } fab.hide(); fab.setEnabled(false); } } }); } /** * Close drawer if open otherwise go to app home screen. */ @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { moveTaskToBack(true); } } private void startTutorial() { //launch app intro Intent i = new Intent(MainActivity.this, TutorialActivity.class); startActivity(i); } /** * @param menu Menu * @return boolean */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } /** * @param item MenuItem * @return boolean */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_framework: { Intent intent = new Intent(getApplicationContext(), OptionsActivity.class); startActivity(intent); return true; } case R.id.action_save: { showFileDialog(R.string.str_save, FileDialog.Type.SAVE, R.string.str_saveError); return true; } case R.id.action_load_pipeline: { showFileDialog(R.string.str_load_pipeline, FileDialog.Type.LOAD_PIPELINE, R.string.str_loadError); return true; } case R.id.action_load_strategy: { showFileDialog(R.string.str_load_strategy, FileDialog.Type.LOAD_STRATEGY, R.string.str_loadError); return true; } case R.id.action_delete_pipeline: { showFileDialog(R.string.str_delete, FileDialog.Type.DELETE_PIPELINE, R.string.str_deleteError); return true; } case R.id.action_clear: { PipelineBuilder.getInstance().clear(); actualizeContent(Util.AppAction.CLEAR, null); return true; } } return true; } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); // if (itemId == R.id.action_graph) // { // Intent intent = new Intent(getApplicationContext(), GraphActivity.class); // startActivity(intent); // } // else if (itemId == R.id.action_train_model) { Intent intent = new Intent(getApplicationContext(), TrainActivity.class); startActivity(intent); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return false; } /** * Initialize floating action button to show/hide SSJ component selection buttons. */ private void initFloatingActionButton() { fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (actionButtonsVisible) { toggleActionButtons(false); } else { toggleActionButtons(true); } } }); } /** * Initialize all linear layouts that contain action buttons for SSJ component selection * and their corresponding text labels. */ private void initActionButtonLayouts() { sensorLayout = (LinearLayout) findViewById(R.id.sensor_layout); sensorChannelLayout = (LinearLayout) findViewById(R.id.sensor_channel_layout); transformerLayout = (LinearLayout) findViewById(R.id.transformers_layout); consumerLayout = (LinearLayout) findViewById(R.id.consumer_layout); eventHandlerLayout = (LinearLayout) findViewById(R.id.event_handler_layout); modelLayout = (LinearLayout) findViewById(R.id.model_layout); } /** * Initialize all action buttons for SSJ component selection and add corresponding event * listeners. */ private void initAddComponentButtons() { FloatingActionButton addSensor = (FloatingActionButton) findViewById(R.id.action_sensors); addSensor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_sensors, SSJDescriptor.getInstance().sensors); } }); FloatingActionButton addProvider = (FloatingActionButton) findViewById(R.id.action_providers); addProvider.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_sensor_channels, SSJDescriptor.getInstance().sensorChannels); } }); FloatingActionButton addTransformer = (FloatingActionButton) findViewById(R.id.action_transformers); addTransformer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_transformers, SSJDescriptor.getInstance().transformers); } }); FloatingActionButton addConsumer = (FloatingActionButton) findViewById(R.id.action_consumers); addConsumer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_consumers, SSJDescriptor.getInstance().consumers); } }); FloatingActionButton addEventHandler = (FloatingActionButton) findViewById(R.id.action_eventhandlers); addEventHandler.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_eventhandlers, SSJDescriptor.getInstance().eventHandlers); } }); FloatingActionButton addModel = (FloatingActionButton) findViewById(R.id.action_models); addModel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddDialog(R.string.str_models, SSJDescriptor.getInstance().models); } }); } /** * Load animations that toggle visibility of action buttons. */ private void loadAnimations() { showButton = AnimationUtils.loadAnimation(MainActivity.this, R.anim.show_button); hideButton = AnimationUtils.loadAnimation(MainActivity.this, R.anim.hide_button); showLayout = AnimationUtils.loadAnimation(MainActivity.this, R.anim.show_layout); hideLayout = AnimationUtils.loadAnimation(MainActivity.this, R.anim.hide_layout); } /** * Toggle visibility of all floating action buttons. * @param enable True to enable visibility, false otherwise. */ private void toggleActionButtons(boolean enable) { toggleLayout(sensorLayout, enable); toggleLayout(sensorChannelLayout, enable); toggleLayout(transformerLayout, enable); toggleLayout(consumerLayout, enable); toggleLayout(eventHandlerLayout, enable); toggleLayout(modelLayout, enable); } /** * Toggle visibility of a linear layout and all of it's children. * @param layout LinearLayout to show/hide. * @param enable True to enable visibility, false otherwise. */ private void toggleLayout(LinearLayout layout, boolean enable) { actionButtonsVisible = enable; if (enable) { layout.setVisibility(View.VISIBLE); layout.startAnimation(showLayout); fab.startAnimation(showButton); } else { layout.setVisibility(View.GONE); layout.startAnimation(hideLayout); fab.startAnimation(hideButton); } for (int i = 0; i < layout.getChildCount(); i++) { layout.getChildAt(i).setEnabled(enable); } } }
27,099
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
GraphActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/GraphActivity.java
/* * GraphActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.os.Bundle; import android.os.Environment; import androidx.appcompat.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import com.obsez.android.lib.filechooser.ChooserDialog; import java.io.File; import hcm.ssj.audio.AudioDecoder; import hcm.ssj.audio.PlaybackListener; import hcm.ssj.audio.PlaybackThread; import hcm.ssj.core.stream.Stream; import hcm.ssj.creator.R; import hcm.ssj.creator.util.PlaybackThreadList; import hcm.ssj.creator.view.StreamLayout; import hcm.ssj.creator.view.StreamView; import hcm.ssj.creator.view.WaveformView; import hcm.ssj.file.FileCons; import hcm.ssj.file.FileUtils; /** * Visualizes user-saved data. This class supports visualization of stream files (.stream~) as well * as multiple media files like .mp3, .mp4, and .wav. */ public class GraphActivity extends AppCompatActivity { private static final String SUPPORTED_MEDIA_TYPES = "mp3|mp4|wav"; private ChooserDialog chooserDialog; private PlaybackThreadList playbackThreads = new PlaybackThreadList(); private StreamLayout streamLayout; private Button playButton; private Button resetButton; private int maxAudioLength = Integer.MIN_VALUE; private int screenWidth; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.graph_layout); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); screenWidth = displayMetrics.widthPixels; streamLayout = (StreamLayout) findViewById(R.id.stream_layout); streamLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.performClick(); float percentage = event.getX() / screenWidth; playbackThreads.seekTo((int) (percentage * maxAudioLength)); return true; } }); initializeUI(); } private void initializeUI() { playButton = (Button) findViewById(R.id.play); playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (playbackThreads.isPlaying()) { playbackThreads.pause(); playButton.setText(R.string.play); } else { playbackThreads.play(); playButton.setText(R.string.pause); } } }); resetButton = (Button) findViewById(R.id.reset); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playbackThreads.reset(); playButton.setText(R.string.play); } }); Button loadButton = (Button) findViewById(R.id.load_stream_file); loadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chooserDialog = new ChooserDialog().with(GraphActivity.this); chooserDialog.withStartFile(Environment.getExternalStorageDirectory().getPath()); chooserDialog.withChosenListener(new ChooserDialog.Result() { @Override public void onChoosePath(String path, File file) { try { String type = FileUtils.getFileType(file); if (type.matches(SUPPORTED_MEDIA_TYPES)) { AudioDecoder decoder = new AudioDecoder(file.getPath()); int audioLength = decoder.getAudioLength(); WaveformView waveform = new WaveformView(GraphActivity.this); waveform.setSamples(decoder.getSamples()); waveform.setAudioLength(audioLength); streamLayout.addView(waveform, 0); showMediaButtons(); playbackThreads.add(new PlaybackThread(GraphActivity.this, file)); if (audioLength > maxAudioLength) { maxAudioLength = audioLength; playbackThreads.removePlaybackListener(); PlaybackListener playbackListener = new PlaybackListener() { @Override public void onProgress(int progress) { streamLayout.setMarkerProgress(progress); } @Override public void onCompletion() { playButton.setText(R.string.play); streamLayout.resetMarker(); playbackThreads.resetFinishedPlaying(); } }; playbackThreads.setPlaybackListener(playbackListener); } } else if (type.matches(FileCons.FILE_EXTENSION_STREAM)) { Stream streamData = Stream.load(file.getPath()); StreamView streamView = new StreamView(GraphActivity.this, streamData); streamLayout.addView(streamView); } } catch (Exception e) { e.printStackTrace(); } } }).build(); chooserDialog.show(); } }); } private void showMediaButtons() { playButton.setVisibility(View.VISIBLE); resetButton.setVisibility(View.VISIBLE); } }
6,287
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
TutorialActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/TutorialActivity.java
/* * TutorialActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.github.paolorotolo.appintro.AppIntro; import com.github.paolorotolo.appintro.AppIntroFragment; import hcm.ssj.creator.R; /** * Created by Johnny on 22.08.2016. */ public class TutorialActivity extends AppIntro { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Instead of fragments, you can also use our default slide // Just set a title, description, background and image. AppIntro will do the rest. addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide1_title), getResources().getString(R.string.slide1_text), R.drawable.logo, Color.parseColor("#0099CC"))); addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide2_title), getResources().getString(R.string.slide2_text), R.drawable.file, Color.parseColor("#BB8930"))); addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide3_title), getResources().getString(R.string.slide3_text), R.drawable.edit, Color.parseColor("#979797"))); addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide4_title), getResources().getString(R.string.slide4_text), R.drawable.eventconnections, Color.parseColor("#0F9D58"))); addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide5_title), getResources().getString(R.string.slide5_text), R.drawable.start, Color.parseColor("#4A82AE"))); addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.slide6_title), getResources().getString(R.string.slide6_text), R.drawable.tabs, Color.parseColor("#963aff"))); // OPTIONAL METHODS // Override bar/separator color. // setBarColor(Color.parseColor("#4A82AE")); // setSeparatorColor(Color.parseColor("#4A82AE")); // Hide Skip/Done button. showSkipButton(true); setProgressButtonEnabled(true); } @Override public void onSkipPressed(Fragment currentFragment) { super.onSkipPressed(currentFragment); // Do something when users tap on Skip button. finish(); } @Override public void onDonePressed(Fragment currentFragment) { super.onDonePressed(currentFragment); // Do something when users tap on Done button. finish(); } @Override public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) { super.onSlideChanged(oldFragment, newFragment); // Do something when the slide changes. } void loadMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } }
4,256
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipelineService.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/PipelineService.java
/* * PipelineService.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Build; import android.os.IBinder; import hcm.ssj.core.Pipeline; import hcm.ssj.creator.R; import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION; /** * Created by Michael Dietz on 10.09.2021. */ public class PipelineService extends Service { public static final int ONGOING_NOTIFICATION_ID = 1; public static final String SERVICE_NOTIFICATION_CHANNEL = "hcm.ssj.creator"; public static final String SERVICE_NOTIFICATION_CHANNEL_NAME = "Pipeline Service"; Pipeline pipeline; @Override public IBinder onBind(Intent intent) { // Don't allow binding return null; } @Override public void onCreate() { super.onCreate(); startForegroundNotification(); startPipeline(); } private void startPipeline() { pipeline = Pipeline.getInstance(); if (!pipeline.isRunning()) { new Thread() { @Override public void run() { pipeline.start(); } }.start(); } } @Override public void onDestroy() { super.onDestroy(); } private void startForegroundNotification() { Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Builder builder = new Notification.Builder(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create separate notification channel NotificationChannel channel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL, SERVICE_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); builder = builder.setChannelId(SERVICE_NOTIFICATION_CHANNEL); } Notification notification = builder.setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.str_notification_text)) .setSmallIcon(R.drawable.logo_small_black) .setContentIntent(pendingIntent) .setTicker(getString(R.string.str_notification_text)) .build(); startForeground(ONGOING_NOTIFICATION_ID, notification); } }
3,799
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
TrainActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/activity/TrainActivity.java
/* * TrainActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.text.InputType; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import hcm.ssj.core.Annotation; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.stream.Stream; import hcm.ssj.creator.R; import hcm.ssj.creator.core.SSJDescriptor; import hcm.ssj.creator.util.FileChooser; import hcm.ssj.file.FileCons; import hcm.ssj.ml.Model; import hcm.ssj.ml.NaiveBayes; import hcm.ssj.ml.SVM; import hcm.ssj.ml.Session; import hcm.ssj.ml.TensorFlow; /** * Visualize user-saved stream file data with the GraphView. */ public class TrainActivity extends AppCompatActivity { private Activity activity = this; ArrayList<Session> sessions = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.train_layout); //setup session list Button btn_add_session = (Button) findViewById(R.id.button_session_list_add); btn_add_session.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LinearLayout sessionList = (LinearLayout) findViewById(R.id.session_list); int id = sessions.size(); Session session = new Session(); session.name = "Session " + id; sessions.add(session); sessionList.addView(createSessionView(session), id +1); } }); final EditText textModelPath = (EditText) findViewById(R.id.model_filepath); textModelPath.setText(FileCons.MODELS_DIR); ImageButton butModelPath = (ImageButton) findViewById(R.id.model_filepath_button); butModelPath.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String startPath = (textModelPath.getText().toString().isEmpty()) ? FileCons.SSJ_EXTERNAL_STORAGE : textModelPath.getText().toString(); FileChooser chooser = new FileChooser(activity, startPath, true, null) { @Override public void onResult(String path, File pathFile) { textModelPath.setText(path); } }; chooser.show(); } }); //populate Model list ArrayList<String> items = new ArrayList<>(); for(Class<?> model : SSJDescriptor.getInstance().models) { try { if(model.getMethod("train", Stream.class, String.class).getDeclaringClass() == model) items.add(model.getSimpleName()); } catch (NoSuchMethodException e) { //do nothing, method is not implemented for model, thus ignore } } ((Spinner) findViewById(R.id.model_selector)).setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items)); Button butTrain = (Button) findViewById(R.id.train_button); butTrain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view.setEnabled(false); new Thread(new Runnable() { @Override public void run() { trainModel(); } }).start(); } }); } private View createSessionView(final Session session_obj) { LinearLayout sessionLayout = new LinearLayout(this); sessionLayout.setBackgroundColor(Color.parseColor("#EEEEEE")); final TextView textView = new TextView(this); textView.setText(session_obj.name); textView.setTextSize(textView.getTextSize() * 0.5f); int dpValue = 8; // margin in dips float d = getResources().getDisplayMetrics().density; int margin = (int) (dpValue * d); // margin in pixels LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(margin, margin, margin, 0); sessionLayout.setLayoutParams(params); sessionLayout.addView(textView); //define popup for clicking on a session textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { //content LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setOrientation(LinearLayout.VERTICAL); final EditText nameText = new EditText(activity); nameText.setInputType(InputType.TYPE_CLASS_TEXT); nameText.setText(((TextView) v).getText(), TextView.BufferType.NORMAL); linearLayout.addView(nameText); LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams text_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.9f); LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams((int)(50 * getResources().getDisplayMetrics().density), ViewGroup.LayoutParams.MATCH_PARENT); //stream file LinearLayout streamLayout = new LinearLayout(activity); streamLayout.setOrientation(LinearLayout.HORIZONTAL); streamLayout.setLayoutParams(layout_params); final EditText streamFile = new EditText(activity); streamFile.setInputType(InputType.TYPE_CLASS_TEXT); streamFile.setHint(R.string.train_load_stream_hint); streamFile.setText(session_obj.stream_path); streamFile.setLayoutParams(text_params); streamLayout.addView(streamFile); ImageButton streamLoadButton = new ImageButton(activity); streamLoadButton.setLayoutParams(button_params); streamLoadButton.setPadding(0, 10, 0, 0); streamLoadButton.setImageResource(R.drawable.ic_insert_drive_file_black_24dp); streamLoadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String startPath = (streamFile.getText().toString().isEmpty()) ? FileCons.SSJ_EXTERNAL_STORAGE : streamFile.getText().toString(); FileChooser chooser = new FileChooser(activity, startPath, false, "stream") { @Override public void onResult(String path, File pathFile) { streamFile.setText(path); } }; chooser.show(); } }); streamLayout.addView(streamLoadButton); linearLayout.addView(streamLayout); //anno file LinearLayout annoLayout = new LinearLayout(activity); streamLayout.setOrientation(LinearLayout.HORIZONTAL); annoLayout.setLayoutParams(layout_params); final EditText annoFile = new EditText(activity); annoFile.setHint(R.string.train_load_anno_hint); annoFile.setText(session_obj.anno_path); annoFile.setInputType(InputType.TYPE_CLASS_TEXT); annoFile.setLayoutParams(text_params); annoLayout.addView(annoFile); ImageButton annoLoadButton = new ImageButton(activity); annoLoadButton.setLayoutParams(button_params); annoLoadButton.setPadding(0, 10, 0, 0); annoLoadButton.setImageResource(R.drawable.ic_insert_drive_file_black_24dp); annoLoadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String startPath = FileCons.SSJ_EXTERNAL_STORAGE; if(!annoFile.getText().toString().isEmpty()) startPath = annoFile.getText().toString(); else if(!streamFile.getText().toString().isEmpty()) startPath = streamFile.getText().toString(); FileChooser chooser = new FileChooser(activity, startPath, false, "annotation") { @Override public void onResult(String path, File pathFile) { annoFile.setText(path); } }; chooser.show(); } }); annoLayout.addView(annoLoadButton); linearLayout.addView(annoLayout); //dialog AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.str_session); builder.setView(linearLayout); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ViewGroup viewGroup = (ViewGroup) v.getParent(); String name = nameText.getText().toString().trim(); ((TextView) viewGroup.getChildAt(0)).setText(name); session_obj.anno_path = annoFile.getText().toString(); session_obj.stream_path = streamFile.getText().toString(); } }); builder.setNegativeButton(R.string.str_cancel, null); builder.setNeutralButton(R.string.str_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ViewGroup viewGroup = (ViewGroup) v.getParent(); if (viewGroup != null) { sessions.remove(session_obj); ((ViewGroup) viewGroup.getParent()).removeView(viewGroup); } v.invalidate(); } }); AlertDialog alert = builder.create(); alert.show(); } }); return sessionLayout; } private void trainModel() { if(sessions.isEmpty()) { showToast("no data sources provided", Toast.LENGTH_SHORT); return; } SparseArray<String> classes = new SparseArray<>(); for(int i = 0; i< sessions.size(); i++) { Session session = sessions.get(i); //load stream try { session.stream = Stream.load(session.stream_path); } catch (Exception e) { Log.e("error loading stream file", e); showToast("error loading stream file", Toast.LENGTH_SHORT); return; } //check if streams match if(i != 0) { if(session.stream.dim != sessions.get(0).stream.dim) { String msg = "stream dimension mismatch: " + session.stream.dim +"!=" + sessions.get(0).stream.dim; Log.e(msg); showToast(msg, Toast.LENGTH_SHORT); return; } if(session.stream.sr != sessions.get(0).stream.sr) { String msg = "stream sr mismatch: " + session.stream.sr +"!=" + sessions.get(0).stream.sr; Log.e(msg); showToast(msg, Toast.LENGTH_SHORT); return; } if(session.stream.type != sessions.get(0).stream.type) { String msg = "stream type mismatch: " + session.stream.type +"!=" + sessions.get(0).stream.type; Log.e(msg); showToast(msg, Toast.LENGTH_SHORT); return; } } //load anno try { session.anno = new Annotation(); session.anno.load(session.anno_path); } catch (IOException | XmlPullParserException e) { Log.e("error loading anno file", e); Toast.makeText(this, "error loading anno file", Toast.LENGTH_SHORT).show(); return; } String emptyClass = null; CheckBox checkBox = (CheckBox) findViewById(R.id.train_anno_garbage); if (checkBox.isChecked()) { emptyClass = Cons.GARBAGE_CLASS; } session.anno.convertToFrames(1.0 / session.stream.sr, emptyClass, 0, 0.5f); //update known classes for (int j = 0; j < session.anno.getClasses().size(); j++) { classes.put(session.anno.getClasses().keyAt(j), session.anno.getClasses().valueAt(j)); } } String str_model = ((Spinner) findViewById(R.id.model_selector)).getSelectedItem().toString(); Model model = null; if(str_model.compareToIgnoreCase("NaiveBayes") == 0 || str_model.compareToIgnoreCase("OnlineNaiveBayes") == 0) model = new NaiveBayes(); else if (str_model.compareToIgnoreCase("SVM") == 0) model = new SVM(); else if (str_model.compareToIgnoreCase("PythonModel") == 0) model = new TensorFlow(); if (model == null) { showToast("unknown model", Toast.LENGTH_SHORT); return; } //todo merge multiple streams showToast("model training started", Toast.LENGTH_SHORT); //init model String classes_array[] = new String[classes.size()]; for (int i = 0; i < classes.size(); i++) { classes_array[i] = classes.valueAt(i); } Stream stream = sessions.get(0).stream; model.setup(classes_array, stream.bytes, stream.dim, stream.sr, stream.type); //train for(Session session : sessions) model.train(session.stream, session.anno); // save model String str_path = ((EditText) findViewById(R.id.model_filepath)).getText().toString(); String str_name = ((EditText) findViewById(R.id.model_filename)).getText().toString(); try { model.save(str_path, str_name); showToast("model training finished", Toast.LENGTH_SHORT); } catch (IOException e) { Log.e("error writing model file", e); showToast("error writing model file", Toast.LENGTH_SHORT); } //enable button this.runOnUiThread(new Runnable() { @Override public void run() { findViewById(R.id.train_button).setEnabled(true); } }); } private void showToast(final String text, final int duration) { final Activity act = this; this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(act, text, duration).show(); } }); } }
14,556
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
BandComm.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/BandComm.java
/* * BandComm.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.AsyncTask; import android.util.Log; import com.microsoft.band.BandClient; import com.microsoft.band.BandClientManager; import com.microsoft.band.BandException; import com.microsoft.band.BandIOException; import com.microsoft.band.BandInfo; import com.microsoft.band.ConnectionState; import com.microsoft.band.notifications.MessageFlags; import com.microsoft.band.notifications.VibrationType; import com.microsoft.band.tiles.BandTile; import com.microsoft.band.tiles.pages.FlowPanel; import com.microsoft.band.tiles.pages.FlowPanelOrientation; import com.microsoft.band.tiles.pages.HorizontalAlignment; import com.microsoft.band.tiles.pages.PageData; import com.microsoft.band.tiles.pages.PageLayout; import com.microsoft.band.tiles.pages.TextBlock; import com.microsoft.band.tiles.pages.TextBlockData; import com.microsoft.band.tiles.pages.TextBlockFont; import com.microsoft.band.tiles.pages.TextButton; import com.microsoft.band.tiles.pages.TextButtonData; import com.microsoft.band.tiles.pages.VerticalAlignment; import java.util.Date; import java.util.List; import java.util.UUID; import hcm.ssj.creator.R; /** * Created by Johnny on 01.02.2017. */ public class BandComm { BandClient client; public static final int BTN_YES = 1; public static final int BTN_NO = 2; public static final int TXT_TITLE = 3; public static final UUID tileId = UUID.nameUUIDFromBytes("SSJCreator-tile".getBytes());//fromString("cc0D508F-70A3-47D4-BBA3-812BADB1F8Aa"); public static final UUID pageId = UUID.nameUUIDFromBytes("SSJCreator-page".getBytes());//UUID.fromString("b1234567-89ab-cdef-0123-456789abcd00"); Activity activity = null; private String tileTitle = "SSJ"; public BandComm(Activity activity) { this.activity = activity; } public void create() { new StartTask().execute(); } public void destroy() { new StopTask().execute(); } public void popup(String title, String body) { new PingTask(title, body).execute(); } public boolean isBandInitialized() { try { if (getConnectedBandClient() && doesTileExist()) return true; else return false; } catch (BandException | InterruptedException e) { Log.e(this.getClass().getSimpleName(), "exception", e); return false; } } private class StartTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { try { if (getConnectedBandClient()) { Log.i(this.getClass().getSimpleName(), "seting up Band"); if (addTile()) { updatePages(); } else { Log.e(this.getClass().getSimpleName(), "Cannot find Band tile, make sure the band has been set up."); return false; } } else { Log.e(this.getClass().getSimpleName(), "Band isn't connected. Please make sure bluetooth is on and the band is in range.\n"); return false; } } catch (BandException e) { handleBandException(e); return false; } catch (Exception e) { Log.e(this.getClass().getSimpleName(), e.getMessage()); return false; } return true; } } public class StopTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { try { if (getConnectedBandClient()) { Log.i(this.getClass().getSimpleName(), "removing tile from Band."); removeTile(); } else { Log.e(this.getClass().getSimpleName(), "Band isn't connected. Please make sure bluetooth is on and the band is in range.\n"); return false; } } catch (BandException e) { handleBandException(e); return false; } catch (Exception e) { Log.e(this.getClass().getSimpleName(), e.getMessage()); return false; } return true; } } private class PingTask extends AsyncTask<Void, Void, Boolean> { String title; String body; public PingTask(String title, String body) { this.title = title; this.body = body; } @Override protected Boolean doInBackground(Void... params) { try { if (getConnectedBandClient()) { sendMessage(title, body); } else { Log.e(this.getClass().getSimpleName(), "Band isn't connected. Please make sure bluetooth is on and the band is in range.\n"); return false; } } catch (BandException e) { handleBandException(e); return false; } catch (Exception e) { Log.e(this.getClass().getSimpleName(), e.getMessage()); return false; } return true; } } private boolean sendMessage(String title, String body) throws Exception { if (!doesTileExist()) { return false; } client.getNotificationManager().vibrate(VibrationType.ONE_TONE_HIGH); Thread.sleep(500); client.getNotificationManager().sendMessage(tileId, title, body, new Date(), MessageFlags.SHOW_DIALOG); Log.i(this.getClass().getSimpleName(), "notification sent to msband"); //clear page to remove notification message client.getTileManager().removePages(tileId); updatePages(); return true; } private boolean getConnectedBandClient() throws InterruptedException, BandException { if (client == null) { BandInfo[] devices = BandClientManager.getInstance().getPairedBands(); if (devices.length == 0) { Log.e(this.getClass().getSimpleName(), "Band isn't paired with your phone."); return false; } client = BandClientManager.getInstance().create(activity.getApplicationContext(), devices[0]); } else if (ConnectionState.CONNECTED == client.getConnectionState()) { return true; } Log.i(this.getClass().getSimpleName(), "Band is connecting...\n"); return ConnectionState.CONNECTED == client.connect().await(); } private boolean doesTileExist() throws BandIOException, InterruptedException, BandException { List<BandTile> tiles = client.getTileManager().getTiles().await(); for (BandTile tile : tiles) { if (tile.getTileId().equals(tileId)) { return true; } } return false; } private boolean addTile() throws Exception { if (doesTileExist()) { return true; } /* Set the options */ BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap tileIcon = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(), R.drawable.logo_small, options); BandTile tile = new BandTile.Builder(tileId, tileTitle, tileIcon) .setPageLayouts(createButtonLayout()) .build(); if (client.getTileManager().addTile(activity, tile).await()) { Log.i(this.getClass().getSimpleName(), "Button Tile has been added to msband."); return true; } else { Log.e(this.getClass().getSimpleName(), "Unable to add button tile to ms band."); return false; } } private void removeTile() throws BandIOException, InterruptedException, BandException { if (doesTileExist()) { client.getTileManager().removeTile(tileId).await(); } } private PageLayout createButtonLayout() { return new PageLayout( new FlowPanel(15, 0, 243, 120, FlowPanelOrientation.VERTICAL) .addElements(new TextBlock(0, 0, 243, 40, TextBlockFont.SMALL).setId(TXT_TITLE)) .addElements(new FlowPanel(0, 0, 243, 80, FlowPanelOrientation.HORIZONTAL) .addElements(new TextButton(0, 0, 100, 70).setMargins(5, 5, 5, 5).setId(BTN_YES).setPressedColor(Color.GREEN).setHorizontalAlignment(HorizontalAlignment.CENTER).setVerticalAlignment(VerticalAlignment.CENTER)) .addElements(new TextButton(100, 0, 100, 70).setMargins(5, 5, 5, 5).setId(BTN_NO).setPressedColor(Color.RED).setHorizontalAlignment(HorizontalAlignment.CENTER).setVerticalAlignment(VerticalAlignment.CENTER)))); } private void updatePages() throws BandIOException { client.getTileManager().setPages(tileId, new PageData(pageId, 0) .update(new TextButtonData(BTN_YES, "Start")) .update(new TextButtonData(BTN_NO, "End")) .update(new TextBlockData(TXT_TITLE, "Annotation"))); } private void handleBandException(BandException e) { String exceptionMessage = ""; switch (e.getErrorType()) { case DEVICE_ERROR: exceptionMessage = "Please make sure bluetooth is on and the band is in range.\n"; break; case UNSUPPORTED_SDK_VERSION_ERROR: exceptionMessage = "Microsoft Health BandService doesn't support your SDK Version. Please update to latest SDK.\n"; break; case SERVICE_ERROR: exceptionMessage = "Microsoft Health BandService is not available. Please make sure Microsoft Health is installed and that you have the correct permissions.\n"; break; case BAND_FULL_ERROR: exceptionMessage = "Band is full. Please use Microsoft Health to remove a tile.\n"; break; default: exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n"; break; } Log.e(this.getClass().getSimpleName(), exceptionMessage); } }
12,179
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipelineBuilder.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/PipelineBuilder.java
/* * PipelineBuilder.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import hcm.ssj.core.Annotation; import hcm.ssj.core.Component; import hcm.ssj.core.Consumer; import hcm.ssj.core.EventChannel; import hcm.ssj.core.EventHandler; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.core.SSJException; import hcm.ssj.core.Sensor; import hcm.ssj.core.SensorChannel; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.creator.core.container.ContainerElement; import hcm.ssj.creator.core.container.FeedbackCollectionContainerElement; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.ml.IModelHandler; import hcm.ssj.ml.Model; import hcm.ssj.ml.Trainer; /** * Linker for a pipeline.<br> * Created by Frank Gaibler on 09.03.2016. */ public class PipelineBuilder { private static PipelineBuilder instance = null; protected LinkedHashSet<ContainerElement<SensorChannel>> hsSensorChannelElements = new LinkedHashSet<>(); protected LinkedHashSet<ContainerElement<Sensor>> hsSensorElements = new LinkedHashSet<>(); protected LinkedHashSet<ContainerElement<Transformer>> hsTransformerElements = new LinkedHashSet<>(); protected LinkedHashSet<ContainerElement<Consumer>> hsConsumerElements = new LinkedHashSet<>(); protected LinkedHashSet<ContainerElement<EventHandler>> hsEventHandlerElements = new LinkedHashSet<>(); protected LinkedHashSet<ContainerElement<Model>> hsModelElements = new LinkedHashSet<>(); protected Annotation anno; /** * */ private PipelineBuilder() { } /** * @return Linker */ public static synchronized PipelineBuilder getInstance() { if (instance == null) { instance = new PipelineBuilder(); } return instance; } /** * @param o Object * @return Option[] */ public static Option[] getOptionList(Object o) { try { Method[] methods = o.getClass().getMethods(); for (Method method : methods) { if (method.getName().equals("getOptions")) { OptionList list = (OptionList) method.invoke(o); if(list != null) return list.getOptions(); else return null; } } } catch (SecurityException | IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } return null; } public FeedbackCollectionContainerElement getFeedbackCollectionContainerElement(FeedbackCollection feedbackCollection) { for(ContainerElement<EventHandler> containerElement : hsEventHandlerElements) { if(containerElement.getElement().equals(feedbackCollection)) { return (FeedbackCollectionContainerElement) containerElement; } } return null; } /** * */ public void clear() { hsSensorChannelElements.clear(); hsSensorElements.clear(); hsTransformerElements.clear(); hsConsumerElements.clear(); hsEventHandlerElements.clear(); hsModelElements.clear(); if(anno != null) anno.clear(); } public Component getComponentForHash(int hash) { for (ContainerElement containerElement : hsSensorElements) { Sensor element = (Sensor) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } for (ContainerElement containerElement : hsSensorChannelElements) { SensorChannel element = (SensorChannel) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } for (ContainerElement containerElement : hsTransformerElements) { Transformer element = (Transformer) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } for (ContainerElement containerElement : hsConsumerElements) { Consumer element = (Consumer) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } for (ContainerElement containerElement : hsEventHandlerElements) { EventHandler element = (EventHandler) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } for (ContainerElement containerElement : hsModelElements) { Model element = (Model) containerElement.getElement(); if (element.hashCode() == hash) { return element; } } return null; } public List<Component> getComponentsOfClass(Type type, Class componentClass) { List<Component> componentList = new ArrayList<>(); Object[] componentsOfType = getAll(type); for (Object component : componentsOfType) { if (componentClass.isInstance(component)) { componentList.add((Component) component); } } return componentList; } /** * @param type Type */ public Object[] getAll(Type type) { switch (type) { case Sensor: { Object[] objects = new Object[hsSensorElements.size()]; int i = 0; for (ContainerElement element : hsSensorElements) { objects[i] = element.getElement(); i++; } return objects; } case SensorChannel: { Object[] objects = new Object[hsSensorChannelElements.size()]; int i = 0; for (ContainerElement element : hsSensorChannelElements) { objects[i] = element.getElement(); i++; } return objects; } case Transformer: { Object[] objects = new Object[hsTransformerElements.size()]; int i = 0; for (ContainerElement element : hsTransformerElements) { objects[i] = element.getElement(); i++; } return objects; } case Consumer: { Object[] objects = new Object[hsConsumerElements.size()]; int i = 0; for (ContainerElement element : hsConsumerElements) { objects[i] = element.getElement(); i++; } return objects; } case EventHandler: { Object[] objects = new Object[hsEventHandlerElements.size()]; int i = 0; for (ContainerElement element : hsEventHandlerElements) { objects[i] = element.getElement(); i++; } return objects; } case Model: { Object[] objects = new Object[hsModelElements.size()]; int i = 0; for (ContainerElement element : hsModelElements) { objects[i] = element.getElement(); i++; } return objects; } default: throw new RuntimeException(); } } /** * */ public void buildPipe() throws SSJException { resetElementsState(); Pipeline framework = Pipeline.getInstance(); //add to framework //sensors and sensorChannels for (ContainerElement<Sensor> sensor : hsSensorElements) { HashSet<ContainerElement<Provider>> channels = sensor.getStreamConnectionContainers(); if (channels.size() > 0) { for (ContainerElement<?> channel : channels) { framework.addSensor(sensor.getElement(), (SensorChannel) channel.getElement()); sensor.setAdded(true); channel.setAdded(true); } } } //models for (ContainerElement<Model> element : hsModelElements) { Model model = element.getElement(); framework.addModel(model); HashSet<ContainerElement<IModelHandler>> handlers = element.getModelConnectionContainers(); if (handlers.size() > 0) { for (ContainerElement<IModelHandler> handler : handlers) { handler.getElement().setModel(model); } } } //transformers int count = 0; int lastCount = -1; while (count < hsTransformerElements.size() && count != lastCount) { lastCount = count; for (ContainerElement<Transformer> transformer : hsTransformerElements) { if (transformer.getStreamConnectionContainers().size() > 0) { if (transformer.allStreamConnectionsAdded() && !transformer.hasBeenAdded()) { Provider[] sources = transformer.getStreamConnections(); double frame = (transformer.getFrameSize() != null) ? transformer.getFrameSize() : sources[0].getOutputStream().num / sources[0].getOutputStream().sr; framework.addTransformer(transformer.getElement(), sources, frame, transformer.getDelta()); transformer.setAdded(true); count++; } } else { count++; } } } //consumers //Avoid reregistering consumers as eventlisteners if they are triggered by event LinkedHashSet<ContainerElement<Consumer>> hsConsumerElementsNotTriggeredByEvent = new LinkedHashSet<>(); for (ContainerElement<Consumer> consumer : hsConsumerElements) { EventChannel trigger = null; Object triggerSource = consumer.getEventTrigger(); if(triggerSource != null && triggerSource instanceof Component) trigger = ((Component)triggerSource).getEventChannelOut(); else if(triggerSource != null && triggerSource instanceof Annotation) trigger = ((Annotation)triggerSource).getChannel(); if (consumer.getStreamConnectionContainers().size() > 0 && consumer.allStreamConnectionsAdded()) { Provider[] sources = consumer.getStreamConnections(); double frame = (consumer.getFrameSize() != null) ? consumer.getFrameSize() : sources[0].getOutputStream().num / sources[0].getOutputStream().sr; if (trigger != null) { framework.addConsumer(consumer.getElement(), sources, trigger); } else { framework.addConsumer(consumer.getElement(), sources, frame, consumer.getDelta()); hsConsumerElementsNotTriggeredByEvent.add(consumer); } } //special case: Trainer if(consumer.getElement() instanceof Trainer) { Trainer trainer = (Trainer)consumer.getElement(); getAnnotation().setClasses(trainer.getModel().getClassNames()); } } buildEventPipeline(hsSensorElements); buildEventPipeline(hsSensorChannelElements); buildEventPipeline(hsTransformerElements); buildEventPipeline(hsConsumerElementsNotTriggeredByEvent); buildEventPipeline(hsEventHandlerElements); } private void resetElementsState() { for (ContainerElement<?> element : hsSensorElements) { element.reset(); } for (ContainerElement<?> element : hsSensorChannelElements) { element.reset(); } for (ContainerElement<?> element : hsTransformerElements) { element.reset(); } for (ContainerElement<?> element : hsConsumerElements) { element.reset(); } for (ContainerElement<?> element : hsModelElements) { element.reset(); } for (ContainerElement<?> element : hsEventHandlerElements) { element.reset(); } } private <T extends Component> void buildEventPipeline(LinkedHashSet<ContainerElement<T>> hsElements) { for (ContainerElement<T> element : hsElements) { if (!element.getEventConnectionContainers().isEmpty()) { for (Component component : element.getEventConnections()) { Pipeline.getInstance().registerEventListener(element.getElement(), component.getEventChannelOut()); } } } // Register elements in feedback container AFTER all elements are registered! for (ContainerElement<T> element : hsElements) { if (element instanceof FeedbackCollectionContainerElement) { FeedbackCollection feedbackCollection = (FeedbackCollection) element.getElement(); List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackList = ((FeedbackCollectionContainerElement) element).getFeedbackList(); Pipeline.getInstance().registerInFeedbackCollection(feedbackCollection, feedbackList); } } } /** * @param o Object * @return boolean */ public boolean add(Object o) { //sensorChannel if (o instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(o)) { return false; } } return hsSensorChannelElements.add(new ContainerElement<>((SensorChannel) o)); } //sensor else if (o instanceof Sensor) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return false; } } return hsSensorElements.add(new ContainerElement<>((Sensor) o)); } //transformer else if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return false; } } return hsTransformerElements.add(new ContainerElement<>((Transformer) o)); } //consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return false; } } return hsConsumerElements.add(new ContainerElement<>((Consumer) o)); } //eventhandler else if (o instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(o)) { return false; } } if(o instanceof FeedbackCollection) return hsEventHandlerElements.add(new FeedbackCollectionContainerElement((FeedbackCollection) o)); else return hsEventHandlerElements.add(new ContainerElement<>((EventHandler) o)); } //Models else if (o instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(o)) { return false; } } return hsModelElements.add(new ContainerElement<>((Model) o)); } return false; } /** * @param o Object * @return boolean */ public boolean remove(Object o) { removeAllReferences((Component) o); //sensor if (o instanceof Sensor) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return hsSensorElements.remove(element); } } } //sensorChannel else if (o instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(o)) { return hsSensorChannelElements.remove(element); } } } //transformer else if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return hsTransformerElements.remove(element); } } } //consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return hsConsumerElements.remove(element); } } } //EventHandler else if (o instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(o)) { return hsEventHandlerElements.remove(element); } } } //Models else if (o instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(o)) { return hsModelElements.remove(element); } } } return false; } private void removeAllReferences(Component component) { ContainerElement<?> containerElement = getContainerElement(component); for (ContainerElement<Sensor> sensor : hsSensorElements) { if (component instanceof Provider) { sensor.removeStreamConnection((ContainerElement<Provider>)containerElement); } sensor.removeEventConnection((ContainerElement<Component>)containerElement); } for (ContainerElement<SensorChannel> sensorChannel : hsSensorChannelElements) { if (component instanceof Provider) { sensorChannel.removeStreamConnection((ContainerElement<Provider>)containerElement); } sensorChannel.removeEventConnection((ContainerElement<Component>)containerElement); } for (ContainerElement<Transformer> transformer : hsTransformerElements) { if (component instanceof Provider) { transformer.removeStreamConnection((ContainerElement<Provider>)containerElement); } transformer.removeEventConnection((ContainerElement<Component>)containerElement); } for (ContainerElement<Consumer> consumer : hsConsumerElements) { if (component instanceof Provider) { consumer.removeStreamConnection((ContainerElement<Provider>)containerElement); } consumer.removeEventConnection((ContainerElement<Component>)containerElement); } for (ContainerElement<EventHandler> eventHandler : hsEventHandlerElements) { eventHandler.removeEventConnection((ContainerElement<Component>)containerElement); } for (ContainerElement<Model> model : hsModelElements) { if (component instanceof IModelHandler) { model.removeModelConnection((ContainerElement<IModelHandler>)containerElement); } } } /** * @param o Object * @return Object[] */ public Object[] getStreamConnections(Object o) { if (o instanceof Transformer) { for (ContainerElement element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.getStreamConnections(); } } } else if (o instanceof Consumer) { for (ContainerElement element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.getStreamConnections(); } } } else if (o instanceof Sensor) { for (ContainerElement element : hsSensorElements) { if (element.getElement().equals(o)) { return element.getStreamConnections(); } } } return null; } public void addFeedbackToCollectionContainer(FeedbackCollection feedbackCollection, Feedback feedback, int level, FeedbackCollection.LevelBehaviour levelBehaviour) { add(feedback); // Add to container for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(feedbackCollection)) { ((FeedbackCollectionContainerElement) element).addFeedback(feedback, level, levelBehaviour); } } } public ContainerElement<?> getContainerElement(Component component) { //sensorChannels if (component instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(component)) { return element; } } } //transformers else if (component instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(component)) { return element; } } } //consumers else if (component instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(component)) { return element; } } } //sensors else if (component instanceof Sensor) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(component)) { return element; } } } //models else if (component instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(component)) { return element; } } } //eventhandlers else if (component instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(component)) { return element; } } } return null; } /** * @param o Object * @param provider Provider * @return boolean */ public boolean addStreamConnection(Object o, Provider provider) { ContainerElement<Provider> providerContainer = (ContainerElement<Provider>)getContainerElement(provider); //add to sensor if (o instanceof Sensor && provider instanceof SensorChannel) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return element.addStreamConnection(providerContainer); } } } //add to transformer if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { //prevent adding it to itself if (element.getElement().equals(o) && !element.getElement().equals(provider)) { return element.addStreamConnection(providerContainer); } } } //add to consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.addStreamConnection(providerContainer); } } } return false; } /** * @param o Object * @param provider Provider * @return boolean */ public boolean removeStreamConnection(Object o, Provider provider) { ContainerElement<Provider> providerContainer = (ContainerElement<Provider>)getContainerElement(provider); //remove from sensor if (o instanceof Sensor && provider instanceof SensorChannel) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return element.removeStreamConnection(providerContainer); } } } //remove from transformer if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.removeStreamConnection(providerContainer); } } } //remove from consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.removeStreamConnection(providerContainer); } } } return false; } /** * @param o Object * @return Double */ public Double getFrameSize(Object o) { if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.getFrameSize(); } } } else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.getFrameSize(); } } } return null; } /** * @param o Object * @param frameSize Double * @return boolean */ public boolean setFrameSize(Object o, Double frameSize) { if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { element.setFrameSize(frameSize); return true; } } } else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { element.setFrameSize(frameSize); return true; } } } return false; } /** * @param o Object * @return double */ public double getDelta(Object o) { if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.getDelta(); } } } else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.getDelta(); } } } return 0; } /** * @param o Object * @param delta double * @return boolean */ public boolean setDelta(Object o, double delta) { if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { element.setDelta(delta); return true; } } } else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { element.setDelta(delta); return true; } } } return false; } public boolean setEventTrigger(Object o, Object trigger) { if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { element.setEventTrigger(trigger); return true; } } } return false; } public Object getEventTrigger(Object o) { if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.getEventTrigger(); } } } return null; } /** * @return int */ public int getNumberOfStreamConnections() { int number = 0; for (ContainerElement<Sensor> element : hsSensorElements) { number += element.getStreamConnectionContainers().size(); } for (ContainerElement<Transformer> element : hsTransformerElements) { number += element.getStreamConnectionContainers().size(); } for (ContainerElement<Consumer> element : hsConsumerElements) { number += element.getStreamConnectionContainers().size(); } return number; } /** * @param o Object * @return int[] */ public int[] getStreamConnectionHashes(Object o) { //sensor if (o instanceof Sensor) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { Object[] objects = element.getStreamConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //transformer else if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { Object[] objects = element.getStreamConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { Object[] objects = element.getStreamConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } return null; } /** * @param o Object * @param provider Provider * @return boolean */ public boolean addEventConnection(Object o, Component provider) { ContainerElement<Component> providerContainer = (ContainerElement<Component>) getContainerElement(provider); //check for existence in //sensorChannels if (o instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(o)) { return element.addEventConnection(providerContainer); } } } //add to sensor if (o instanceof Sensor /*&& provider instanceof SensorChannel*/) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return element.addEventConnection(providerContainer); } } } //add to transformer if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { //prevent adding it to itself if (element.getElement().equals(o) && !element.getElement().equals(provider)) { return element.addEventConnection(providerContainer); } } } //add to consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.addEventConnection(providerContainer); } } } //add to eventhandler else if (o instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(o)) { return element.addEventConnection(providerContainer); } } } return false; } /** * @param o Object * @param provider Provider * @return boolean */ public boolean removeEventConnection(Object o, Component provider) { ContainerElement<Component> providerContainer = (ContainerElement<Component>) getContainerElement(provider); //check for existence in //sensorChannels if (o instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } //transformers else if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } //remove from sensor if (o instanceof Sensor /*&& provider instanceof SensorChannel*/) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } //remove from transformer if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } //remove from consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } //remove from eventhandler else if (o instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(o)) { return element.removeEventConnection(providerContainer); } } } return false; } /** * @return int */ public int getNumberOfEventConnections() { int number = 0; for (ContainerElement<Sensor> element : hsSensorElements) { number += element.getEventConnectionContainers().size(); } for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { number += element.getEventConnectionContainers().size(); } for (ContainerElement<Transformer> element : hsTransformerElements) { number += element.getEventConnectionContainers().size(); } for (ContainerElement<Consumer> element : hsConsumerElements) { number += element.getEventConnectionContainers().size(); } for (ContainerElement<EventHandler> element : hsEventHandlerElements) { number += element.getEventConnectionContainers().size(); } return number; } /** * @param o Object * @return Object[] */ public Object[] getEventConnections(Object o) { if (o instanceof Sensor) { for (ContainerElement element : hsSensorElements) { if (element.getElement().equals(o)) { return element.getEventConnections(); } } } else if (o instanceof SensorChannel) { for (ContainerElement element : hsSensorChannelElements) { if (element.getElement().equals(o)) { return element.getEventConnections(); } } } else if (o instanceof Transformer) { for (ContainerElement element : hsTransformerElements) { if (element.getElement().equals(o)) { return element.getEventConnections(); } } } else if (o instanceof Consumer) { for (ContainerElement element : hsConsumerElements) { if (element.getElement().equals(o)) { return element.getEventConnections(); } } } else if (o instanceof EventHandler) { for (ContainerElement element : hsEventHandlerElements) { if (element.getElement().equals(o)) { return element.getEventConnections(); } } } return null; } /** * @param o Object * @return int[] */ public int[] getEventConnectionHashes(Object o) { //sensor if (o instanceof Sensor) { for (ContainerElement<Sensor> element : hsSensorElements) { if (element.getElement().equals(o)) { Object[] objects = element.getEventConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //sensor channel else if (o instanceof SensorChannel) { for (ContainerElement<SensorChannel> element : hsSensorChannelElements) { if (element.getElement().equals(o)) { Object[] objects = element.getEventConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //transformer else if (o instanceof Transformer) { for (ContainerElement<Transformer> element : hsTransformerElements) { if (element.getElement().equals(o)) { Object[] objects = element.getEventConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //consumer else if (o instanceof Consumer) { for (ContainerElement<Consumer> element : hsConsumerElements) { if (element.getElement().equals(o)) { Object[] objects = element.getEventConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } //eventhandler else if (o instanceof EventHandler) { for (ContainerElement<EventHandler> element : hsEventHandlerElements) { if (element.getElement().equals(o)) { Object[] objects = element.getEventConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } return null; } public boolean isManagedFeedback(Object element) { if (!(element instanceof Feedback)) { return false; } for (ContainerElement<EventHandler> hsEventHandlerElement : hsEventHandlerElements) { if(hsEventHandlerElement instanceof FeedbackCollectionContainerElement) { for (Map<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourMap : ((FeedbackCollectionContainerElement) hsEventHandlerElement).getFeedbackList()) { if (feedbackLevelBehaviourMap.containsKey(element)) { return true; } } } } return false; } /** * @param start Component * @param end Component * @return boolean */ public boolean addModelConnection(Component start, Component end) { if (start instanceof IModelHandler && end instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(end)) { return element.addModelConnection((ContainerElement<IModelHandler>) getContainerElement(start)); } } } //add to sensor if (start instanceof Model && end instanceof IModelHandler) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(start)) { return element.addModelConnection((ContainerElement<IModelHandler>) getContainerElement(end)); } } } return false; } /** * @param start Component * @param end Component * @return boolean */ public boolean removeModelConnection(Component start, Component end) { if (start instanceof IModelHandler && end instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(end)) { return element.removeModelConnection((ContainerElement<IModelHandler>) getContainerElement(start)); } } } //add to sensor if (start instanceof Model && end instanceof IModelHandler) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(start)) { return element.removeModelConnection((ContainerElement<IModelHandler>) getContainerElement(end)); } } } return false; } /** * @param o Object * @return Object[] */ public Object[] getModelConnections(Object o) { if (o instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(o)) { return element.getModelConnections(); } } } if (o instanceof IModelHandler) { ArrayList<Model> connections = new ArrayList<>(); for (ContainerElement<Model> element : hsModelElements) { for(IModelHandler mh : element.getModelConnections()) { if (mh.equals(o)) { connections.add(element.getElement()); } } } return connections.toArray(); } return null; } /** * @return int */ public int getNumberOfModelConnections() { int number = 0; for (ContainerElement<Model> element : hsModelElements) { number += element.getModelConnectionContainers().size(); } return number; } public int[] getModelConnectionHashes(Object o) { //model if (o instanceof Model) { for (ContainerElement<Model> element : hsModelElements) { if (element.getElement().equals(o)) { Object[] objects = element.getModelConnections(); if (objects.length > 0) { int[] hashes = new int[objects.length]; for (int i = 0; i < objects.length; i++) { hashes[i] = objects[i].hashCode(); } return hashes; } return null; } } } return null; } public enum Type { Sensor, SensorChannel, Transformer, Consumer, EventHandler, Model, ModelHandler } /** * @return Object[] */ public Object[] getPossibleEventConnections(Object object) { //add possible providers ArrayList<Object> alCandidates = new ArrayList<>(); alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.Sensor))); alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.SensorChannel))); alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.Transformer))); alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.Consumer))); alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.EventHandler))); //remove oneself alCandidates.remove(object); return alCandidates.toArray(); } /** * @return Object[] */ public Object[] getModelHandlers() { //add possible providers ArrayList<Object> alCandidates = new ArrayList<>(); alCandidates.addAll(PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Consumer, IModelHandler.class)); alCandidates.addAll(PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.Transformer, IModelHandler.class)); return alCandidates.toArray(); } /** * @return Object[] */ public Object[] getPossibleStreamConnections(Object object) { //add possible providers Object[] sensProvCandidates = getAll(PipelineBuilder.Type.SensorChannel); ArrayList<Object> alCandidates = new ArrayList<>(); //only add sensorChannels for sensors if (!(object instanceof Sensor)) { alCandidates.addAll(Arrays.asList(getAll(PipelineBuilder.Type.Transformer))); //remove oneself for (int i = 0; i < alCandidates.size(); i++) { if (object.equals(alCandidates.get(i))) { alCandidates.remove(i); } } } alCandidates.addAll(0, Arrays.asList(sensProvCandidates)); return alCandidates.toArray(); } public synchronized boolean annotationExists() { return anno != null; } public synchronized Annotation getAnnotation() { if(anno == null) anno = new Annotation(); return anno; } }
41,376
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SaveLoad.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/SaveLoad.java
/* * SaveLoad.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core; import android.util.SparseArray; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import hcm.ssj.core.Annotation; import hcm.ssj.core.Component; import hcm.ssj.core.Consumer; import hcm.ssj.core.EventHandler; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.core.Sensor; import hcm.ssj.core.SensorChannel; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.Option; import hcm.ssj.creator.core.container.ContainerElement; import hcm.ssj.creator.util.ConnectionType; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.ml.IModelHandler; import hcm.ssj.ml.Model; /** * Save and load files in a {@link PipelineBuilder} friendly format.<br> * Created by Frank Gaibler on 28.06.2016. */ public abstract class SaveLoad { private final static String ROOT = "ssjSaveFile"; private final static String VERSION = "version"; private final static String VERSION_NUMBER = "7"; private final static String FRAMEWORK = "framework"; private final static String SENSOR_CHANNEL_LIST = "sensorChannelList"; private final static String SENSOR_LIST = "sensorList"; private final static String TRANSFORMER_LIST = "transformerList"; private final static String CONSUMER_LIST = "consumerList"; private final static String EVENT_HANDLER_LIST = "eventHandlerList"; private final static String SENSOR_CHANNEL = "sensorChannel"; private final static String SENSOR = "sensor"; private final static String TRANSFORMER = "transformer"; private final static String CONSUMER = "consumer"; private final static String EVENT_HANDLER = "eventHandler"; private final static String MODEL = "model"; private static final String MODEL_LIST = "modelList"; private final static String CLASS = "class"; private final static String ID = "id"; private final static String OPTIONS = "options"; private final static String OPTION = "option"; private final static String NAME = "name"; private final static String VALUE = "value"; private final static String CHANNEL_ID = "providerId"; private final static String CHANNEL_LIST = "providerList"; private final static String EVENT_CHANNEL_ID = "eventProviderId"; private final static String EVENT_CHANNEL_LIST = "eventProviderList"; private final static String MODEL_HANDLER_ID = "modelHandlerId"; private static final String MODEL_HANDLER_LIST = "modelHandlerList"; private final static String FRAME_SIZE = "frameSize"; private final static String DELTA = "delta"; private final static String EVENT_TRIGGER = "eventTrigger"; private static final String FEEDBACK_LEVEL_LIST = "feedbackLevelList"; private static final String FEEDBACK_LEVEL = "feedbackLevel"; private static final String FEEDBACK = "feedback"; private static final String LEVEL = "level"; private static final String FEEDBACK_BEHAVIOUR = "feedbackBehaviour"; private final static String ANNOTATION = "annotation"; private final static String ANNOTATION_CLASS = "class"; private final static String FILE_NAME = "fileName"; private final static String FILE_PATH = "filePath"; /** * Saves the values in {@link PipelineBuilder} * * @param file File * @return boolean */ public static boolean save(File file) { //open stream FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(file); } catch (FileNotFoundException e) { Log.e("file not found"); return false; } XmlSerializer serializer = Xml.newSerializer(); try { //start document serializer.setOutput(fileOutputStream, "UTF-8"); serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, ROOT); serializer.attribute(null, VERSION, VERSION_NUMBER); //framework serializer.startTag(null, FRAMEWORK); addOptions(serializer, Pipeline.getInstance()); serializer.endTag(null, FRAMEWORK); //sensorChannels serializer.startTag(null, SENSOR_CHANNEL_LIST); for (ContainerElement<SensorChannel> containerElement : PipelineBuilder.getInstance().hsSensorChannelElements) { addContainerElement(serializer, SENSOR_CHANNEL, containerElement, false); } serializer.endTag(null, SENSOR_CHANNEL_LIST); //sensors serializer.startTag(null, SENSOR_LIST); for (ContainerElement<Sensor> containerElement : PipelineBuilder.getInstance().hsSensorElements) { addContainerElement(serializer, SENSOR, containerElement, false); } serializer.endTag(null, SENSOR_LIST); //transformers serializer.startTag(null, TRANSFORMER_LIST); for (ContainerElement<Transformer> containerElement : PipelineBuilder.getInstance().hsTransformerElements) { addContainerElement(serializer, TRANSFORMER, containerElement, true); } serializer.endTag(null, TRANSFORMER_LIST); //consumers serializer.startTag(null, CONSUMER_LIST); for (ContainerElement<Consumer> containerElement : PipelineBuilder.getInstance().hsConsumerElements) { addContainerElement(serializer, CONSUMER, containerElement, true); } serializer.endTag(null, CONSUMER_LIST); //eventhandler serializer.startTag(null, EVENT_HANDLER_LIST); for (ContainerElement<EventHandler> containerElement : PipelineBuilder.getInstance().hsEventHandlerElements) { addContainerElement(serializer, EVENT_HANDLER, containerElement, true); } serializer.endTag(null, EVENT_HANDLER_LIST); //models serializer.startTag(null, MODEL_LIST); for (ContainerElement<Model> containerElement : PipelineBuilder.getInstance().hsModelElements) { addContainerElement(serializer, MODEL, containerElement, false); } serializer.endTag(null, MODEL_LIST); //annotation if(PipelineBuilder.getInstance().annotationExists()) { addAnnotation(serializer, PipelineBuilder.getInstance().getAnnotation()); } //finish document serializer.endTag(null, ROOT); serializer.endDocument(); serializer.flush(); } catch (IOException ex) { Log.e("could not save file"); return false; } finally { try { fileOutputStream.close(); } catch (IOException ex) { Log.e("could not close stream"); } } return true; } /** * @param File file * @return boolean */ public static boolean load(File file) { InputStream inputStream = null; try { inputStream = new FileInputStream(file); //check file version XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(inputStream, null); parser.nextTag(); if (parser.getName().equals(ROOT)) { String value = parser.getAttributeValue(null, VERSION); float versionFile = Float.parseFloat(value); float versionCurrent = Float.parseFloat(VERSION_NUMBER); if (versionFile < versionCurrent) { Log.i("old file version detected, converting from v" + versionFile + " to v" + versionCurrent); String text = convertOldVersion(file, versionFile); inputStream.close(); inputStream = new ByteArrayInputStream(text.getBytes()); //reset stream parser.setInput(inputStream, null); parser.nextTag(); } } else { return false; } //clear previous content Pipeline.getInstance().clear(); PipelineBuilder.getInstance().clear(); //load classes parser.nextTag(); String tag; Object context = null; Option[] options = null; LinkedHashMap<Object, LinkContainer> connectionMap = new LinkedHashMap<>(); LinkedHashMap<Object, LinkFeedbackCollection> feedbackCollectionMap = new LinkedHashMap<>(); while (!(tag = parser.getName()).equals(ROOT)) { if (parser.getEventType() == XmlPullParser.START_TAG) { switch (tag) { case FRAMEWORK: { context = Pipeline.getInstance(); break; } case OPTIONS: { options = PipelineBuilder.getOptionList(context); break; } case OPTION: { if (options != null) { String name = parser.getAttributeValue(null, NAME); String value = parser.getAttributeValue(null, VALUE); for (Option option : options) { if (option.getName().equals(name)) { option.setValue(value); break; } } } break; } case SENSOR_CHANNEL: case SENSOR: case MODEL: { String clazz = parser.getAttributeValue(null, CLASS); context = Class.forName(clazz).newInstance(); PipelineBuilder.getInstance().add(context); String hash = parser.getAttributeValue(null, ID); LinkContainer container = new LinkContainer(); container.hash = Integer.parseInt(hash); connectionMap.put(context, container); break; } case TRANSFORMER: case CONSUMER: case EVENT_HANDLER: { String clazz = parser.getAttributeValue(null, CLASS); context = Class.forName(clazz).newInstance(); PipelineBuilder.getInstance().add(context); Double frame = (parser.getAttributeValue(null, FRAME_SIZE) != null) ? Double.valueOf(parser.getAttributeValue(null, FRAME_SIZE)) : null; PipelineBuilder.getInstance().setFrameSize(context, frame); PipelineBuilder.getInstance().setDelta(context, Double.valueOf(parser.getAttributeValue(null, DELTA))); String hash = parser.getAttributeValue(null, ID); LinkContainer container = new LinkContainer(); container.hash = Integer.parseInt(hash); connectionMap.put(context, container); String trigger_hash = parser.getAttributeValue(null, EVENT_TRIGGER); if(trigger_hash != null) connectionMap.get(context).typedHashes.put(Integer.parseInt(trigger_hash), ConnectionType.EVENTTRIGGERCONNECTION); if (context instanceof FeedbackCollection) { LinkFeedbackCollection linkFeedbackCollection = new LinkFeedbackCollection(); linkFeedbackCollection.hash = Integer.parseInt(hash); feedbackCollectionMap.put(context, linkFeedbackCollection); } break; } case CHANNEL_ID: { String hash = parser.getAttributeValue(null, ID); connectionMap.get(context).typedHashes.put(Integer.parseInt(hash), ConnectionType.STREAMCONNECTION); break; } case EVENT_CHANNEL_ID: { String hash = parser.getAttributeValue(null, ID); connectionMap.get(context).typedHashes.put(Integer.parseInt(hash), ConnectionType.EVENTCONNECTION); break; } case MODEL_HANDLER_ID: { String hash = parser.getAttributeValue(null, ID); connectionMap.get(context).typedHashes.put(Integer.parseInt(hash), ConnectionType.MODELCONNECTION); break; } case FEEDBACK_LEVEL: { int level = Integer.parseInt(parser.getAttributeValue(null, LEVEL)); LinkFeedbackCollection contextLinkFeedbackCollection = feedbackCollectionMap.get(context); while (contextLinkFeedbackCollection.typedHashes.size() <= level) { contextLinkFeedbackCollection.typedHashes.add(new LinkedHashMap<Integer, FeedbackCollection.LevelBehaviour>()); } Map<Integer, FeedbackCollection.LevelBehaviour> levelLinkMap = contextLinkFeedbackCollection.typedHashes.get(level); parser.nextTag(); while (parser.getName().equals(FEEDBACK)) { if(parser.getEventType() == XmlPullParser.START_TAG) { int hash = Integer.parseInt(parser.getAttributeValue(null, ID)); FeedbackCollection.LevelBehaviour behaviour = FeedbackCollection.LevelBehaviour.valueOf(parser.getAttributeValue(null, FEEDBACK_BEHAVIOUR)); levelLinkMap.put(hash, behaviour); } parser.nextTag(); } break; } case ANNOTATION: { String hash = parser.getAttributeValue(null, ID); LinkContainer container = new LinkContainer(); container.hash = Integer.parseInt(hash); container.typedHashes.put(Integer.parseInt(hash), ConnectionType.EVENTTRIGGERCONNECTION); connectionMap.put(PipelineBuilder.getInstance().getAnnotation(), container); String filename = parser.getAttributeValue(null, FILE_NAME); if(filename != null && !filename.isEmpty()) PipelineBuilder.getInstance().getAnnotation().setFileName(filename); String filepath = parser.getAttributeValue(null, FILE_PATH); if(filepath != null && !filepath.isEmpty()) PipelineBuilder.getInstance().getAnnotation().setFilePath(filepath); break; } case ANNOTATION_CLASS: { String annoClass = parser.getAttributeValue(null, NAME); String annoClassId = parser.getAttributeValue(null, ID); PipelineBuilder.getInstance().getAnnotation().addClass(Integer.parseInt(annoClassId), annoClass); break; } } } parser.nextTag(); } setConnections(connectionMap); setInnerFeedbackCollectionComponents(feedbackCollectionMap, connectionMap); return true; } catch (IOException | XmlPullParserException ex) { Log.e("could not parse file", ex); return false; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Log.e("could not create class", ex); return false; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ex) { Log.e("could not close stream", ex); } } } private static void setConnections(LinkedHashMap<Object, LinkContainer> connectionMap) { for (Map.Entry<Object, LinkContainer> entry : connectionMap.entrySet()) { Object key = entry.getKey(); LinkContainer value = entry.getValue(); for (int provider : value.typedHashes.keySet()) { for (Map.Entry<Object, LinkContainer> candidate : connectionMap.entrySet()) { Object candidateKey = candidate.getKey(); LinkContainer candidateValue = candidate.getValue(); if (candidateValue.hash == provider) { if (value.typedHashes.get(provider).equals(ConnectionType.STREAMCONNECTION)) { PipelineBuilder.getInstance().addStreamConnection(key, (Provider) candidateKey); } else if (value.typedHashes.get(provider).equals(ConnectionType.EVENTCONNECTION)) { PipelineBuilder.getInstance().addEventConnection(key, (Component) candidateKey); } else if (value.typedHashes.get(provider).equals(ConnectionType.EVENTTRIGGERCONNECTION)) { PipelineBuilder.getInstance().setEventTrigger(key, candidateKey); } else if (value.typedHashes.get(provider).equals(ConnectionType.MODELCONNECTION)) { PipelineBuilder.getInstance().addModelConnection((Component) key, (Component) candidateKey); } } } } } } private static void setInnerFeedbackCollectionComponents(Map<Object, LinkFeedbackCollection> feedbackCollectionMap, Map<Object, LinkContainer> connectionMap) { //set inner components of FeedbackCollection for (Map.Entry<Object, LinkFeedbackCollection> entry : feedbackCollectionMap.entrySet()) { if (!(entry.getKey() instanceof FeedbackCollection)) { continue; } FeedbackCollection feedbackCollection = (FeedbackCollection) entry.getKey(); LinkFeedbackCollection linkFeedbackCollection = entry.getValue(); for (int level = 0; level < linkFeedbackCollection.typedHashes.size(); level++) { for (Map.Entry<Integer, FeedbackCollection.LevelBehaviour> feedbackEntry : linkFeedbackCollection.typedHashes.get(level).entrySet()) { for (Map.Entry<Object, LinkContainer> candidate : connectionMap.entrySet()) { if (candidate.getValue().hash == feedbackEntry.getKey()) { Feedback feedback = (Feedback) candidate.getKey(); PipelineBuilder.getInstance().addFeedbackToCollectionContainer(feedbackCollection, feedback, level, feedbackEntry.getValue()); } } } } } } /** * @param serializer XmlSerializer * @param object Object * @throws IOException */ private static void addStandard(XmlSerializer serializer, Object object) throws IOException { serializer.attribute(null, CLASS, object.getClass().getName()); serializer.attribute(null, ID, String.valueOf(object.hashCode())); } /** * @param serializer XmlSerializer * @param object Object * @throws IOException */ private static void addOptions(XmlSerializer serializer, Object object) throws IOException { serializer.startTag(null, OPTIONS); Option[] options = PipelineBuilder.getOptionList(object); if (options != null) { for (Option option : options) { if (option.isAssignableByString() && option.get() != null) { serializer.startTag(null, OPTION); serializer.attribute(null, NAME, option.getName()); if (option.getType().isArray()) { Object value = option.get(); List ar = new ArrayList(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { ar.add(Array.get(value, i)); } Object[] objects = ar.toArray(); serializer.attribute(null, VALUE, Arrays.toString(objects)); } else { serializer.attribute(null, VALUE, String.valueOf(option.get())); } serializer.endTag(null, OPTION); } } } serializer.endTag(null, OPTIONS); } /** * @param serializer XmlSerializer * @param tag String * @param containerElement ContainerElement * @param withAttributes boolean */ private static void addContainerElement(XmlSerializer serializer, String tag, ContainerElement<?> containerElement, boolean withAttributes) throws IOException { serializer.startTag(null, tag); addStandard(serializer, containerElement.getElement()); if (withAttributes) { if (containerElement.getFrameSize() != null) { serializer.attribute(null, FRAME_SIZE, String.valueOf(containerElement.getFrameSize())); } serializer.attribute(null, DELTA, String.valueOf(containerElement.getDelta())); if(containerElement.getEventTrigger() != null) { serializer.attribute(null, EVENT_TRIGGER, String.valueOf(containerElement.getEventTrigger().hashCode())); } } addOptions(serializer, containerElement.getElement()); Provider[] providers = containerElement.getStreamConnections(); if(providers.length > 0) { serializer.startTag(null, CHANNEL_LIST); for (Provider element : providers) { serializer.startTag(null, CHANNEL_ID); serializer.attribute(null, ID, String.valueOf(element.hashCode())); serializer.endTag(null, CHANNEL_ID); } serializer.endTag(null, CHANNEL_LIST); } Component[] eventInputs = containerElement.getEventConnections(); if(eventInputs.length > 0) { serializer.startTag(null, EVENT_CHANNEL_LIST); for (Component element : eventInputs) { serializer.startTag(null, EVENT_CHANNEL_ID); serializer.attribute(null, ID, String.valueOf(element.hashCode())); serializer.endTag(null, EVENT_CHANNEL_ID); } serializer.endTag(null, EVENT_CHANNEL_LIST); } if (containerElement.getElement() instanceof FeedbackCollection) { addFeedbackCollectionTag(serializer, containerElement); } IModelHandler[] modelHandlers = containerElement.getModelConnections(); if(modelHandlers.length > 0) { serializer.startTag(null, MODEL_HANDLER_LIST); for(IModelHandler element : modelHandlers) { serializer.startTag(null, MODEL_HANDLER_ID); serializer.attribute(null, ID, String.valueOf(element.hashCode())); serializer.endTag(null, MODEL_HANDLER_ID); } serializer.endTag(null, MODEL_HANDLER_LIST); } serializer.endTag(null, tag); } private static void addFeedbackCollectionTag(XmlSerializer serializer, ContainerElement<?> containerElement) throws IOException { serializer.startTag(null, FEEDBACK_LEVEL_LIST); FeedbackCollection feedbackCollection = (FeedbackCollection) containerElement.getElement(); List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackLevelList = feedbackCollection.getFeedbackList(); for (int i = 0; i < feedbackLevelList.size(); i++) { serializer.startTag(null, FEEDBACK_LEVEL); serializer.attribute(null, LEVEL, String.valueOf(i)); for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> entry : feedbackLevelList.get(i).entrySet()) { serializer.startTag(null, FEEDBACK); serializer.attribute(null, FEEDBACK_BEHAVIOUR, entry.getValue().toString()); serializer.attribute(null, ID, String.valueOf(entry.getKey().hashCode())); serializer.endTag(null, FEEDBACK); } serializer.endTag(null, FEEDBACK_LEVEL); } serializer.endTag(null, FEEDBACK_LEVEL_LIST); } /** * @param serializer XmlSerializer * @param anno Annotation */ private static void addAnnotation(XmlSerializer serializer, Annotation anno) throws IOException { serializer.startTag(null, ANNOTATION); addStandard(serializer, anno); serializer.attribute(null, FILE_NAME, anno.getFileName()); serializer.attribute(null, FILE_PATH, anno.getFilePath()); SparseArray<String> anno_classes = anno.getClasses(); for (int i = 0; i < anno_classes.size(); i++) { serializer.startTag(null, ANNOTATION_CLASS); serializer.attribute(null, ID, String.valueOf(anno_classes.keyAt(i))); serializer.attribute(null, NAME, anno_classes.valueAt(i)); serializer.endTag(null, ANNOTATION_CLASS); } serializer.endTag(null, ANNOTATION); } private static String convertOldVersion(File file, float from_version) throws IOException { int bufferSize = 10240; char[] buffer = new char[bufferSize]; FileReader reader = new FileReader(file); int len = reader.read(buffer); buffer[len] = '\0'; String text = new String(buffer, 0, len); if(from_version <= 0.2) { text = text.replace("Provider", "Channel"); text = text.replace("SimpleFile", "File"); text = text.replace("Classifier", "ClassifierT"); text = text.replace("option name=\"timeoutThread\"", "option name=\"waitThreadKill\""); } if(from_version <= 3) { text = text.replaceAll("eventTrigger=\"(true|false)\"", ""); } if(from_version <= 5) { text = text.replaceAll("praat.Intensity", "audio.Intensity"); } if(from_version <= 7) { text = text.replaceAll("option name=\"thresin\"", "option name=\"threshold_in\""); text = text.replaceAll("option name=\"thresout\"", "option name=\"threshold_out\""); } text = text.replaceFirst(ROOT + " version=\".+\"", ROOT + " version=\"" + VERSION_NUMBER + "\""); java.io.FileWriter writer = new java.io.FileWriter(file); writer.write(text); writer.flush(); return text; } /** * Used to add connections. */ private static class LinkContainer { int hash; LinkedHashMap<Integer, ConnectionType> typedHashes = new LinkedHashMap<>(); } /** * Used to add inner feedback components for FeedbackCollection. */ private static class LinkFeedbackCollection { int hash; List<Map<Integer, FeedbackCollection.LevelBehaviour>> typedHashes = new ArrayList<>(); } }
25,153
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SSJDescriptor.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/SSJDescriptor.java
/* * SSJDescriptor.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import dalvik.system.DexFile; import dalvik.system.PathClassLoader; import hcm.ssj.core.Log; import hcm.ssj.core.SSJApplication; /** * Builds pipelines.<br> * Created by Frank Gaibler on 09.03.2016. */ public class SSJDescriptor { private static SSJDescriptor instance = null; // public ArrayList<Class> sensors = new ArrayList<>(); public ArrayList<Class> sensorChannels = new ArrayList<>(); public ArrayList<Class> transformers = new ArrayList<>(); public ArrayList<Class> consumers = new ArrayList<>(); public ArrayList<Class> eventHandlers = new ArrayList<>(); public ArrayList<Class> models = new ArrayList<>(); private HashSet<String> hsClassNames = new HashSet<>(); /** * */ private SSJDescriptor() { scan(); } /** * @return Builder */ public static synchronized SSJDescriptor getInstance() { if (instance == null) { instance = new SSJDescriptor(); } return instance; } private static SharedPreferences getMultiDexPreferences(Context context) { return context.getSharedPreferences("multidex.version", Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } /** * Parse classes.dex to find all implemented SSJ components.<br> * Based on code from stackoverflow (<a href="http://stackoverflow.com/a/31087947">one</a> * and <a href="http://stackoverflow.com/a/36491692">two</a>). */ private void scan() { try { ApplicationInfo applicationInfo = SSJApplication.getAppContext().getPackageManager().getApplicationInfo(SSJApplication.getAppContext().getPackageName(), 0); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { scanDex(new DexFile(applicationInfo.sourceDir)); } else { //get source directory String dir = applicationInfo.sourceDir.substring(0, applicationInfo.sourceDir.lastIndexOf(File.separator)); //iterate through all .apk and .dex in the source directory File[] files = new File(dir).listFiles(); for (File slice : files) { if (!slice.isFile()) { continue; } Log.i("Scanning slice: " + slice.getAbsolutePath()); // Exclude splitted apk since classes are only in base_config if (!slice.getName().startsWith("split_config")) { try { String extension = slice.getName().substring(slice.getName().lastIndexOf(".")); if (extension.equalsIgnoreCase(".apk") || extension.equalsIgnoreCase(".dex")) { scanDex(new DexFile(slice)); } } catch (Exception e) { Log.e("Failed to scan file: " + slice.getAbsolutePath(), e); } } } } } catch (IOException | PackageManager.NameNotFoundException ex) { Log.e("Error while scanning dex files", ex); } //add classes PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader(); for (String className : hsClassNames) { try { Class<?> aClass = classLoader.loadClass(className); //only add valid classes if (!Modifier.isAbstract(aClass.getModifiers()) && !Modifier.isInterface(aClass.getModifiers()) && !Modifier.isPrivate(aClass.getModifiers())) { Class<?> parent = aClass.getSuperclass(); while (parent != null) { if (parent.getSimpleName().compareToIgnoreCase("Sensor") == 0) { sensors.add(aClass); } else if (parent.getSimpleName().compareToIgnoreCase("SensorChannel") == 0) { sensorChannels.add(aClass); } else if (parent.getSimpleName().compareToIgnoreCase("Transformer") == 0) { transformers.add(aClass); } else if (parent.getSimpleName().compareToIgnoreCase("Consumer") == 0) { consumers.add(aClass); } else if (parent.getSimpleName().compareToIgnoreCase("EventHandler") == 0) { eventHandlers.add(aClass); } else if (parent.getSimpleName().compareToIgnoreCase("Model") == 0) { models.add(aClass); } parent = parent.getSuperclass(); } } } catch (ClassNotFoundException cnfe) { Log.e("Class not found", cnfe); } } } /** * @param dexFile DexFile */ private void scanDex(DexFile dexFile) { Enumeration<String> classNames = dexFile.entries(); while (classNames.hasMoreElements()) { String className = classNames.nextElement(); if (className.startsWith("hcm.ssj.") && !className.contains("$")) { hsClassNames.add(className); } } } /** * @param clazz Class * @return Object */ public static Object instantiate(Class clazz) { try { return clazz.newInstance(); } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException(ex); } } }
6,540
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FeedbackCollectionContainerElement.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/container/FeedbackCollectionContainerElement.java
/* * FeedbackCollectionContainerElement.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core.container; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; /** * Created by Antonio Grieco on 18.10.2017. */ public class FeedbackCollectionContainerElement extends ContainerElement { private List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackList; public FeedbackCollectionContainerElement(FeedbackCollection element) { super(element); feedbackList = element.getFeedbackList(); } public List<Map<Feedback, FeedbackCollection.LevelBehaviour>> getFeedbackList() { return feedbackList; } public void addFeedback(Feedback feedback, int level, FeedbackCollection.LevelBehaviour levelBehaviour) { while (feedbackList.size() <= level) { feedbackList.add(new LinkedHashMap<Feedback, FeedbackCollection.LevelBehaviour>()); } feedbackList.get(level).put(feedback, levelBehaviour); } public void removeAllFeedbacks() { feedbackList = new ArrayList<>(); } }
2,438
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ContainerElement.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/core/container/ContainerElement.java
/* * ContainerElement.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.core.container; import java.util.LinkedHashSet; import hcm.ssj.core.Component; import hcm.ssj.core.Provider; import hcm.ssj.ml.IModelHandler; /** * Container element for pipeline builder.<br> * Created by Frank Gaibler on 10.03.2016. */ public class ContainerElement<T> { private T element; private Double frameSize = null; private double delta = 0; private Object eventTrigger = null; private boolean added; private LinkedHashSet<ContainerElement<Provider>> hsStreamConnections = new LinkedHashSet<>(); private LinkedHashSet<ContainerElement<Component>> hsEventConnections = new LinkedHashSet<>(); private LinkedHashSet<ContainerElement<IModelHandler>> hsModelConnections = new LinkedHashSet<>(); /** * @param element T */ public ContainerElement(T element) { this.element = element; } /** * @return T */ public T getElement() { return element; } /** * @return Double */ public Double getFrameSize() { return frameSize; } /** * @param frameSize double */ public void setFrameSize(Double frameSize) { this.frameSize = frameSize; } /** * @return double */ public double getDelta() { return delta; } /** * @param delta double */ public void setDelta(double delta) { this.delta = delta; } public void setEventTrigger(Object eventTrigger) { this.eventTrigger = eventTrigger; } public Object getEventTrigger() { return eventTrigger; } public void setAdded(boolean value) { added = value; } public boolean hasBeenAdded() { return added; } public void reset() { added = false; } /** * @return LinkedHashMap */ public LinkedHashSet<ContainerElement<Provider>> getStreamConnectionContainers() { return hsStreamConnections; } public Provider[] getStreamConnections() { Provider[] providers = new Provider[hsStreamConnections.size()]; int i = 0; for (ContainerElement<Provider> element : hsStreamConnections) { providers[i++] = element.getElement(); } return providers; } /** * @return boolean */ public boolean allStreamConnectionsAdded() { boolean allAdded = true; for (ContainerElement<?> element : hsStreamConnections) { allAdded &= element.hasBeenAdded(); } return allAdded; } /** * @param element ContainerElement * @return boolean */ public boolean addStreamConnection(ContainerElement<Provider> element) { return !hsStreamConnections.contains(element) && hsStreamConnections.add(element); } /** * @param element ContainerElement * @return boolean */ public boolean removeStreamConnection(ContainerElement<Provider> element) { return hsStreamConnections.remove(element); } /** * @return LinkedHashMap */ public LinkedHashSet<ContainerElement<Component>> getEventConnectionContainers() { return hsEventConnections; } public Component[] getEventConnections() { Component[] components = new Component[hsEventConnections.size()]; int i = 0; for (ContainerElement<Component> element : hsEventConnections) { components[i++] = element.getElement(); } return components; } /** * @param provider Provider * @return boolean */ public boolean addEventConnection(ContainerElement<Component> provider) { return !hsEventConnections.contains(provider) && hsEventConnections.add(provider); } /** * @param provider Provider * @return boolean */ public boolean removeEventConnection(ContainerElement<Component> provider) { return hsEventConnections.remove(provider); } /** * @return LinkedHashMap */ public LinkedHashSet<ContainerElement<IModelHandler>> getModelConnectionContainers() { return hsModelConnections; } public IModelHandler[] getModelConnections() { IModelHandler[] handlers = new IModelHandler[hsModelConnections.size()]; int i = 0; for (ContainerElement<IModelHandler> element : hsModelConnections) { handlers[i++] = element.getElement(); } return handlers; } /** * @param handler IModelHandler * @return boolean */ public boolean addModelConnection(ContainerElement<IModelHandler> handler) { return !hsModelConnections.contains(handler) && hsModelConnections.add(handler); } /** * @param handler IModelHandler * @return boolean */ public boolean removeModelConnection(ContainerElement<IModelHandler> handler) { return hsModelConnections.remove(handler); } }
5,993
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ArrayAdapterWithNull.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/ArrayAdapterWithNull.java
/* * ArrayAdapterWithNull.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by Ionut Damian on 02.11.2017. */ public class ArrayAdapterWithNull extends ArrayAdapter<Object> { private Context context; private String defaultLabel; private int resource; public ArrayAdapterWithNull(Context context, int resource, ArrayList<Object> objects, String defaultLabel) { super(context, resource, objects); this.context = context; this.defaultLabel = defaultLabel; this.resource = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView label; if (convertView == null) { label = (TextView)LayoutInflater.from(context).inflate(resource, parent, false); } else { label = (TextView)convertView; } String text = (getItem(position) == null) ? defaultLabel : getItem(position).getClass().getSimpleName(); label.setText(text); return label; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { TextView label; if (convertView == null) { label = (TextView)LayoutInflater.from(context).inflate(resource, parent, false); } else { label = (TextView)convertView; } String text = (getItem(position) == null) ? defaultLabel : getItem(position).getClass().getSimpleName(); label.setText(text); return label; } }
2,891
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ConnectionType.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/ConnectionType.java
/* * ConnectionType.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.graphics.DashPathEffect; import android.graphics.PathEffect; import hcm.ssj.creator.R; /** * Created by Antonio Grieco on 29.06.2017. */ public enum ConnectionType{ STREAMCONNECTION(new PathEffect(), R.color.colorConnectionStream), EVENTCONNECTION(new DashPathEffect(new float[]{45f, 30f}, 0), R.color.colorConnectionEvent), EVENTTRIGGERCONNECTION(null, R.color.colorConnectionEvent), MODELCONNECTION(new DashPathEffect(new float[]{10f, 10f}, 0), R.color.colorConnectionModel); private final PathEffect pathEffect; private final int color; ConnectionType(PathEffect pathEffect, int color) { this.pathEffect = pathEffect; this.color = color; } public PathEffect getPathEffect() { return pathEffect; } public int getColor() { return color; } }
2,174
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ProviderTable.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/ProviderTable.java
/* * ProviderTable.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.app.Activity; import android.util.TypedValue; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.TableRow; import android.widget.TextView; import hcm.ssj.core.Component; import hcm.ssj.core.Provider; import hcm.ssj.creator.R; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.ml.IModelHandler; /** * Create a table row which includes viable providers * Created by Frank Gaibler on 19.05.2016. */ public class ProviderTable { /** * @param activity Activity * @param mainObject Object * @param dividerTop boolean * @return TableRow */ public static TableRow createStreamTable(Activity activity, final Object mainObject, boolean dividerTop, int heading) { TableRow tableRow = new TableRow(activity); tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setOrientation(LinearLayout.VERTICAL); if (dividerTop) { //add divider linearLayout.addView(Util.addDivider(activity)); } TextView textViewName = new TextView(activity); textViewName.setText(heading); textViewName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); textViewName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); linearLayout.addView(textViewName); //get possible providers final Object[] objects = PipelineBuilder.getInstance().getPossibleStreamConnections(mainObject); // if (objects.length > 0) { for (int i = 0; i < objects.length; i++) { CheckBox checkBox = new CheckBox(activity); checkBox.setText(objects[i].getClass().getSimpleName()); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19); Object[] providers = PipelineBuilder.getInstance().getStreamConnections(mainObject); if (providers != null) { for (Object provider : providers) { if (objects[i].equals(provider)) { checkBox.setChecked(true); break; } } } final int count = i; checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { final Object o = objects[count]; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { PipelineBuilder.getInstance().addStreamConnection(mainObject, (Provider) o); } else { PipelineBuilder.getInstance().removeStreamConnection(mainObject, (Provider) o); } } }); linearLayout.addView(checkBox); } } else { return null; } tableRow.addView(linearLayout); return tableRow; } /** * @param activity Activity * @param mainObject Object * @param dividerTop boolean * @return TableRow */ public static TableRow createEventTable(Activity activity, final Object mainObject, boolean dividerTop) { TableRow tableRow = new TableRow(activity); tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setOrientation(LinearLayout.VERTICAL); if (dividerTop) { //add divider linearLayout.addView(Util.addDivider(activity)); } TextView textViewName = new TextView(activity); textViewName.setText(R.string.str_event_input); textViewName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); textViewName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); linearLayout.addView(textViewName); //get possible providers final Object[] objects = PipelineBuilder.getInstance().getPossibleEventConnections(mainObject); // if (objects.length > 0) { for (int i = 0; i < objects.length; i++) { if(PipelineBuilder.getInstance().isManagedFeedback(objects[i])) continue; CheckBox checkBox = new CheckBox(activity); checkBox.setText(objects[i].getClass().getSimpleName()); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19); Object[] providers = PipelineBuilder.getInstance().getEventConnections(mainObject); if (providers != null) { for (Object provider : providers) { if (objects[i].equals(provider)) { checkBox.setChecked(true); break; } } } final int count = i; checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { final Object o = objects[count]; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { PipelineBuilder.getInstance().addEventConnection(mainObject, (Component) o); } else { PipelineBuilder.getInstance().removeEventConnection(mainObject, (Component) o); } } }); linearLayout.addView(checkBox); } } else { return null; } tableRow.addView(linearLayout); return tableRow; } /** * @param activity Activity * @param mainObject Object * @param dividerTop boolean * @return TableRow */ public static TableRow createModelTable(Activity activity, final Object mainObject, boolean dividerTop, int heading) { TableRow tableRow = new TableRow(activity); tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setOrientation(LinearLayout.VERTICAL); if (dividerTop) { //add divider linearLayout.addView(Util.addDivider(activity)); } TextView textViewName = new TextView(activity); textViewName.setText(heading); textViewName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); textViewName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); linearLayout.addView(textViewName); //get possible providers final Object[] objects = (mainObject instanceof IModelHandler) ? PipelineBuilder.getInstance().getAll(PipelineBuilder.Type.Model) : PipelineBuilder.getInstance().getModelHandlers(); if (objects.length > 0) { for (int i = 0; i < objects.length; i++) { CheckBox checkBox = new CheckBox(activity); checkBox.setText(objects[i].getClass().getSimpleName()); checkBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19); Object[] connections = PipelineBuilder.getInstance().getModelConnections(mainObject); if (connections != null) { for (Object conn : connections) { if (objects[i].equals(conn)) { checkBox.setChecked(true); break; } } } final int count = i; checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { final Object o = objects[count]; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { PipelineBuilder.getInstance().addModelConnection((Component) mainObject, (Component) o); } else { PipelineBuilder.getInstance().removeModelConnection((Component) mainObject, (Component) o); } } }); linearLayout.addView(checkBox); } } else { return null; } tableRow.addView(linearLayout); return tableRow; } }
10,293
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
StrategyLoader.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/StrategyLoader.java
/* * StrategyLoader.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import androidx.annotation.Nullable; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import hcm.ssj.core.Component; import hcm.ssj.core.SSJFatalException; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.event.ThresholdClassEventSender; import hcm.ssj.feedback.AndroidTactileFeedback; import hcm.ssj.feedback.AuditoryFeedback; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.feedback.MSBandTactileFeedback; import hcm.ssj.feedback.MyoTactileFeedback; import hcm.ssj.feedback.VisualFeedback; /** * Created by Antonio Grieco on 20.10.2017. */ public class StrategyLoader { private File strategyFile; private List<ParsedStrategyFeedback> parsedStrategyFeedbackList = new ArrayList<>(); private List<Component> addedComponents = new ArrayList<>(); public StrategyLoader(File strategyFile) { this.strategyFile = strategyFile; } public boolean load() { InputStream inputStream = null; try { inputStream = new FileInputStream(strategyFile); XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(inputStream, null); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "ssj"); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "strategy"); loadStrategyComponents(parser); inputStream.close(); addComponents(); return true; } catch (IOException | XmlPullParserException | SSJFatalException e) { removeAddedComponents(); return false; } } private void removeAddedComponents() { for (Component addedComponent : addedComponents) { PipelineBuilder.getInstance().remove(addedComponent); } } private void loadStrategyComponents(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "strategy"); while (parser.next() != XmlPullParser.END_DOCUMENT) { switch (parser.getEventType()) { case XmlPullParser.START_TAG: if (parser.getName().equalsIgnoreCase("feedback")) { parsedStrategyFeedbackList.add(getNextParsedStrategyFeedback(parser)); } break; } } } private ParsedStrategyFeedback getNextParsedStrategyFeedback(XmlPullParser parser) throws IOException, XmlPullParserException { ParsedStrategyFeedback parsedStrategyFeedback = new ParsedStrategyFeedback(); goToNextTagWithName(parser, "feedback"); parsedStrategyFeedback.feedbackAttributes = new FeedbackAttributes(parser); goToNextTagWithName(parser, "condition"); parsedStrategyFeedback.conditionAttributes = new ConditionAttributes(parser); goToNextTagWithName(parser, "action"); parsedStrategyFeedback.actionAttributes = new ActionAttributes(parser); return parsedStrategyFeedback; } private void goToNextTagWithName(XmlPullParser parser, String tagName) throws IOException, XmlPullParserException { while (parser.getName() == null || !parser.getName().equalsIgnoreCase(tagName)) { parser.next(); } } private void addComponents() throws SSJFatalException { PipelineBuilder pipelineBuilder = PipelineBuilder.getInstance(); FeedbackCollection feedbackCollection = new FeedbackCollection(); pipelineBuilder.add(feedbackCollection); addedComponents.add(feedbackCollection); Map<String, List<Float>> thresholdEventMap = getThresholdEventMap(parsedStrategyFeedbackList); List<ThresholdClassEventSender> thresholdClassEventSenders = getThresholdClassEventSenders(thresholdEventMap); for (ThresholdClassEventSender thresholdClassEventSender : thresholdClassEventSenders) { pipelineBuilder.add(thresholdClassEventSender); pipelineBuilder.addEventConnection(feedbackCollection, thresholdClassEventSender); addedComponents.add(thresholdClassEventSender); } addFeedbacks(feedbackCollection, thresholdEventMap); } private void addFeedbacks(FeedbackCollection feedbackCollection, Map<String, List<Float>> thresholdEventMap) throws SSJFatalException { for (ParsedStrategyFeedback parsedStrategyFeedback : parsedStrategyFeedbackList) { Feedback feedback = getFeedbackForParsedFeedback(parsedStrategyFeedback); if (feedback == null) { throw new SSJFatalException(); } PipelineBuilder.getInstance().add(feedback); PipelineBuilder.getInstance().addFeedbackToCollectionContainer( feedbackCollection, feedback, getLevel(parsedStrategyFeedback), getLevelBehaviour(parsedStrategyFeedback) ); addedComponents.add(feedback); // Set lock if (parsedStrategyFeedback.actionAttributes.lockSelf != null) { feedback.getOptions().lock.set(Integer.parseInt(parsedStrategyFeedback.actionAttributes.lockSelf)); } String strategyEventName = parsedStrategyFeedback.conditionAttributes.event; String[] eventNames = getEventNames(strategyEventName, thresholdEventMap.get(strategyEventName), parsedStrategyFeedback.conditionAttributes.from, parsedStrategyFeedback.conditionAttributes.to); feedback.getOptions().eventNames.set(eventNames); } } private List<ThresholdClassEventSender> getThresholdClassEventSenders(Map<String, List<Float>> thresholdEventMap) { List<ThresholdClassEventSender> thresholdClassEventSenders = new ArrayList<>(); for (Map.Entry<String, List<Float>> thresholdEntry : thresholdEventMap.entrySet()) { ThresholdClassEventSender thresholdClassEventSender = new ThresholdClassEventSender(); float[] thresholdArray = new float[thresholdEntry.getValue().size()]; int thresholdArrayCounter = 0; for (Float threshold : thresholdEntry.getValue()) { thresholdArray[thresholdArrayCounter++] = (threshold != null ? threshold : Float.NaN); } thresholdClassEventSender.options.thresholds.set(thresholdArray); List<String> thresholdNames = new ArrayList<>(); for (int thresholdNameCounter = 0; thresholdNameCounter < thresholdArray.length; thresholdNameCounter++) { thresholdNames.add(thresholdEntry.getKey() + thresholdNameCounter); } thresholdClassEventSender.options.classes.set(thresholdNames.toArray(new String[thresholdNames.size()])); thresholdClassEventSenders.add(thresholdClassEventSender); } return thresholdClassEventSenders; } private Map<String, List<Float>> getThresholdEventMap(List<ParsedStrategyFeedback> parsedStrategyFeedbackList) { Map<String, List<Float>> thresholdEventMap = new HashMap<>(); // Iterate first time to build up Thresholds for (ParsedStrategyFeedback parsedStrategyFeedback : parsedStrategyFeedbackList) { String event = parsedStrategyFeedback.conditionAttributes.event; if (!thresholdEventMap.containsKey(event)) { thresholdEventMap.put(event, new ArrayList<Float>()); } if (parsedStrategyFeedback.conditionAttributes.from != null) { float from = Float.parseFloat(parsedStrategyFeedback.conditionAttributes.from); if (!thresholdEventMap.get(event).contains(from)) { thresholdEventMap.get(event).add(from); } } if (parsedStrategyFeedback.conditionAttributes.to != null) { float to = Float.parseFloat(parsedStrategyFeedback.conditionAttributes.to); if (!thresholdEventMap.get(event).contains(to)) { thresholdEventMap.get(event).add(to); } } } for (List<Float> thresholdList : thresholdEventMap.values()) { Collections.sort(thresholdList); } return thresholdEventMap; } private String[] getEventNames(String strategyEventName, List<Float> thresholds, String from, String to) { if (from == null || to == null) { return null; } Float fromFloat = Float.parseFloat(from); Float toFloat = Float.parseFloat(to); List<String> thresholdNames = new ArrayList<>(); for (int i = thresholds.indexOf(fromFloat); i < thresholds.indexOf(toFloat); i++) { thresholdNames.add(strategyEventName + i); } return thresholdNames.toArray(new String[thresholdNames.size()]); } private FeedbackCollection.LevelBehaviour getLevelBehaviour(ParsedStrategyFeedback parsedStrategyFeedback) { FeedbackCollection.LevelBehaviour levelBehaviour = FeedbackCollection.LevelBehaviour.Neutral; if (parsedStrategyFeedback.feedbackAttributes.valence != null) { if (parsedStrategyFeedback.feedbackAttributes.valence.equalsIgnoreCase("desirable")) { levelBehaviour = FeedbackCollection.LevelBehaviour.Regress; } else if (parsedStrategyFeedback.feedbackAttributes.valence.equalsIgnoreCase("undesirable")) { levelBehaviour = FeedbackCollection.LevelBehaviour.Progress; } } return levelBehaviour; } private int getLevel(ParsedStrategyFeedback parsedStrategyFeedback) { if (parsedStrategyFeedback.feedbackAttributes.level != null) { return Integer.parseInt(parsedStrategyFeedback.feedbackAttributes.level); } else { return 0; } } @Nullable private Feedback getFeedbackForParsedFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { if (parsedStrategyFeedback.feedbackAttributes.type.equalsIgnoreCase("audio")) { return getAuditoryFeedback(parsedStrategyFeedback); } else if (parsedStrategyFeedback.feedbackAttributes.type.equalsIgnoreCase("visual")) { return getVisualFeedback(parsedStrategyFeedback); } else if (parsedStrategyFeedback.feedbackAttributes.type.equalsIgnoreCase("tactile")) { return getTactileFeedback(parsedStrategyFeedback); } return null; } @Nullable private Feedback getTactileFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { if (parsedStrategyFeedback.feedbackAttributes.device == null || parsedStrategyFeedback.feedbackAttributes.device.equalsIgnoreCase("Android")) { return getAndroidTactileFeedback(parsedStrategyFeedback); } else if (parsedStrategyFeedback.feedbackAttributes.device.equalsIgnoreCase("Myo")) { return getMyoTactileFeedback(parsedStrategyFeedback); } else if (parsedStrategyFeedback.feedbackAttributes.device.equalsIgnoreCase("MsBand")) { return getMsBandTactileFeedback(parsedStrategyFeedback); } return null; } private Feedback getMsBandTactileFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { MSBandTactileFeedback msBandTactileFeedback = new MSBandTactileFeedback(); // Duration msBandTactileFeedback.options.duration.setValue(parsedStrategyFeedback.actionAttributes.duration); // VibrationType msBandTactileFeedback.options.vibrationType.setValue(parsedStrategyFeedback.actionAttributes.type); // DeviceId msBandTactileFeedback.options.deviceId.setValue(parsedStrategyFeedback.feedbackAttributes.deviceId); return msBandTactileFeedback; } private Feedback getAndroidTactileFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { AndroidTactileFeedback androidTactileFeedback = new AndroidTactileFeedback(); //Vibration Pattern androidTactileFeedback.options.vibrationPattern.setValue(parsedStrategyFeedback.actionAttributes.duration); return androidTactileFeedback; } private Feedback getMyoTactileFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { MyoTactileFeedback myoTactileFeedback = new MyoTactileFeedback(); //DeviceId myoTactileFeedback.options.deviceId.set(parsedStrategyFeedback.feedbackAttributes.deviceId); //Intensity myoTactileFeedback.options.intensity.setValue(parsedStrategyFeedback.actionAttributes.intensity); //Duration myoTactileFeedback.options.duration.setValue(parsedStrategyFeedback.actionAttributes.duration); return myoTactileFeedback; } private Feedback getVisualFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { VisualFeedback visualFeedback = new VisualFeedback(); //Options if (parsedStrategyFeedback.actionAttributes.brightness != null) { visualFeedback.options.brightness.set(Float.parseFloat(parsedStrategyFeedback.actionAttributes.brightness)); } if (parsedStrategyFeedback.actionAttributes.duration != null) { visualFeedback.options.duration.set(Integer.parseInt(parsedStrategyFeedback.actionAttributes.duration)); } if (parsedStrategyFeedback.feedbackAttributes.fade != null) { visualFeedback.options.fade.set(Integer.parseInt(parsedStrategyFeedback.feedbackAttributes.fade)); } if (parsedStrategyFeedback.feedbackAttributes.position != null) { visualFeedback.options.position.set(Integer.parseInt(parsedStrategyFeedback.feedbackAttributes.position)); } // Icons if (parsedStrategyFeedback.actionAttributes.res != null) { String[] iconString = parsedStrategyFeedback.actionAttributes.res.split(","); if (iconString.length > 0 && !iconString[0].isEmpty()) { visualFeedback.options.feedbackIcon.setValue(iconString[0].trim()); } if (iconString.length == 2 && !iconString[1].isEmpty()) { visualFeedback.options.qualityIcon.setValue(iconString[0].trim()); } } return visualFeedback; } private Feedback getAuditoryFeedback(ParsedStrategyFeedback parsedStrategyFeedback) { AuditoryFeedback auditoryFeedback = new AuditoryFeedback(); //Options auditoryFeedback.options.audioFile.setValue(parsedStrategyFeedback.actionAttributes.res.trim()); if (parsedStrategyFeedback.actionAttributes.intensity != null) { auditoryFeedback.options.intensity.set(Float.parseFloat(parsedStrategyFeedback.actionAttributes.intensity)); } if (parsedStrategyFeedback.actionAttributes.lockSelf != null) { auditoryFeedback.options.lock.set(Integer.parseInt(parsedStrategyFeedback.actionAttributes.lockSelf)); } return auditoryFeedback; } private class ParsedStrategyFeedback { FeedbackAttributes feedbackAttributes; ActionAttributes actionAttributes; ConditionAttributes conditionAttributes; } private class ActionAttributes { final String res; final String lock; final String lockSelf; final String intensity; final String duration; final String brightness; final String type; public ActionAttributes(XmlPullParser xmlPullParser) throws IOException, XmlPullParserException { xmlPullParser.require(XmlPullParser.START_TAG, null, "action"); res = xmlPullParser.getAttributeValue(null, "res"); lock = xmlPullParser.getAttributeValue(null, "lock"); lockSelf = xmlPullParser.getAttributeValue(null, "lockSelf"); intensity = xmlPullParser.getAttributeValue(null, "intensity"); duration = xmlPullParser.getAttributeValue(null, "duration"); brightness = xmlPullParser.getAttributeValue(null, "brightness"); type = xmlPullParser.getAttributeValue(null, "type"); } } private class ConditionAttributes { String event; String sender; String type; String history; String sum; String from; String to; public ConditionAttributes(XmlPullParser xmlPullParser) throws IOException, XmlPullParserException { xmlPullParser.require(XmlPullParser.START_TAG, null, "condition"); event = xmlPullParser.getAttributeValue(null, "event"); sender = xmlPullParser.getAttributeValue(null, "sender"); type = xmlPullParser.getAttributeValue(null, "type"); history = xmlPullParser.getAttributeValue(null, "history"); sum = xmlPullParser.getAttributeValue(null, "sum"); from = xmlPullParser.getAttributeValue(null, "from"); to = xmlPullParser.getAttributeValue(null, "to"); } } private class FeedbackAttributes { String type; String valence; String level; String layout; String position; String fade; String def_brightness; String device; String deviceId; public FeedbackAttributes(XmlPullParser xmlPullParser) throws IOException, XmlPullParserException { xmlPullParser.require(XmlPullParser.START_TAG, null, "feedback"); type = xmlPullParser.getAttributeValue(null, "type"); valence = xmlPullParser.getAttributeValue(null, "valence"); level = xmlPullParser.getAttributeValue(null, "level"); layout = xmlPullParser.getAttributeValue(null, "layout"); position = xmlPullParser.getAttributeValue(null, "position"); fade = xmlPullParser.getAttributeValue(null, "fade"); def_brightness = xmlPullParser.getAttributeValue(null, "def_brightness"); device = xmlPullParser.getAttributeValue(null, "device"); deviceId = xmlPullParser.getAttributeValue(null, "deviceId"); } } }
17,851
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
DemoHandler.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/DemoHandler.java
/* * DemoHandler.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.content.Context; import android.content.res.AssetManager; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import hcm.ssj.core.Log; import hcm.ssj.file.FileUtils; /** * Handle demo files.<br> * Created by Frank Gaibler on 22.09.2016. */ public abstract class DemoHandler { /** * */ private DemoHandler() { } /** * @param context Context */ public static void copyFiles(Context context) { //in v0.7, the location of the pipelines changed copyFiles(null, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR + File.separator + Util.PIPELINES, new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.endsWith(".xml") || name.endsWith(".layout")) return true; else return false; } }); AssetManager assetManager = context.getAssets(); copyFiles(assetManager, Util.DEMO, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR, null); copyFiles(assetManager, Util.DEMO + File.separator + Util.RES, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR + File.separator + Util.RES, null); copyFiles(assetManager, Util.DEMO + File.separator + Util.PIPELINES, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR + File.separator + Util.PIPELINES, null); copyFiles(assetManager, Util.DEMO + File.separator + Util.STRATEGIES, Environment.getExternalStorageDirectory() + File.separator + Util.SSJ + File.separator + Util.CREATOR + File.separator + Util.STRATEGIES, null); } public static void copyFiles(AssetManager assetManager, String src_dir, String dst_dir, FilenameFilter filter) { String[] filenames; try { if(assetManager != null) { filenames = assetManager.list(src_dir); } else { filenames = new File(src_dir).list(filter); } } catch (IOException e) { Log.e("error accessing folder: " + src_dir, e); return; } if(filenames == null || filenames.length == 0) return; for (String file : filenames) { try { InputStream in = null; if(assetManager != null) { in = assetManager.open(src_dir + File.separator + file); } else { in = new FileInputStream(new File(src_dir, file)); } File dir = new File(dst_dir); if(!dir.exists()) dir.mkdirs(); OutputStream out = new FileOutputStream(new File(dir, file)); FileUtils.copyFile(in, out); in.close(); out.flush(); out.close(); } catch (Exception e) { Log.i("skipping copying file: " + file); } } } }
5,288
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PlaybackThreadList.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/PlaybackThreadList.java
/* * PlaybackThreadList.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import java.util.ArrayList; import hcm.ssj.audio.PlaybackListener; import hcm.ssj.audio.PlaybackThread; /** * Convenience class for playback thread management. Only one thread is allowed to have a * {@link hcm.ssj.audio.PlaybackListener}, as playback marker's position is updated by a single * thread (the one with the longest audio duration, meaning that the marker is reset only when * the longest audio file is finished playing). */ public class PlaybackThreadList { private ArrayList<PlaybackThread> playbackThreads = new ArrayList<>(); private int leadThreadIndex = 0; public void add(PlaybackThread thread) { playbackThreads.add(thread); } /** * Starts playing all threads. */ public void play() { for (PlaybackThread thread : playbackThreads) { thread.play(); } } /** * Pauses playback of all threads. */ public void pause() { for (PlaybackThread thread : playbackThreads) { thread.pause(); } } /** * Stops playback of all threads. */ public void reset() { for (PlaybackThread thread : playbackThreads) { thread.reset(); } } /** * Prepares playback threads to be played. */ public void resetFinishedPlaying() { for (PlaybackThread thread : playbackThreads) { thread.resetFinishedPlaying(); } } /** * Skips playback of all threads to the given time. * @param progress Time in milliseconds to skip to. */ public void seekTo(int progress) { resetFinishedPlaying(); for (PlaybackThread thread : playbackThreads) { thread.seekTo(progress); } } /** * Removes playback listener of the leading thread. This method should be called whenever a new * audio file is selected for visualization which has audio length longer than any * previously selected audio files. */ public void removePlaybackListener() { playbackThreads.get(leadThreadIndex).removePlaybackListener(); } /** * Sets {@link hcm.ssj.audio.PlaybackListener} on the newly created thread, and updates the * index of the leading playback thread. This method should be called whenever a new * audio file is selected for visualization which has audio length longer than any previously * selected audio files, meaning this thread is now the leading thread, and thus is responsible * for playback marker progress update. * @param listener Listener for the lead playback thread. */ public void setPlaybackListener(PlaybackListener listener) { leadThreadIndex = playbackThreads.size() - 1; playbackThreads.get(leadThreadIndex).setPlaybackListener(listener); } /** * Return true if at least one thread in the collection is currently running. * @return True if at least one thread is currently running, false otherwise. */ public boolean isPlaying() { for (PlaybackThread thread : playbackThreads) { if (thread.isPlaying()) { return true; } } return false; } }
4,278
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Util.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/Util.java
/* * Util.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.app.Activity; import android.graphics.Color; import android.os.Environment; import android.view.View; import android.widget.LinearLayout; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; /** * Utility class.<br> * Created by Frank Gaibler on 15.09.2016. */ public abstract class Util { public final static String SSJ = "SSJ"; public final static String CREATOR = "Creator"; public final static String SUFFIX = ".xml"; public final static String STRATEGIES = "strategies"; public final static String PIPELINES = "pipelines"; public final static String DEMO = "demo"; public final static String RES = "res"; public enum AppAction { ADD, SAVE, LOAD, CLEAR, DISPLAYED, UNDEFINED } /** * */ private Util() { } /** * @param folder String * @param name String * @return File */ public static File getFile(String folder, String name) { File parent = getDirectory(folder); if (!parent.exists()) { parent.mkdirs(); } return new File(parent, name); } /** * @param file File * @param content String */ public static synchronized void appendFile(File file, String content) { try (PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) { printWriter.print(content); } catch (IOException e) { e.printStackTrace(); Log.e("error in appendFile(): " + file.getName()); } } /** * @param dirName String * @return boolean */ public static synchronized boolean deleteDirectory(String dirName) { File file = getDirectory(dirName); return file.exists() && deleteRecursive(file); } /** * Java can't delete non-empty directories * * @param file File * @return boolean */ private static boolean deleteRecursive(File file) { boolean ret = true; if (file.isDirectory()) { for (File f : file.listFiles()) { ret = ret && deleteRecursive(f); } } return ret && file.delete(); } /** * @param dirName String * @return File */ public static File getDirectory(String dirName) { File file = new File(Environment.getExternalStorageDirectory(), dirName); if (!file.exists()) { file.mkdirs(); } return file; } /** * @param dirName String * @return File[] */ public static File[] getFilesInDirectory(String dirName) { return getDirectory(dirName).listFiles(new FilenameFilter() { @Override public boolean accept(File current, String name) { return new File(current, name).isDirectory(); } }); } /** * @return double */ public static double getAnnotationTime() { return Pipeline.getInstance().getTime(); } /** * @param activity Activity * @return View */ protected static View addDivider(Activity activity) { int dpValue = 3; // margin in dips float d = activity.getResources().getDisplayMetrics().density; int margin = (int) (dpValue * d); // margin in pixels LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, margin, 1f); dpValue = 8; // margin in dips d = activity.getResources().getDisplayMetrics().density; margin = (int) (dpValue * d); // margin in pixels layoutParams.setMargins(0, margin, 0, margin); View view = new View(activity); view.setLayoutParams(layoutParams); view.setBackgroundColor(Color.DKGRAY); return view; } }
5,480
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FileChooser.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/FileChooser.java
/* * FileChooser.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.app.Activity; import com.obsez.android.lib.filechooser.ChooserDialog; import java.io.File; /** * Created by Ionut Damian on 12.12.2017. */ public abstract class FileChooser { private ChooserDialog chooserDialog; public FileChooser(Activity activity, String startPath, boolean dirOnly, String... extensions) { chooserDialog = new ChooserDialog().with(activity); chooserDialog.withStartFile(startPath); chooserDialog.withFilter(dirOnly, false, extensions); chooserDialog.withChosenListener(new ChooserDialog.Result() { @Override public void onChoosePath(String path, File pathFile) { onResult(path, pathFile); } }).build(); } public void show() { chooserDialog.show(); } public abstract void onResult(String path, File pathFile); }
2,173
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
OptionTable.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/util/OptionTable.java
/* * OptionTable.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.util; import android.app.Activity; import androidx.core.content.ContextCompat; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import hcm.ssj.core.Consumer; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.FilePath; import hcm.ssj.core.option.FolderPath; import hcm.ssj.core.option.Option; import hcm.ssj.creator.R; import hcm.ssj.file.FileCons; /** * Create a table row which includes every option * Created by Frank Gaibler on 18.05.2016. */ public class OptionTable { /** * @param activity Activity * @param options Option[] * @param owner Object * @return TableRow */ public static TableRow createTable(Activity activity, Option[] options, Object owner) { TableRow tableRow = new TableRow(activity); tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT)); // LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setOrientation(LinearLayout.VERTICAL); if (owner != null && (owner instanceof Transformer || owner instanceof Consumer)) { //add divider linearLayout.addView(Util.addDivider(activity)); } TextView textViewName = new TextView(activity); textViewName.setText(R.string.str_options); textViewName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); textViewName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); linearLayout.addView(textViewName); // LinearLayout linearLayoutOptions = new LinearLayout(activity); linearLayoutOptions.setBackgroundColor(activity.getResources().getColor(R.color.colorListBorder)); linearLayoutOptions.setOrientation(LinearLayout.VERTICAL); //options for (int i = 0; i < options.length; i++) { if (options[i].isAssignableByString()) { linearLayoutOptions.addView(addOption(activity, options[i], owner)); } } linearLayout.addView(linearLayoutOptions); tableRow.addView(linearLayout); return tableRow; } /** * @param activity Activity * @param option Option * @return LinearLayout */ private static LinearLayout addOption(final Activity activity, final Option option, Object owner) { final Object value = option.get(); // Set up the view LinearLayout linearLayout = new LinearLayout(activity); linearLayout.setBackgroundColor(activity.getResources().getColor(R.color.colorBackground)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f); int dpValue = 4; // margin in dips float d = activity.getResources().getDisplayMetrics().density; int margin = (int) (dpValue * d); // margin in pixels params.setMargins(0, 0, 0, margin); linearLayout.setLayoutParams(params); linearLayout.setOrientation(LinearLayout.VERTICAL); //description of the object LinearLayout linearLayoutDescription = new LinearLayout(activity); linearLayoutDescription.setOrientation(LinearLayout.HORIZONTAL); //name TextView textViewName = new TextView(activity); textViewName.setText(option.getName()); textViewName.setTextColor(activity.getResources().getColor(R.color.colorOptionNameText)); textViewName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); linearLayoutDescription.addView(textViewName); //help final String helpText = option.getHelp(); if (!helpText.isEmpty()) { TextView textViewHelp = new TextView(activity); textViewHelp.setText(" / " + helpText); textViewHelp.setTextColor(activity.getResources().getColor(R.color.colorOptionHelpText)); textViewHelp.setLayoutParams(new LinearLayout.LayoutParams(100, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); textViewHelp.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END); linearLayoutDescription.addView(textViewHelp); } linearLayout.addView(linearLayoutDescription); //edit field View inputView; if (option.getType() == Boolean.class) { //checkbox for boolean values inputView = new CheckBox(activity); ((CheckBox) inputView).setChecked((Boolean) value); ((CheckBox) inputView).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { option.set(isChecked); } }); } else if (option.getType().isEnum()) { //create spinner selection for enums which are not null inputView = new Spinner(activity); //pupulate spinner ArrayList<Object> items = new ArrayList<>(); items.addAll(Arrays.asList((Object[])option.getType().getEnumConstants())); ((Spinner) inputView).setAdapter(new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, items)); //preselect item if(value == null) { ((Spinner) inputView).setSelection(0); } else { for (int i = 0; i < items.size(); i++) { if (items.get(i) != null && items.get(i).equals(value)) { ((Spinner) inputView).setSelection(i); break; } } } ((Spinner) inputView).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { option.set(parent.getItemAtPosition(position)); } @Override public void onNothingSelected(AdapterView parent) { } }); } else { LinearLayout linearLayoutInput = new LinearLayout(activity); linearLayoutDescription.setOrientation(LinearLayout.HORIZONTAL); //normal text view for everything else inputView = new EditText(activity); LinearLayout.LayoutParams layoutParamsinputView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.9f); inputView.setLayoutParams(layoutParamsinputView); ((EditText) inputView).setMaxWidth(linearLayout.getWidth()); //workaround for bug in layout params linearLayoutInput.addView(inputView); //specify the expected input type final Class<?> type = option.getType(); if (type == Byte.class || type == Short.class || type == Integer.class || type == Long.class) { ((TextView) inputView).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED); ((TextView) inputView).setText(value != null ? value.toString() : "", TextView.BufferType.NORMAL); } else if (type == Float.class || type == Double.class) { ((TextView) inputView).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL); ((TextView) inputView).setText(value != null ? value.toString() : "", TextView.BufferType.NORMAL); } else if (value != null && value.getClass().isArray()) { Object[] objects; Class ofArray = value.getClass().getComponentType(); if (ofArray.isPrimitive()) { List ar = new ArrayList(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { if (value.getClass().getComponentType() == byte.class || value.getClass().getComponentType() == Byte.class) { // Apply mask to value to avoid bad representation as there is no unsigned datatype in java. ar.add((byte) (Array.get(value, i)) & 0xFF); } else { ar.add(Array.get(value, i)); } } objects = ar.toArray(); ((TextView) inputView).setInputType(InputType.TYPE_CLASS_TEXT); ((TextView) inputView).setText(Arrays.toString(objects), TextView.BufferType.NORMAL); } else if (String.class.isAssignableFrom(ofArray)) { objects = (Object[]) value; ((TextView) inputView).setInputType(InputType.TYPE_CLASS_TEXT); ((TextView) inputView).setText(Arrays.toString(objects), TextView.BufferType.NORMAL); } else { ((TextView) inputView).setInputType(InputType.TYPE_CLASS_TEXT); ((TextView) inputView).setText(value.toString(), TextView.BufferType.NORMAL); } } else if (type == FilePath.class || type == FolderPath.class) { ((TextView) inputView).setInputType(InputType.TYPE_CLASS_TEXT); String value_str = ""; if(value != null && type == FilePath.class) value_str = ((FilePath)value).value; else if(value != null && type == FolderPath.class) value_str = ((FolderPath)value).value; ((TextView) inputView).setText(value_str, TextView.BufferType.NORMAL); // FileChooserButton ImageButton fileChooserButton = new ImageButton(activity); fileChooserButton.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_insert_drive_file_black_24dp)); final TextView innerInputView = (TextView) inputView; fileChooserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String startPath = (innerInputView.getText().toString().isEmpty()) ? FileCons.SSJ_EXTERNAL_STORAGE : innerInputView.getText().toString(); FileChooser chooser = new FileChooser(activity, startPath, type == FolderPath.class, null) { @Override public void onResult(String path, File pathFile) { innerInputView.setText(path); } }; chooser.show(); } }); linearLayoutInput.addView(fileChooserButton); } else { ((TextView) inputView).setInputType(InputType.TYPE_CLASS_TEXT); ((TextView) inputView).setText(value != null ? value.toString() : "", TextView.BufferType.NORMAL); } ((EditText) inputView).addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { try { // Convert the representation 0-255 to a valid byte value. if (value instanceof byte[] || value instanceof Byte[]) { String[] strings = s.toString().replace("[", "").replace("]", "").split("\\s*,\\s*"); byte[] ar = new byte[strings.length]; for (int i = 0; i < strings.length; i++) { ar[i] = getByteFromUnsignedStringRepresentation(strings[i]); } option.setValue(Arrays.toString(ar)); } else { option.setValue(s.toString()); } } catch (IllegalArgumentException e) { Toast.makeText(activity, activity.getResources().getText(R.string.err_invalidOption), Toast.LENGTH_SHORT).show(); } } }); inputView = linearLayoutInput; } linearLayout.addView(inputView); return linearLayout; } private static byte getByteFromUnsignedStringRepresentation(String s) throws NumberFormatException { int intValue = Integer.parseInt(s); if (intValue < 0 || intValue > 255) { throw new NumberFormatException(); } return (byte) intValue; } }
12,858
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Listener.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/dialogs/Listener.java
/* * Listener.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.dialogs; /** * Created by Frank Gaibler on 21.03.2016. */ public abstract class Listener { public abstract void onPositiveEvent(Object[] o); public abstract void onNegativeEvent(Object[] o); }
1,575
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
AddDialog.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/dialogs/AddDialog.java
/* * AddDialog.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.dialogs; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.ExpandableListView; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import hcm.ssj.creator.R; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.core.SSJDescriptor; /** * A Dialog to confirm actions.<br> * Created by Frank Gaibler on 16.09.2015. */ public class AddDialog extends DialogFragment { private int titleMessage = R.string.app_name; private LinkedHashMap<String, ArrayList<Class>> hashMap = null; private ArrayList<Listener> alListeners = new ArrayList<>(); private ExpandableListView listView; //ExpandableListView doesn't track selected items correctly, so it is done manually private boolean[][] itemState = null; private int allItems = 0; /** * @param savedInstanceState Bundle * @return Dialog */ @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { if (hashMap == null) { throw new RuntimeException(); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(titleMessage); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { boolean written = false; if (hashMap != null) { int x = 0; for (Map.Entry<String, ArrayList<Class>> entry : hashMap.entrySet()) { int y = 0; ArrayList<Class> arrayList = entry.getValue(); for (Class clazz : arrayList) { if (itemState[x][y]) { written = true; PipelineBuilder.getInstance().add(SSJDescriptor.instantiate(clazz)); } y++; } x++; } } for (Listener listener : alListeners) { if (written) { listener.onPositiveEvent(null); } else { listener.onNegativeEvent(null); } } } } ); builder.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { for (Listener listener : alListeners) { listener.onNegativeEvent(null); } } } ); //set up input listView = new ExpandableListView(getContext()); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); setListListeners(); if (hashMap != null && hashMap.size() > 0) { ListAdapter listAdapter = new ListAdapter(getContext(), hashMap); listView.setAdapter(listAdapter); } builder.setView(listView); return builder.create(); } /** * ExpandableListView doesn't track selected items correctly, so it is done manually */ private void setListListeners() { listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition)); parent.setItemChecked(index, !parent.isItemChecked(index)); itemState[groupPosition][childPosition] = !itemState[groupPosition][childPosition]; return true; } }); listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { //get current position int currentPosition = 1; for (int i = 0; i < groupPosition; i++, currentPosition++) { if (listView.isGroupExpanded(i)) { currentPosition += listView.getExpandableListAdapter().getChildrenCount(i); } } //shift values as needed int children = listView.getExpandableListAdapter().getChildrenCount(groupPosition); if (listView.isGroupExpanded(groupPosition)) { //currently closing for (int i = currentPosition; i < allItems; i++) { listView.setItemChecked(i, listView.isItemChecked(i + children)); } } else { //currently expanding for (int i = allItems + 1; i > currentPosition; i--) { listView.setItemChecked(i, listView.isItemChecked(i - children)); } //set values for expanded group from memory for (int i = currentPosition, j = 0; j < children; i++, j++) { listView.setItemChecked(i, itemState[groupPosition][j]); } } return false; } }); } /** * @param title int */ public void setTitleMessage(int title) { this.titleMessage = title; } /** * @param clazzes Class[] */ public void setOption(ArrayList<Class> clazzes) { hashMap = new LinkedHashMap<>(); //get each package once HashSet<Package> hashSet = new HashSet<>(); for (Class clazz : clazzes) { hashSet.add(clazz.getPackage()); } //only show last part of the package name String[] packages = new String[hashSet.size()]; int count = 0; for (Package pack : hashSet) { String name = pack.getName(); packages[count++] = name.substring(name.lastIndexOf(".") + 1); } //sort packages by name and add them to map Arrays.sort(packages); for (String name : packages) { hashMap.put(name, new ArrayList<Class>()); } //sort classes by name Collections.sort(clazzes, new Comparator<Class>() { @Override public int compare(Class lhs, Class rhs) { return lhs.getSimpleName().compareTo(rhs.getSimpleName()); } }); //add every class to its corresponding package for (Class clazz : clazzes) { String name = clazz.getPackage().getName(); hashMap.get(name.substring(name.lastIndexOf(".") + 1)).add(clazz); } //create internal variables to save the state of the list itemState = new boolean[hashMap.size()][]; count = 0; allItems = 0; allItems += hashMap.size(); for (Map.Entry<String, ArrayList<Class>> entry : hashMap.entrySet()) { itemState[count++] = new boolean[entry.getValue().size()]; allItems += entry.getValue().size(); } } /** * @param listener Listener */ public void addListener(Listener listener) { alListeners.add(listener); } /** * @param listener Listener */ public void removeListener(Listener listener) { alListeners.remove(listener); } }
10,109
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FileDialog.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/dialogs/FileDialog.java
/* * FileDialog.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.dialogs; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Environment; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AlertDialog; import android.text.InputType; import android.util.SparseBooleanArray; import android.view.View; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import hcm.ssj.core.Log; import hcm.ssj.creator.R; import hcm.ssj.creator.core.SaveLoad; import hcm.ssj.creator.util.StrategyLoader; import hcm.ssj.creator.util.Util; /** * Dialog to save and choose files.<br> * Created by Frank Gaibler on 04.07.2016. */ public class FileDialog extends DialogFragment { public enum Type { SAVE, LOAD_PIPELINE, LOAD_STRATEGY, DELETE_PIPELINE } private Type type = Type.SAVE; private int titleMessage = R.string.app_name; private ArrayList<Listener> alListeners = new ArrayList<>(); private ListView listView; private EditText editText; private File[] xmlFiles = null; private static String lastFileName = ""; /** * @param savedInstanceState Bundle * @return Dialog */ @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(titleMessage); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { switch (type) { case SAVE: { String fileName = editText.getText().toString().trim(); lastFileName = fileName; File dir1 = new File(Environment.getExternalStorageDirectory(), Util.SSJ); File dir2 = new File(dir1.getPath(), Util.CREATOR); File dir3 = new File(dir2, Util.PIPELINES); if (!fileName.isEmpty() && (dir3.exists() || dir3.mkdirs())) { if (!fileName.endsWith(Util.SUFFIX)) { fileName += Util.SUFFIX; } File file = new File(dir3, fileName); if (isValidFileName(file) && SaveLoad.save(file)) { for (Listener listener : alListeners) { listener.onPositiveEvent(new File[]{file}); } return; } } for (Listener listener : alListeners) { listener.onNegativeEvent(new Boolean[]{false}); } return; } case LOAD_PIPELINE: { if (xmlFiles != null && xmlFiles.length > 0) { int pos = listView.getCheckedItemPosition(); if (pos > AbsListView.INVALID_POSITION) { if (SaveLoad.load(xmlFiles[pos])) { lastFileName = xmlFiles[pos].getName().replace(Util.SUFFIX, ""); for (Listener listener : alListeners) { listener.onPositiveEvent(new File[]{xmlFiles[pos]}); } return; } for (Listener listener : alListeners) { listener.onNegativeEvent(new Boolean[]{false}); } return; } } for (Listener listener : alListeners) { listener.onNegativeEvent(null); } } break; case LOAD_STRATEGY: { if (xmlFiles != null && xmlFiles.length > 0) { int pos = listView.getCheckedItemPosition(); if (pos > AbsListView.INVALID_POSITION) { if (new StrategyLoader(xmlFiles[pos]).load()) { for (Listener listener : alListeners) { listener.onPositiveEvent(new File[]{xmlFiles[pos]}); } return; } for (Listener listener : alListeners) { listener.onNegativeEvent(new Boolean[]{false}); } return; } } for (Listener listener : alListeners) { listener.onNegativeEvent(null); } } break; case DELETE_PIPELINE: { if (xmlFiles != null && xmlFiles.length > 0) { SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions(); for (int i = 0; i < listView.getCount(); i++) { if (sparseBooleanArray.get(i)) { if (!xmlFiles[i].delete()) { for (Listener listener : alListeners) { listener.onNegativeEvent(new Boolean[]{false}); } return; } } } for (Listener listener : alListeners) { listener.onPositiveEvent(null); } return; } for (Listener listener : alListeners) { listener.onNegativeEvent(null); } break; } } } } ); builder.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { for (Listener listener : alListeners) { listener.onNegativeEvent(null); } } } ); //set up the input switch (type) { case SAVE: { editText = new EditText(getContext()); editText.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START); editText.setInputType(InputType.TYPE_CLASS_TEXT); editText.setText(lastFileName); builder.setView(editText); break; } case LOAD_PIPELINE: case DELETE_PIPELINE: { File ssjDir = new File(Environment.getExternalStorageDirectory(), Util.SSJ); File creatorDir = new File(ssjDir.getPath(), Util.CREATOR); File piplineDir = new File(creatorDir.getPath(), Util.PIPELINES); ListView listView = getXmlFileListView(piplineDir); builder.setView(listView); break; } case LOAD_STRATEGY: { File ssjDir = new File(Environment.getExternalStorageDirectory(), Util.SSJ); File creatorDir = new File(ssjDir.getPath(), Util.CREATOR); File piplineDir = new File(creatorDir.getPath(), Util.STRATEGIES); ListView listView = getXmlFileListView(piplineDir); builder.setView(listView); break; } } return builder.create(); } private ListView getXmlFileListView(File directory) { listView = new ListView(getContext()); listView.setChoiceMode(type == Type.DELETE_PIPELINE ? ListView.CHOICE_MODE_MULTIPLE : ListView.CHOICE_MODE_SINGLE); xmlFiles = directory.listFiles(new FilenameFilter() { @Override public boolean accept(File folder, String name) { return name.toLowerCase().endsWith(Util.SUFFIX); } }); if (xmlFiles != null && xmlFiles.length > 0) { String[] ids = new String[xmlFiles.length]; for (int i = 0; i < ids.length; i++) { ids[i] = xmlFiles[i].getName(); } listView.setAdapter(new ArrayAdapter<>(getContext(), type == Type.DELETE_PIPELINE ? android.R.layout.simple_list_item_multiple_choice : android.R.layout.simple_list_item_single_choice, ids)); } else { listView.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_single_choice)); } return listView; } /** * @param title int */ public void setTitleMessage(int title) { this.titleMessage = title; } /** * @param type Type */ public void setType(Type type) { this.type = type; } /** * @param listener Listener */ public void addListener(Listener listener) { alListeners.add(listener); } /** * @param listener Listener */ public void removeListener(Listener listener) { alListeners.remove(listener); } /** * @param file File * @return boolean */ private boolean isValidFileName(File file) { try { file.createNewFile(); } catch (IOException ex) { Log.e("could not create file"); return false; } return true; } }
13,669
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ListAdapter.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/main/java/hcm/ssj/creator/dialogs/ListAdapter.java
/* * ListAdapter.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator.dialogs; import android.content.Context; import android.graphics.Typeface; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckedTextView; import android.widget.TextView; import java.util.ArrayList; import java.util.LinkedHashMap; /** * Adapter for expandable list view. <br> * Created by Frank Gaibler on 02.08.2016. */ class ListAdapter extends BaseExpandableListAdapter { private Context context; private String[] listDataHeader; private LinkedHashMap<String, ArrayList<Class>> mapDataChild; private static final int PADDING = 25; /** * @param context Context * @param mapDataChild LinkedHashMap */ public ListAdapter(Context context, LinkedHashMap<String, ArrayList<Class>> mapDataChild) { this.context = context; this.listDataHeader = mapDataChild.keySet().toArray(new String[mapDataChild.size()]); this.mapDataChild = mapDataChild; } /** * @param groupPosition int * @param childPosition int * @return Object */ @Override public Object getChild(int groupPosition, int childPosition) { return this.mapDataChild.get(this.listDataHeader[groupPosition]).get(childPosition).getSimpleName(); } /** * @param groupPosition int * @param childPosition int * @return long */ @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } /** * @param groupPosition int * @param childPosition int * @param isLastChild boolean * @param convertView View * @param parent ViewGroup * @return View */ @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String childText = (String) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(android.R.layout.simple_list_item_multiple_choice, null); } CheckedTextView txtListChild = (CheckedTextView) convertView; txtListChild.setPadding(PADDING, PADDING, PADDING, PADDING); txtListChild.setText(childText); return convertView; } /** * @param groupPosition int * @return int */ @Override public int getChildrenCount(int groupPosition) { return this.mapDataChild.get(this.listDataHeader[groupPosition]).size(); } /** * @param groupPosition int * @return Object */ @Override public Object getGroup(int groupPosition) { return this.listDataHeader[groupPosition]; } /** * @return int */ @Override public int getGroupCount() { return this.listDataHeader.length; } /** * @param groupPosition int * @return long */ @Override public long getGroupId(int groupPosition) { return groupPosition; } /** * @param groupPosition int * @param isExpanded boolean * @param convertView View * @param parent ViewGroup * @return View */ @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(android.R.layout.simple_expandable_list_item_1, null); } TextView lblListHeader = (TextView) convertView; lblListHeader.setPadding(lblListHeader.getPaddingLeft(), PADDING, lblListHeader.getPaddingRight(), PADDING); lblListHeader.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19); lblListHeader.setTypeface(null, Typeface.ITALIC); lblListHeader.setText(headerTitle); return convertView; } /** * @return boolean */ @Override public boolean hasStableIds() { return false; } /** * @param groupPosition int * @param childPosition int * @return boolean */ @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
6,042
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
testLinker.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/androidTest/java/hcm/ssj/creator/testLinker.java
/* * testLinker.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator; import android.app.Application; import android.test.ApplicationTestCase; import hcm.ssj.androidSensor.AndroidSensor; import hcm.ssj.androidSensor.AndroidSensorChannel; import hcm.ssj.core.Consumer; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Sensor; import hcm.ssj.core.SensorChannel; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.core.SSJDescriptor; import hcm.ssj.test.Logger; /** * Created by Frank Gaibler on 10.03.2016. */ public class testLinker extends ApplicationTestCase<Application> { //test length in milliseconds private final static int TEST_LENGTH = 2 * 5 * 1000; /** * */ public testLinker() { super(Application.class); } /** * @throws Exception */ public void testBuildAndLink() throws Exception { //scan content SSJDescriptor descriptor = SSJDescriptor.getInstance(); // Builder.getInstance().scan(this.getContext()); System.out.println(descriptor.sensors.get(0)); System.out.println(descriptor.sensorChannels.get(0)); System.out.println(descriptor.consumers.get(0)); // Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(2.0f); PipelineBuilder pipelineBuilder = PipelineBuilder.getInstance(); //select classes Sensor sensor = null; for (Class clazz : descriptor.sensors) { if (clazz.equals(AndroidSensor.class)) { sensor = (Sensor) SSJDescriptor.instantiate(clazz); break; } } SensorChannel sensorChannel = null; if (sensor != null) { for (Class clazz : descriptor.sensorChannels) { if (clazz.equals(AndroidSensorChannel.class)) { sensorChannel = (SensorChannel) SSJDescriptor.instantiate(clazz); break; } } } Consumer consumer = null; if (sensorChannel != null) { pipelineBuilder.add(sensor); pipelineBuilder.add(sensorChannel); pipelineBuilder.addStreamProvider(sensor, sensorChannel); for (Class clazz : descriptor.consumers) { if (clazz.equals(Logger.class)) { consumer = (Consumer) SSJDescriptor.instantiate(clazz); break; } } if (consumer != null) { pipelineBuilder.add(consumer); pipelineBuilder.addStreamProvider(consumer, sensorChannel); pipelineBuilder.setFrameSize(consumer, 1.0); pipelineBuilder.setDelta(consumer, 0); } } pipelineBuilder.buildPipe(); //start framework frame.start(); //run for two minutes long end = System.currentTimeMillis() + TEST_LENGTH; try { while (System.currentTimeMillis() < end) { Thread.sleep(1); } } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.release(); } }
4,629
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
StrategyLoaderTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/androidTest/java/hcm/ssj/creator/StrategyLoaderTest.java
/* * StrategyLoaderTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.creator; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Map; import hcm.ssj.core.Component; import hcm.ssj.creator.core.PipelineBuilder; import hcm.ssj.creator.util.StrategyLoader; import hcm.ssj.event.ThresholdClassEventSender; import hcm.ssj.feedback.AndroidTactileFeedback; import hcm.ssj.feedback.AuditoryFeedback; import hcm.ssj.feedback.Feedback; import hcm.ssj.feedback.FeedbackCollection; import hcm.ssj.feedback.VisualFeedback; import static junit.framework.Assert.assertTrue; @RunWith(AndroidJUnit4.class) @SmallTest public class StrategyLoaderTest { File strategyFile; @Before public void makeStrategyFile() throws IOException, XmlPullParserException { String strategyContent = "" + "<ssj xmlns=\"hcm.ssj\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"hcm.ssj http://hcmlab.github.io/ssj/res/feedback.xsd\">" + " <strategy>" + " <feedback type=\"audio\" level=\"0\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"0.0\" to=\"4.0\"/>" + " <action res=\"Creator/res/blop.mp3\" intensity=\"0.0\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"audio\" level=\"1\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"4.0\" to=\"13\"/>" + " <action res=\"Creator/res/blop.mp3\" intensity=\"0.5\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"audio\" level=\"2\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"13\" to=\"999\"/>" + " <action res=\"Creator/res/blop.mp3\" intensity=\"1.0\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"tactile\" device=\"Android\" level=\"0\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"0.0\" to=\"3\"/>" + " <action duration=\"0,100,100,100\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"tactile\" device=\"Android\" level=\"1\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"3\" to=\"12\"/>" + " <action duration=\"0,100,100,100\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"tactile\" device=\"Android\" level=\"2\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"12\" to=\"999\"/>" + " <action duration=\"0,200,100,200\" lockSelf=\"1000\"/>" + " </feedback>" + " <feedback type=\"visual\" position=\"0\" level=\"0\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"0.0\" to=\"3.0\"/>" + " <action res=\"Creator/res/orientation_low.png, Creator/res/thumb_negative.png\"/>" + " </feedback>" + " <feedback type=\"visual\" position=\"0\" level=\"1\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"3.0\" to=\"12.0\"/>" + " <action res=\"Creator/res/orientation_med.png, Creator/res/thumb_positive.png\"/>" + " </feedback>" + " <feedback type=\"visual\" position=\"0\" level=\"2\">" + " <condition type=\"BodyEnergy\" event=\"OverallActivation\" sender=\"SSJ\" from=\"12.0\" to=\"999.0\"/>" + " <action res=\"Creator/res/orientation_high.png, Creator/res/thumb_negative.png\"/>" + " </feedback>" + " </strategy>" + "</ssj>"; strategyFile = File.createTempFile("testStrategy", ".xml"); PrintWriter printWriter = new PrintWriter(strategyFile); printWriter.append(strategyContent); printWriter.close(); StrategyLoader strategyLoader = new StrategyLoader(strategyFile); strategyLoader.load(); } @Test public void testComponentsPresent() { PipelineBuilder pipelineBuilder = PipelineBuilder.getInstance(); /* ------ ThresholdClassEventSender's ------ */ List<Component> thresholdClassEventSenders = pipelineBuilder.getComponentsOfClass(PipelineBuilder.Type.Consumer, ThresholdClassEventSender.class); assertTrue(thresholdClassEventSenders.size() == 1); ThresholdClassEventSender thresholdClassEventSender = (ThresholdClassEventSender)thresholdClassEventSenders.get(0); assertTrue(Arrays.equals(thresholdClassEventSender.options.thresholds.get(), new float[]{0,3,4,12,13,999})); /* ------ FeedbackCollection ------ */ List<Component> feedbackCollections = pipelineBuilder.getComponentsOfClass(PipelineBuilder.Type.EventHandler, FeedbackCollection.class); assertTrue(feedbackCollections.size() == 1); /* ------ Feedbacks ------ */ List<Component> visualFeedbacks = pipelineBuilder.getComponentsOfClass(PipelineBuilder.Type.EventHandler, VisualFeedback.class); assertTrue(visualFeedbacks.size() == 3); for (Component visualFeedback : visualFeedbacks) { assertTrue(pipelineBuilder.isManagedFeedback(visualFeedback)); } List<Component> auditoryFeedbacks = pipelineBuilder.getComponentsOfClass(PipelineBuilder.Type.EventHandler, AuditoryFeedback.class); assertTrue(auditoryFeedbacks.size() == 3); for (Component auditoryFeedback : auditoryFeedbacks) { assertTrue(pipelineBuilder.isManagedFeedback(auditoryFeedback)); } List<Component> androidTactileFeedbacks = pipelineBuilder.getComponentsOfClass(PipelineBuilder.Type.EventHandler, AndroidTactileFeedback.class); assertTrue(androidTactileFeedbacks.size() == 3); for (Component androidTactileFeedback : androidTactileFeedbacks) { assertTrue(pipelineBuilder.isManagedFeedback(androidTactileFeedback)); } } @Test public void testComponentsOnRightLevel() { List<Component> feedbackCollections = PipelineBuilder.getInstance().getComponentsOfClass(PipelineBuilder.Type.EventHandler, FeedbackCollection.class); assertTrue(feedbackCollections.size() == 1); FeedbackCollection feedbackCollection = (FeedbackCollection) feedbackCollections.get(0); List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackList = feedbackCollection.getFeedbackList(); assertTrue(feedbackList.size() == 3); for (Map feedbackMap : feedbackList) { assertTrue(feedbackMap.size() == 3); } } @After public void deleteStrategyFile() { if (strategyFile != null) { strategyFile.delete(); } PipelineBuilder.getInstance().clear(); } }
8,252
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ApplicationTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/ssjcreator/src/androidTest/java/hcm/ssj/creator/ApplicationTest.java
/* * ApplicationTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.creator; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
1,699
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Invert.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Invert.java
/* * Invert.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * inverts a signal by subtracting it from a predefined value * * Created by Johnny on 01.04.2015. */ public class Invert extends Transformer { @Override public OptionList getOptions() { return options; } public class Options extends OptionList { public final Option<Float> max = new Option<>("max", 1.0f, Float.class, ""); /** * */ private Options() {addOptions();} } public final Options options = new Options(); public Invert() { _name = "Invert"; } @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { } @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { float[] out = stream_out.ptrF(); for(int i = 0; i < stream_in[0].dim; i++) { for(int j = 0; j < stream_in[0].num; j++) { int index = j * stream_in[0].dim + i; switch(stream_in[0].type) { case CHAR: out[index] = options.max.get() - (float)stream_in[0].ptrC()[index]; break; case SHORT: out[index] = options.max.get() - (float)stream_in[0].ptrS()[index]; break; case INT: out[index] = options.max.get() - (float)stream_in[0].ptrI()[index]; break; case FLOAT: out[index] = options.max.get() - stream_in[0].ptrF()[index]; break; case DOUBLE: out[index] = options.max.get() - (float)stream_in[0].ptrD()[index]; break; } } } } @Override public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException {} @Override public int getSampleDimension(Stream[] stream_in) { return stream_in[0].dim; } @Override public int getSampleNumber(int sampleNumber_in) { return sampleNumber_in; } @Override public int getSampleBytes(Stream[] stream_in) { return 4; //float } @Override public Cons.Type getSampleType(Stream[] stream_in) { switch(stream_in[0].type) { case CHAR: case SHORT: case INT: case FLOAT: case DOUBLE: return Cons.Type.FLOAT; default: Log.e("unsupported input type"); return Cons.Type.UNDEF; } } @Override public void describeOutput(Stream[] stream_in, Stream stream_out) { stream_out.desc = new String[stream_in[0].dim]; System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length); } }
4,557
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Butfilt.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Butfilt.java
/* * Butfilt.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.Util; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Created by Michael Dietz on 10.08.2015. */ public class Butfilt extends Transformer { @Override public OptionList getOptions() { return options; } public enum Type { LOW, HIGH, BAND } public class Options extends OptionList { public final Option<Type> type = new Option<>("type", Type.LOW, Type.class, ""); public final Option<Integer> order = new Option<>("order", 1, Integer.class, "Filter order"); public final Option<Boolean> norm = new Option<>("norm", true, Boolean.class, "Frequency values are normalized in interval [0..1], where 1 is the nyquist frequency (=half the sample rate)"); public final Option<Double> low = new Option<>("low", 0., Double.class, "Low cutoff frequency given either as normalized value in interval [0..1] or as an absolute value in Hz (see -norm)"); public final Option<Double> high = new Option<>("high", 1., Double.class, "High cutoff frequency given either as normalized value in interval [0..1] or as an absolute value in Hz (see -norm)"); public final Option<Boolean> zero = new Option<>("zero", true, Boolean.class, "Subtract first sample from signal to avoid artifacts at the beginning of the signal"); /** * */ private Options() { addOptions(); } } public final Options options = new Options(); IIR _iir; Matrix<Float> _coefficients; float[] _firstSample; boolean _firstCall; public Butfilt() { _name = "Butfilt"; } protected Matrix<Float> getCoefficients(double sr) { double low = options.norm.get() ? options.low.get() : 2 * options.low.get() / sr; double high = options.norm.get() ? options.high.get() : 2 * options.high.get() / sr; return initCoefficients(options.type.get(), options.order.get(), low, high); } protected Matrix<Float> initCoefficients(Type type, int order, double low, double high) { Matrix<Float> coefficients = null; switch (type) { case LOW: coefficients = FilterTools.getInstance().getLPButter(order, low); break; case HIGH: coefficients = FilterTools.getInstance().getHPButter(order, high); break; case BAND: coefficients = FilterTools.getInstance().getBPButter(order, low, high); break; } return coefficients; } @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { _coefficients = getCoefficients(stream_in[0].sr); _iir = new IIR(); _iir.setCoefficients(_coefficients); _iir.enter(stream_in, stream_out); _firstCall = true; } @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { if (_firstCall) { if (options.zero.get()) { _firstSample = new float[stream_in[0].dim]; System.arraycopy(stream_in[0].ptrF(), 0, _firstSample, 0, stream_in[0].dim); } _firstCall = false; } if (_firstSample != null) { float[] ptr = stream_in[0].ptrF(); int ptrIndex = 0; for (int i = 0; i < stream_in[0].num; i++) // TODO SSI: info.frame_num? { for (int j = 0; j < stream_in[0].dim; j++) { ptr[ptrIndex++] -= _firstSample[j]; } } } _iir.transform(stream_in, stream_out); if (_firstSample != null) { float[] ptr = stream_out.ptrF(); int ptrIndex = 0; for (int i = 0; i < stream_in[0].num; i++) // TODO SSI: info.frame_num? { for (int j = 0; j < stream_in[0].dim; j++) { ptr[ptrIndex++] += _firstSample[j]; } } } } @Override public int getSampleDimension(Stream[] stream_in) { return stream_in[0].dim; } @Override public int getSampleBytes(Stream[] stream_in) { return Util.sizeOf(Cons.Type.FLOAT); // Float } @Override public Cons.Type getSampleType(Stream[] stream_in) { if (stream_in[0].type != Cons.Type.FLOAT) { Log.e("unsupported input type"); } return Cons.Type.FLOAT; } @Override public int getSampleNumber(int sampleNumber_in) { return sampleNumber_in; } @Override public void describeOutput(Stream[] stream_in, Stream stream_out) { stream_out.desc = new String[stream_in[0].dim]; System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length); } }
5,750
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Derivative.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Derivative.java
/* * Derivative.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.Util; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Transformer to calculate derivative of signal data.<br> * Created by Ionut Damian on 01.02.2017. Based on Derivative plugin from SSI. */ public class Derivative extends Transformer { @Override public OptionList getOptions() { return options; } /** * All options for the transformer */ public class Options extends OptionList { public final Option<Boolean> zero = new Option<>("zero", true, Boolean.class, "pass along the untransformed stream"); public final Option<Boolean> first = new Option<>("first", true, Boolean.class, "compute first derivative"); public final Option<Boolean> second = new Option<>("second", true, Boolean.class, "compute second derivative"); public final Option<Boolean> third = new Option<>("third", true, Boolean.class, "compute third derivative"); public final Option<Boolean> fourth = new Option<>("fourth", true, Boolean.class, "compute fourth derivative"); /** * */ private Options() { addOptions(); } } public final Options options = new Options(); private float[] history; private int depth = 0; private boolean first_call; private boolean[] store_value = new boolean[5]; /** * */ public Derivative() { _name = this.getClass().getSimpleName(); } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { if (options.fourth.get()) store_value[4] = true; if (options.third.get()) store_value[3] = true; if (options.second.get()) store_value[2] = true; if (options.first.get()) store_value[1] = true; if (options.zero.get()) store_value[0] = true; for (int i = 0; i <= 4; i++) { if (store_value[i]) depth = i; } depth++; history = new float[(depth - 1) * stream_in[0].dim]; first_call = true; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { int sample_dimension = stream_in[0].dim; int sample_number = stream_in[0].num; float src[] = stream_in[0].ptrF(); float dst[] = stream_out.ptrF(); float tmp, tmp2; // initialize history during first call if (first_call) { for (int i = 0; i < sample_dimension; ++i) { for (int j = 0; j < depth-1; j++) { history[i*(depth-1) + j] = j == 0 ? src[i] : 0; } } first_call = false; } // calculate derivative int srccnt = 0; int dstcnt = 0; for (int i = 0; i < sample_number; i++) { int histcnt = 0; for (int j = 0; j < sample_dimension; j++) { tmp = src[srccnt++]; if (store_value[0]) { dst[dstcnt++] = tmp; } for (int k = 1; k < depth; k++) { tmp2 = tmp; tmp -= history[histcnt]; history[histcnt++] = tmp2; if (store_value[k]) { dst[dstcnt++] = tmp; } } } } } @Override public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException { history = null; store_value = null; } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleDimension(Stream[] stream_in) { int dim = 0; if (options.fourth.get()) dim++; if (options.third.get()) dim++; if (options.second.get()) dim++; if (options.first.get()) dim++; if (options.zero.get()) dim++; return dim * stream_in[0].dim; } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleBytes(Stream[] stream_in) { return Util.sizeOf(Cons.Type.FLOAT); } /** * @param stream_in Stream[] * @return Cons.Type */ @Override public Cons.Type getSampleType(Stream[] stream_in) { return Cons.Type.FLOAT; } /** * @param sampleNumber_in int * @return int */ @Override public int getSampleNumber(int sampleNumber_in) { return sampleNumber_in; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override protected void describeOutput(Stream[] stream_in, Stream stream_out) { int overallDimension = getSampleDimension(stream_in); stream_out.desc = new String[overallDimension]; for (int i = 0; i < stream_in[0].dim; i++) { int j = 0; if (options.zero.get()) stream_out.desc[j++] = stream_in[0].desc[i]; if (options.first.get()) stream_out.desc[j] = stream_in[0].desc[i] + ".d" + j++; if (options.second.get()) stream_out.desc[j] = stream_in[0].desc[i] + ".d" + j++; if (options.third.get()) stream_out.desc[j] = stream_in[0].desc[i] + ".d" + j++; if (options.fourth.get()) stream_out.desc[j] = stream_in[0].desc[i] + ".d" + j; } } }
7,023
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Avg.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Avg.java
/* * Avg.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Computes the average/mean for each dimension of the input signal * * Created by Johnny on 01.04.2015. */ public class Avg extends Transformer { @Override public OptionList getOptions() { return options; } public class Options extends OptionList { /** * */ private Options() {addOptions();} } public final Options options = new Options(); public Avg() { _name = "Avg"; } @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { } @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { float[] out = stream_out.ptrF(); float sum; for(int i = 0; i < stream_in[0].dim; i++) { sum = 0; for(int j = 0; j < stream_in[0].num; j++) { int index = j * stream_in[0].dim + i; switch(stream_in[0].type) { case CHAR: sum += (float)stream_in[0].ptrC()[index]; break; case SHORT: sum += (float)stream_in[0].ptrS()[index]; break; case INT: sum += (float)stream_in[0].ptrI()[index]; break; case FLOAT: sum += stream_in[0].ptrF()[index]; break; case DOUBLE: sum += (float)stream_in[0].ptrD()[index]; break; } } out[i] = sum / stream_in[0].num; } } @Override public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException {} @Override public int getSampleDimension(Stream[] stream_in) { return stream_in[0].dim; } @Override public int getSampleNumber(int sampleNumber_in) { return 1; } @Override public int getSampleBytes(Stream[] stream_in) { return 4; //float } @Override public Cons.Type getSampleType(Stream[] stream_in) { switch(stream_in[0].type) { case CHAR: case SHORT: case INT: case FLOAT: case DOUBLE: return Cons.Type.FLOAT; default: Log.e("unsupported input type"); return Cons.Type.UNDEF; } } @Override public void describeOutput(Stream[] stream_in, Stream stream_out) { stream_out.desc = new String[stream_in[0].dim]; System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length); } }
4,372
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PSD.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/PSD.java
/* * PSD.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import org.jtransforms.fft.FloatFFT_1D; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.Util; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Calculates probability density function (PSD) or entropy. <br> * Created by Frank Gaibler on 10.01.2017. */ public class PSD extends Transformer { @Override public OptionList getOptions() { return options; } /** * All options for the transformer */ public class Options extends OptionList { public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph"); public final Option<Boolean> entropy = new Option<>("entropy", false, Boolean.class, "Calculate entropy instead of PSD"); public final Option<Boolean> normalize = new Option<>("normalize", false, Boolean.class, "Normalize PSD"); /** * */ private Options() { addOptions(); } } public final Options options = new Options(); //helper variables private FloatFFT_1D fft; private float[] copy, psd; /** * */ public PSD() { _name = this.getClass().getSimpleName(); } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { if (stream_in.length != 1 || stream_in[0].dim != 1 || stream_in[0].type != Cons.Type.FLOAT) { Log.e("invalid input stream"); } fft = new FloatFFT_1D(stream_in[0].num); copy = new float[stream_in[0].num]; psd = new float[stream_in[0].num / 2 + 1]; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException { super.flush(stream_in, stream_out); fft = null; copy = null; psd = null; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { int rfft = psd.length; float[] ptr_in = stream_in[0].ptrF(), ptr_out = stream_out.ptrF(); float fde = 0; // Copy data for FFT System.arraycopy(ptr_in, 0, copy, 0, stream_in[0].num); // 1. Calculate FFT fft.realForward(copy); // Format values like in SSI joinFFT(copy); if (rfft > 0) { // 2. Calculate Power Spectral Density for (int i = 0; i < rfft; i++) { psd[i] = (float) Math.pow(psd[i], 2) / (float) (rfft); } if (options.entropy.get() || options.normalize.get()) { float psdSum = getSum(psd); if (psdSum > 0) { if (options.entropy.get() || options.normalize.get()) { // 3. Normalize calculated PSD so that it can be viewed as a Probability Density Function for (int i = 0; i < rfft; i++) { psd[i] = psd[i] / psdSum; } } if (options.entropy.get()) { // 4. Calculate the Frequency Domain Entropy for (float val : psd) { if (val != 0) { fde += val * Math.log(val); } } fde *= -1; } } } if (!options.entropy.get()) { //return psd System.arraycopy(psd, 0, ptr_out, 0, rfft); } } //return entropy if (options.entropy.get()) { ptr_out[0] = fde; } } /** * calculates the sum of all values * * @param values float[] * @return float */ private float getSum(float[] values) { float sum = 0; for (float val : values) { sum += val; } return sum; } /** * Helper function to format fft values similar to SSI * * @param fft float[] */ private void joinFFT(float[] fft) { for (int i = 0; i < fft.length; i += 2) { if (i == 0) { psd[0] = fft[0]; psd[1] = fft[1]; } else { psd[i / 2 + 1] = (float) Math.sqrt(Math.pow(fft[i], 2) + Math.pow(fft[i + 1], 2)); } } } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleDimension(Stream[] stream_in) { return 1; } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleBytes(Stream[] stream_in) { return Util.sizeOf(Cons.Type.FLOAT); } /** * @param stream_in Stream[] * @return Cons.Type */ @Override public Cons.Type getSampleType(Stream[] stream_in) { return Cons.Type.FLOAT; } /** * @param sampleNumber_in int * @return int */ @Override public int getSampleNumber(int sampleNumber_in) { if (options.entropy.get()) { return 1; } else { return sampleNumber_in / 2 + 1; } } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override protected void describeOutput(Stream[] stream_in, Stream stream_out) { int overallDimension = getSampleDimension(stream_in); stream_out.desc = new String[overallDimension]; if (options.outputClass.get() != null && overallDimension == options.outputClass.get().length) { System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length); } else { if (options.outputClass.get() != null && overallDimension != options.outputClass.get().length) { Log.w("invalid option outputClass length"); } for (int i = 0; i < overallDimension; i++) { stream_out.desc[i] = "psd" + i; } } } }
8,137
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FFTfeat.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/FFTfeat.java
/* * FFTfeat.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import org.jtransforms.fft.FloatFFT_1D; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.Util; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Created by Michael Dietz on 18.10.2016. */ public class FFTfeat extends Transformer { private FloatFFT_1D fft; private float[][] fft_in; private float[][] fft_out; private int fft_dim = 0; private int fft_size = 0; private int rfft = 0; public FFTfeat() { _name = this.getClass().getSimpleName(); } @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { fft_dim = stream_in[0].dim; fft_size = stream_in[0].num; fft = new FloatFFT_1D(fft_size); fft_out = new float[fft_dim][]; fft_in = new float[fft_dim][]; for(int i = 0; i < fft_dim; i++){ fft_in[i]= new float[fft_size]; fft_out[i] = new float[rfft]; } } @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { float[] in = stream_in[0].ptrF(); float[] out = stream_out.ptrF(); for (int j = 0; j < fft_size; j++) { for (int i = 0; i < fft_dim; i++) { if (j < stream_in[0].num){ fft_in[i][j] = in[j * fft_dim + i]; } else { fft_in[i][j] = 0; } } } for (int i = 0; i < fft_dim; i++) { // Calculate FFT fft.realForward(fft_in[i]); // Format values like in SSI Util.joinFFT(fft_in[i], fft_out[i]); } for (int j = 0; j < rfft; j++){ for (int i = 0; i < fft_dim; i++){ out[j * fft_dim + i] = fft_out[i][j]; } } } @Override public int getSampleDimension(Stream[] stream_in) { rfft = ((stream_in[0].num >> 1) + 1); return stream_in[0].dim * rfft; } @Override public int getSampleBytes(Stream[] stream_in) { return stream_in[0].bytes; } @Override public Cons.Type getSampleType(Stream[] stream_in) { if(stream_in[0].type != Cons.Type.FLOAT) { Log.e("Unsupported input stream type"); } return Cons.Type.FLOAT; } @Override public int getSampleNumber(int sampleNumber_in) { return 1; } @Override protected void describeOutput(Stream[] stream_in, Stream stream_out) { stream_out.desc = new String[]{"fft"}; } @Override public OptionList getOptions() { return null; } }
3,703
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
Count.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Count.java
/* * Count.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library 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 any later version. * * This library 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 this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.Util; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Counts high values. * Created by Frank Gaibler on 31.08.2015. */ public class Count extends Transformer { @Override public OptionList getOptions() { return options; } /** * All options for the transformer */ public class Options extends OptionList { public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph"); public final Option<Boolean> frameCount = new Option<>("frameCount", true, Boolean.class, "Global or frame count"); public final Option<Boolean> divideByNumber = new Option<>("divideByNumber", false, Boolean.class, "Divide through number of values to be comparable"); /** * */ private Options() { addOptions(); } } public final Options options = new Options(); //helper variables private float[] oldValues; private int counter = 0; /** * */ public Count() { _name = this.getClass().getSimpleName(); } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { //no check for a specific type to allow for different providers if (stream_in.length < 1 || stream_in[0].dim < 1) { Log.e("invalid input stream"); } //every stream should have the same sample number int num = stream_in[0].num; for (int i = 1; i < stream_in.length; i++) { if (num != stream_in[i].num) { Log.e("invalid input stream num for stream " + i); } } oldValues = new float[stream_out.dim]; counter = 0; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { float[] out = stream_out.ptrF(); if (options.frameCount.get()) { oldValues = new float[stream_out.dim]; } for (int i = 0; i < stream_in[0].num; i++) { int t = 0; for (Stream aStream_in : stream_in) { for (int k = 0; k < aStream_in.dim; k++, t++) { float value = aStream_in.ptrF()[i * aStream_in.dim + k]; if (value > 0) { oldValues[t]++; } } } } //write to output if (options.divideByNumber.get()) { float divider = options.frameCount.get() ? stream_in[0].num : ++counter * stream_in[0].num; for (int i = 0; i < oldValues.length; i++) { out[i] = oldValues[i] / divider; } } else { System.arraycopy(oldValues, 0, out, 0, oldValues.length); } } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleDimension(Stream[] stream_in) { int overallDimension = 0; for (Stream stream : stream_in) { overallDimension += stream.dim; } return overallDimension; } /** * @param stream_in Stream[] * @return int */ @Override public int getSampleBytes(Stream[] stream_in) { return Util.sizeOf(Cons.Type.FLOAT); } /** * @param stream_in Stream[] * @return Cons.Type */ @Override public Cons.Type getSampleType(Stream[] stream_in) { return Cons.Type.FLOAT; } /** * @param sampleNumber_in int * @return int */ @Override public int getSampleNumber(int sampleNumber_in) { return 1; } /** * @param stream_in Stream[] * @param stream_out Stream */ @Override protected void describeOutput(Stream[] stream_in, Stream stream_out) { int overallDimension = getSampleDimension(stream_in); stream_out.desc = new String[overallDimension]; if (options.outputClass.get() != null) { if (overallDimension == options.outputClass.get().length) { System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length); return; } else { Log.w("invalid option outputClass length"); } } for (int i = 0, k = 0; i < stream_in.length; i++) { for (int j = 0; j < stream_in[i].dim; j++, k++) { stream_out.desc[k] = "cnt" + i + "." + j; } } } }
6,487
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z